diff --git a/ChangeLog b/ChangeLog
index 31ddbd56bddfc7d8f2697712a32e317ce944cc84..3eb284ccc801e261191dc9927af1303d7facfb7d 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -13,7 +13,9 @@ Following changes may create regression for some external modules, but were nece
 * The page compta/facture.php was renamed into compta/facture/card.php to match page naming conventions.
 * The signature of method ->delete() of class Product and PriceExpression was changed from 
   ->delete($id, notrigger) to ->delete(User, notrigger) to match standard dev rules.
-
+* Removed CommonObject::displayMarginInfos (was deprecated in 3.8). Use same method into
+  html.formmargin.class.php
+* Removed Societe::set_commnucation_level (was deprecated in 4.0). Was not used.
 
 ***** ChangeLog for 5.0.1 compared to 5.0.0 *****
 FIX: #6503: SQL error in "Last pending payment invoices"
diff --git a/build/debian/README.howto b/build/debian/README.howto
index 705899d47c4898f5138b842cb2255d60936c258f..c94309ec2ef7ea21f44e3bbb9223911443ae8cfe 100644
--- a/build/debian/README.howto
+++ b/build/debian/README.howto
@@ -152,7 +152,7 @@ tag 729538 -moreinfo
 
 
 
-##### Testing a package into unstable env
+##### Testing a package into a chroot environment
 
 Check you have a mysql server available from another interface than "localhost".
 Set line in /etc/mysql/my.cnf if required and restart mysql
@@ -160,9 +160,11 @@ Set line in /etc/mysql/my.cnf if required and restart mysql
 [mysqld]
 bind-address           = *
 
-Create a chroot called "unstable-amd64-sbuild".
+Create a chroot called "jessie" or "unstable".
 Chroot env is stored into /srv/chroot directory.
 > sudo sbuild-createchroot --keyring=unstable /srv/chroot/unstable http://ftp.uk.debian.org/debian
+or
+> sudo sbuild-createchroot jessie /srv/chroot/jessie http://ftp.uk.debian.org/debian
 
 Pour lister les env chroot
 > schroot -l
@@ -170,8 +172,9 @@ or
 > ls /srv/chroot
 
 Puis pour se connecter et préparer l'environnement 
-> schroot -c name_of_chroot
+> schroot -c name_of_chroot  (exemple schroot -c unstable-amd64-sbuild)
 > cat /etc/debian_chroot       to check which debian branch we are into
+> apt-get install vi dialog
 > vi /usr/sbin/policy-rc.d     and replace return code 101 (not allowed) into 0 (ok)
 > apt-get update
 > apt-get upgrade
@@ -385,13 +388,14 @@ http://packages.qa.debian.org
 * Package will be into release when test will be moved as stable.
 
 
-##### Send an unblock request 
+
+##### Send an unblock request to make a full update of a stable package 
 
 Use this to move from unstable to testing.
 
 reportbug -B debian --smtphost=smtp.gmail.com:587 --smtpuser=xxxx --smtppasswd=yyyy --tls
 Choose package "release.debian.org"
-Then "unblock"
+Then usertag "unblock"
 Then name of package "dolibarr"
 Fill message, for example:
 "Please unblock package dolibarr
@@ -401,11 +405,11 @@ so it is a better solution to validate this maintenance release than applying a
 After discussion with ..., it appears that security holes are enough to request this unblock request."
 
 
-Use this to request an update of a stable package
+Use this to request an full update of a stable package
 
 reportbug -B debian --smtphost=smtp.gmail.com:587 --smtpuser=xxxx --smtppasswd=yyyy --tls
 Choose package "release.debian.org"
-Then "unblock"
+Then usertag "unblock"
 Then name of package "dolibarr"
 Fill message, for example:
 "
@@ -417,11 +421,26 @@ Pro are:
 - It fixes also stability bugs
 - Patches were already tested because deployed and used by several thousands of users.
 - It is easier for package maintener to include this official set of fixes than applying one patch after one patch for each debian report or backported each patch into a dedicated version.
-- Debian maintenance version matches with official project maintenance version (better when all fixes are not related to the way the software is packaged)
+- Debian maintenance version is inline with official project maintenance version (better when all fixes are not related to the way the software is packaged)
 Cons are: 
-- The patch include more than the only one security reported fxes
+- The patch include more than the only one security reported fixes
 
 So I just need to know if it's ok to push such a version 3.5.7 (fixes for 3.5.* branch) instead of only one fix for only the few (the only) reported debian bugs,
 since it provides more stability and is for me a more secured process.
 "
 
+##### Send an request to ask a simple fix of a stable package 
+
+Use this to ask to apply patches on a stable version.
+
+reportbug -B debian --smtphost=smtp.gmail.com:587 --smtpuser=xxxx --smtppasswd=yyyy --tls
+Choose package "release.debian.org"
+Then usertag "jessie-pu" (if tags is not available in list, choose another one, and change it later into email content text)
+Then name of package "dolibarr"
+Fill message, for example:
+"Please unblock package dolibarr
+A security error CVE-2015-3935 was reported and is fixed into package 3.5.7.
+Note that package 3.5.7 contains not only fixed for bugs reported to debian. It includes other fixes, but they are all related to stability or security,
+so it is a better solution to validate this maintenance release than applying a patch of the only CVE-2015-3935. 
+After discussion with ..., it appears that security holes are enough to request this unblock request."
+
diff --git a/htdocs/accountancy/admin/accountmodel.php b/htdocs/accountancy/admin/accountmodel.php
index 0b4aa70e54820f41d417db38ad7e0f5fce54e045..55c194cd4169125428ea5da54e99ef5ec2aa74af 100644
--- a/htdocs/accountancy/admin/accountmodel.php
+++ b/htdocs/accountancy/admin/accountmodel.php
@@ -757,8 +757,7 @@ if ($id)
         {
         	print '<tr><td colspan="8">* '.$langs->trans("AvailableVariables").": ";
         	require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
-        	$formmail=new FormMail($db);
-        	$tmp=$formmail->getAvailableSubstitKey('form');
+        	$tmp=FormMail::getAvailableSubstitKey('formemail');
         	print implode(', ', $tmp);
         	print '</td></tr>';
         }
diff --git a/htdocs/accountancy/admin/journals.php b/htdocs/accountancy/admin/journals.php
deleted file mode 100644
index 677f2a743e51f687bd3e25aaf5cbc19c08f651fc..0000000000000000000000000000000000000000
--- a/htdocs/accountancy/admin/journals.php
+++ /dev/null
@@ -1,168 +0,0 @@
-<?php
-/* Copyright (C) 2017		Alexandre Spangaro   <aspangaro@zendsi.com>
- *
- * This program 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.
- *
- * This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
- *
- */
-
-/**
- * \file		htdocs/accountancy/admin/journals.php
- * \ingroup		Advanced accountancy
- * \brief		Setup page to configure journals
- */
-require '../../main.inc.php';
-require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php';
-require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php';
-require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingjournal.class.php';
-
-$action = GETPOST('action');
-
-// Load variable for pagination
-$limit = GETPOST("limit")?GETPOST("limit","int"):$conf->liste_limit;
-$sortfield = GETPOST('sortfield','alpha');
-$sortorder = GETPOST('sortorder','alpha');
-$page = GETPOST('page','int');
-if ($page == -1) { $page = 0; }
-$offset = $limit * $page;
-$pageprev = $page - 1;
-$pagenext = $page + 1;
-if (! $sortfield) $sortfield="j.rowid"; // Set here default search field
-if (! $sortorder) $sortorder="ASC";
-
-$langs->load("admin");
-$langs->load("compta");
-$langs->load("accountancy");
-
-// Security check
-if ($user->societe_id > 0)
-	accessforbidden();
-if (! $user->rights->accounting->fiscalyear)              // If we can read accounting records, we shoul be able to see fiscal year.
-    accessforbidden();
-	
-$error = 0;
-
-// List of status
-/*
-static $tmptype2label = array (
-		'0' => 'AccountingJournalTypeVariousOperation',
-		'1' => 'AccountingJournalTypeSale',
-		'2' => 'AccountingJournalTypePurchase',
-		'3' => 'AccountingJournalTypeBank',
-		'9' => 'AccountingJournalTypeHasNew'
-);
-$type2label = array (
-		'' 
-);
-foreach ( $tmptype2label as $key => $val )
-	$type2label[$key] = $langs->trans($val);
-*/
-
-$errors = array ();
-
-$object = new AccountingJournal($db);
-
-
-/*
- * Actions
- */
-
-
-
-/*
- * View
- */
-$title = $langs->trans('AccountingJournals');
-$helpurl = "";
-llxHeader('', $title, $helpurl);
-
-$max = 100;
-$form = new Form($db);
-
-$linkback = '<a href="' . DOL_URL_ROOT . '/admin/modules.php">' . $langs->trans("BackToModuleList") . '</a>';
-print load_fiche_titre($langs->trans('ConfigAccountingExpert'), $linkback, 'title_setup');
-
-$head = admin_accounting_prepare_head(null);
-
-dol_fiche_head($head, 'journal', $langs->trans("Configuration"), -1, 'cron');
-
-$sql = "SELECT j.rowid, j.code, j.label, j.nature, j.active";
-$sql .= " FROM " . MAIN_DB_PREFIX . "accounting_journal as j";
-// $sql .= " WHERE j.entity = " . $conf->entity;
-$sql.=$db->order($sortfield,$sortorder);
-
-// Count total nb of records
-$nbtotalofrecords = '';
-if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
-{
-	$result = $db->query($sql);
-	$nbtotalofrecords = $db->num_rows($result);
-}
-
-$sql.= $db->plimit($limit+1, $offset);
-
-$result = $db->query($sql);
-if ($result) {
-	$num = $db->num_rows($result);
-
-	$i = 0;
-
-	// $title = $langs->trans('AccountingJournals');
-	// print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $params, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_accountancy', 0, '', '', $limit, 1);
-
-	// Load attribute_label
-	print '<table class="noborder" width="100%">';
-	print '<tr class="liste_titre">';
-	// print '<td>' . $langs->trans("Ref") . '</td>';
-	print '<td>' . $langs->trans("Code") . '</td>';
-	print '<td>' . $langs->trans("Label") . '</td>';
-	print '<td>' . $langs->trans("Nature") . '</td>';
-	print '</tr>';
-
-	if ($num) {
-		$accountingjournalstatic = new AccountingJournal($db);
-
-		while ( $i < $num && $i < $max ) {
-			$obj = $db->fetch_object($result);
-			$accountingjournalstatic->id = $obj->rowid;
-			print '<tr class="oddeven">';
-			print '<td><a href="journals_card.php?id=' . $obj->rowid . '">' . img_object($langs->trans("ShowJournal"), "technic") . ' ' . $obj->code . '</a></td>';
-			print '<td align="left">' . $obj->label . '</td>';
-			print '<td>' . $accountingjournalstatic->LibType($obj->nature, 0) . '</td>';
-			print '</tr>';
-			$i ++;
-		}
-	} else {
-		print '<tr class="oddeven"><td colspan="3" class="opacitymedium">' . $langs->trans("None") . '</td></tr>';
-	}
-	print '</table>';
-} else {
-	dol_print_error($db);
-}
-
-dol_fiche_end();
-
-// Buttons
-print '<div class="tabsAction">';
-if (! empty($user->rights->accounting->fiscalyear))
-{
-    print '<a class="butAction" href="journals_card.php?action=create">' . $langs->trans("NewAccountingJournal") . '</a>';
-}
-else
-{
-    print '<a class="butActionRefused" href="#">' . $langs->trans("NewAccountingJournal") . '</a>';
-}
-print '</div>';
-
-llxFooter();
-$db->close();
\ No newline at end of file
diff --git a/htdocs/accountancy/admin/journals_card.php b/htdocs/accountancy/admin/journals_card.php
deleted file mode 100644
index 9e04d75ce9f1260125ceec52608c02139e35127a..0000000000000000000000000000000000000000
--- a/htdocs/accountancy/admin/journals_card.php
+++ /dev/null
@@ -1,294 +0,0 @@
-<?php
-/* Copyright (C) 2017		Alexandre Spangaro	<aspangaro@zendsi.com>
- *
- * This program 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.
- *
- * This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-/**
- * \file        htdocs/accountancy/admin/journals_card.php
- * \ingroup     Advanced accountancy
- * \brief       Page to show an accounting journal
- */
-require '../../main.inc.php';
-
-require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php';
-require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingjournal.class.php';
-
-$langs->load("admin");
-$langs->load("compta");
-$langs->load("accountancy");
-
-// Security check
-if ($user->societe_id > 0)
-	accessforbidden();
-if (empty($user->rights->accounting->fiscalyear))
-	accessforbidden();
-
-$error = 0;
-
-$action = GETPOST('action', 'alpha');
-$confirm = GETPOST('confirm', 'alpha');
-$id = GETPOST('id', 'int');
-
-// List of status
-static $tmptype2label = array (
-		'0' => 'AccountingJournalTypeVariousOperation',
-		'1' => 'AccountingJournalTypeSale',
-		'2' => 'AccountingJournalTypePurchase',
-		'3' => 'AccountingJournalTypeBank',
-		'9' => 'AccountingJournalTypeHasNew'
-);
-$type2label = array (
-		'' 
-);
-foreach ( $tmptype2label as $key => $val )
-	$type2label[$key] = $langs->trans($val);
-
-$object = new AccountingJournal($db);
-
-/*
- * Actions
- */
-
-if ($action == 'confirm_delete' && $confirm == "yes") {
-	$result = $object->delete($id);
-	if ($result >= 0) {
-		header("Location: journals.php");
-		exit();
-	} else {
-		setEventMessages($object->error, $object->errors, 'errors');
-	}
-} 
-
-else if ($action == 'add') {
-	if (! GETPOST('cancel', 'alpha')) {
-		$error = 0;
-
-		$object->code = GETPOST('code', 'alpha');
-		$object->label = GETPOST('label', 'alpha');
-		$object->nature = GETPOST('nature', 'int');
-
-		if (empty($object->code)) {
-			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Code")), null, 'errors');
-			$error ++;
-		}
-		if (empty($object->label)) {
-			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors');
-			$error ++;
-		}
-
-		if (! $error) {
-			$db->begin();
-
-			$id = $object->create($user);
-
-			if ($id > 0) {
-				$db->commit();
-
-				header("Location: " . $_SERVER["PHP_SELF"] . "?id=" . $id);
-				exit();
-			} else {
-				$db->rollback();
-
-				setEventMessages($object->error, $object->errors, 'errors');
-				$action = 'create';
-			}
-		} else {
-			$action = 'create';
-		}
-	} else {
-		header("Location: ./journals.php");
-		exit();
-	}
-} 
-
-// Update record
-else if ($action == 'update') {
-	if (! GETPOST('cancel', 'alpha')) {
-		$result = $object->fetch($id);
-
-		$object->code = GETPOST('code', 'alpha');
-		$object->label = GETPOST('label', 'alpha');
-		$object->nature = GETPOST('nature', 'int');
-
-		if (empty($object->code)) {
-			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Code")), null, 'errors');
-			$error ++;
-		}
-		if (empty($object->label)) {
-			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors');
-			$error ++;
-		}
-
-		$result = $object->update($user);
-		
-		if ($result > 0) {
-			header("Location: " . $_SERVER["PHP_SELF"] . "?id=" . $id);
-			exit();
-		} else {
-			setEventMessages($object->error, $object->errors, 'errors');
-		}
-	} else {
-		header("Location: " . $_SERVER["PHP_SELF"] . "?id=" . $id);
-		exit();
-	}
-}
-
-
-
-/*
- * View
- */
-
-$title = $langs->trans("Journal") . " - " . $langs->trans("Card");
-$helpurl = "";
-llxHeader("",$title,$helpurl);
-
-$form = new Form($db);
-
-if ($action == 'create') 
-{
-	print load_fiche_titre($langs->trans("NewAccountingJournal"));
-
-	print '<form action="' . $_SERVER["PHP_SELF"] . '" method="POST">';
-	print '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
-	print '<input type="hidden" name="action" value="add">';
-
-	dol_fiche_head();
-
-	print '<table class="border" width="100%">';
-
-	// Code
-	print '<tr><td class="titlefieldcreate fieldrequired">' . $langs->trans("Code") . '</td><td><input name="code" size="10" value="' . GETPOST("code") . '"></td></tr>';
-
-
-	// Label
-	print '<tr><td class="fieldrequired">' . $langs->trans("Label") . '</td><td><input name="label" size="32" value="' . GETPOST("label") . '"></td></tr>';
-
-	// Nature
-	print '<tr>';
-	print '<td class="fieldrequired">' . $langs->trans("Type") . '</td>';
-	print '<td class="valeur">';
-	print $form->selectarray('nature', $type2label, GETPOST('nature'));
-	print '</td></tr>';
-	
-	print '</table>';
-
-	dol_fiche_end();
-
-	print '<div class="center">';
-	print '<input class="button" type="submit" value="' . $langs->trans("Save") . '">';
-	print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
-	print '<input class="button" type="submit" name="cancel" value="' . $langs->trans("Cancel") . '">';
-	print '</div>';
-
-	print '</form>';
-} else if ($id) {
-	$result = $object->fetch($id);
-	if ($result > 0) {
-		$head = accounting_journal_prepare_head($object);
-
-		if ($action == 'edit') {
-			dol_fiche_head($head, 'card', $langs->trans("AccountingJournal"), 0, 'cron');
-
-			print '<form name="update" action="' . $_SERVER["PHP_SELF"] . '" method="POST">' . "\n";
-			print '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
-			print '<input type="hidden" name="action" value="update">';
-			print '<input type="hidden" name="id" value="' . $id . '">';
-
-			print '<table class="border" width="100%">';
-
-			// Code
-			print "<tr>";
-			print '<td class="titlefieldcreate fieldrequired">' . $langs->trans("Code") . '</td><td>';
-			print '<input name="code" class="flat" size="8" value="' . $object->code . '">';
-			print '</td></tr>';
-
-			// Label
-			print '<tr><td class="fieldrequired">' . $langs->trans("Label") . '</td><td>';
-			print '<input name="label" class="flat" size="32" value="' . $object->label . '">';
-			print '</td></tr>';
-
-			// Nature
-			print '<tr><td>' . $langs->trans("Type") . '</td><td>';
-			print $form->selectarray('nature', $type2label, $object->nature);
-			print '</td></tr>';
-
-			print '</table>';
-
-			print '<br><div class="center">';
-			print '<input type="submit" class="button" value="' . $langs->trans("Save") . '">';
-			print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
-			print '<input type="submit" name="cancel" class="button" value="' . $langs->trans("Cancel") . '">';
-			print '</div>';
-
-			print '</form>';
-
-			dol_fiche_end();
-		} else {
-			/*
-			 * Confirm delete
-			 */
-			if ($action == 'delete') {
-				print $form->formconfirm($_SERVER["PHP_SELF"] . "?id=" . $id, $langs->trans("DeleteFiscalYear"), $langs->trans("ConfirmDeleteFiscalYear"), "confirm_delete");
-			}
-
-			dol_fiche_head($head, 'card', $langs->trans("AccountingJournal"), 0, 'cron');
-
-			print '<table class="border" width="100%">';
-
-			$linkback = '<a href="' . DOL_URL_ROOT . '/accountancy/admin/journals.php">' . $langs->trans("BackToList") . '</a>';
-
-			// Ref
-			print '<tr><td class="titlefield">' . $langs->trans("Code") . '</td><td width="50%">';
-			print $object->code;
-			print '</td><td>';
-			print $linkback;
-			print '</td></tr>';
-
-			// Label
-			print '<tr><td class="tdtop">';
-			print $form->editfieldkey("Label", 'label', $object->label, $object, $conf->global->MAIN_EDIT_ALSO_INLINE, 'alpha:32');
-			print '</td><td colspan="2">';
-			print $form->editfieldval("Label", 'label', $object->label, $object, $conf->global->MAIN_EDIT_ALSO_INLINE, 'alpha:32');
-			print "</td></tr>";
-
-			// Nature
-			print '<tr><td>' . $langs->trans("Type") . '</td><td colspan="2">' . $object->getLibType(0) . '</td></tr>';
-
-			print "</table>";
-
-			dol_fiche_end();
-
-			if (! empty($user->rights->accounting->fiscalyear))
-			{
-    			/*
-    			 * Barre d'actions
-    			 */
-    			print '<div class="tabsAction">';
-
-    			print '<a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?action=edit&id=' . $id . '">' . $langs->trans('Modify') . '</a>';
-
-    			print '<a class="butActionDelete" href="' . $_SERVER["PHP_SELF"] . '?action=delete&id=' . $id . '">' . $langs->trans('Delete') . '</a>';
-
-    			print '</div>';
-			}
-		}
-	} else {
-		dol_print_error($db);
-	}
-}
-
-llxFooter();
-$db->close();
diff --git a/htdocs/accountancy/admin/journals_list.php b/htdocs/accountancy/admin/journals_list.php
new file mode 100644
index 0000000000000000000000000000000000000000..0b13bfc7d4d2fbdc9d176a6d45134060aa74b981
--- /dev/null
+++ b/htdocs/accountancy/admin/journals_list.php
@@ -0,0 +1,752 @@
+<?php
+/* Copyright (C) 2017		Alexandre Spangaro   <aspangaro@zendsi.com>
+ *
+ * This program 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.
+ *
+ * This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+/**
+ * \file		htdocs/accountancy/admin/journals_list.php
+ * \ingroup		Advanced accountancy
+ * \brief		Setup page to configure journals
+ */
+require '../../main.inc.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php';
+
+$langs->load("admin");
+$langs->load("compta");
+$langs->load("accountancy");
+
+$action=GETPOST('action','alpha')?GETPOST('action','alpha'):'view';
+$confirm=GETPOST('confirm','alpha');
+$id=GETPOST('id','int');
+$rowid=GETPOST('rowid','alpha');
+
+// Security access
+if (! empty($user->rights->accountancy->chartofaccount))
+{
+	accessforbidden();
+}
+
+$acts[0] = "activate";
+$acts[1] = "disable";
+$actl[0] = img_picto($langs->trans("Disabled"),'switch_off');
+$actl[1] = img_picto($langs->trans("Activated"),'switch_on');
+
+$listoffset=GETPOST('listoffset');
+$listlimit=GETPOST('listlimit')>0?GETPOST('listlimit'):1000;
+$active = 1;
+
+$sortfield = GETPOST("sortfield",'alpha');
+$sortorder = GETPOST("sortorder",'alpha');
+$page = GETPOST("page",'int');
+if ($page == -1) { $page = 0 ; }
+$offset = $listlimit * $page ;
+$pageprev = $page - 1;
+$pagenext = $page + 1;
+if (empty($sortfield)) $sortfield='code';
+if (empty($sortorder)) $sortorder='ASC';
+
+$error = 0;
+
+// Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array
+$hookmanager->initHooks(array('admin'));
+
+// This page is a generic page to edit dictionaries
+// Put here declaration of dictionaries properties
+
+// Sort order to show dictionary (0 is space). All other dictionaries (added by modules) will be at end of this.
+$taborder=array(35);
+
+// Name of SQL tables of dictionaries
+$tabname=array();
+$tabname[35]= MAIN_DB_PREFIX."accounting_journal";
+
+// Dictionary labels
+$tablib=array();
+$tablib[35]= "DictionaryAccountancyJournal";
+
+// Requests to extract data
+$tabsql=array();
+$tabsql[35]= "SELECT a.rowid as rowid, a.code as code, a.label, a.nature, a.active FROM ".MAIN_DB_PREFIX."accounting_journal as a";
+
+// Criteria to sort dictionaries
+$tabsqlsort=array();
+$tabsqlsort[35]="code ASC";
+
+// Nom des champs en resultat de select pour affichage du dictionnaire
+$tabfield=array();
+$tabfield[35]= "code,label,nature";
+
+// Nom des champs d'edition pour modification d'un enregistrement
+$tabfieldvalue=array();
+$tabfieldvalue[35]= "code,label,nature";
+
+// Nom des champs dans la table pour insertion d'un enregistrement
+$tabfieldinsert=array();
+$tabfieldinsert[35]= "code,label,nature";
+
+// Nom du rowid si le champ n'est pas de type autoincrement
+// Example: "" if id field is "rowid" and has autoincrement on
+//          "nameoffield" if id field is not "rowid" or has not autoincrement on
+$tabrowid=array();
+$tabrowid[35]= "";
+
+// Condition to show dictionary in setup page
+$tabcond=array();
+$tabcond[35]= ! empty($conf->accounting->enabled);
+
+// List of help for fields
+$tabhelp=array();
+$tabhelp[35] = array('code'=>$langs->trans("EnterAnyCode"));
+
+// List of check for fields (NOT USED YET)
+$tabfieldcheck=array();
+$tabfieldcheck[35] = array();
+
+// Complete all arrays with entries found into modules
+complete_dictionary_with_modules($taborder,$tabname,$tablib,$tabsql,$tabsqlsort,$tabfield,$tabfieldvalue,$tabfieldinsert,$tabrowid,$tabcond,$tabhelp,$tabfieldcheck);
+
+
+// Define elementList and sourceList (used for dictionary type of contacts "llx_c_type_contact")
+$elementList = array();
+    // Must match ids defined into eldy.lib.php 
+    $sourceList = array(
+			'1' => $langs->trans('AccountingJournalType1'),
+			'2' => $langs->trans('AccountingJournalType2'),
+			'3' => $langs->trans('AccountingJournalType3'),
+			'4' => $langs->trans('AccountingJournalType4'),
+			'9' => $langs->trans('AccountingJournalType9')
+	);
+
+/*
+ * Actions
+ */
+
+if (GETPOST('button_removefilter') || GETPOST('button_removefilter.x') || GETPOST('button_removefilter_x'))
+{
+    $search_country_id = '';    
+}
+
+// Actions add or modify an entry into a dictionary
+if (GETPOST('actionadd') || GETPOST('actionmodify'))
+{
+    $listfield=explode(',', str_replace(' ', '',$tabfield[$id]));
+    $listfieldinsert=explode(',',$tabfieldinsert[$id]);
+    $listfieldmodify=explode(',',$tabfieldinsert[$id]);
+    $listfieldvalue=explode(',',$tabfieldvalue[$id]);
+
+    // Check that all fields are filled
+    $ok=1;
+    foreach ($listfield as $f => $value)
+    {
+		if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label'))  $fieldnamekey='Label';
+        if ($fieldnamekey == 'code') $fieldnamekey = 'Code';
+		if ($fieldnamekey == 'nature') $fieldnamekey = 'Nature';
+    }
+    // Other checks
+    if (isset($_POST["code"]))
+    {
+    	if ($_POST["code"]=='0')
+    	{
+        	$ok=0;
+    		setEventMessages($langs->transnoentities('ErrorCodeCantContainZero'), null, 'errors');
+        }
+        /*if (!is_numeric($_POST['code']))	// disabled, code may not be in numeric base
+    	{
+	    	$ok = 0;
+	    	$msg .= $langs->transnoentities('ErrorFieldFormat', $langs->transnoentities('Code')).'<br />';
+	    }*/
+    }
+
+	// Clean some parameters
+    if ($_POST["accountancy_code"] <= 0) $_POST["accountancy_code"]='';	// If empty, we force to null
+	if ($_POST["accountancy_code_sell"] <= 0) $_POST["accountancy_code_sell"]='';	// If empty, we force to null
+	if ($_POST["accountancy_code_buy"] <= 0) $_POST["accountancy_code_buy"]='';	// If empty, we force to null
+
+    // Si verif ok et action add, on ajoute la ligne
+    if ($ok && GETPOST('actionadd'))
+    {
+        if ($tabrowid[$id])
+        {
+            // Recupere id libre pour insertion
+            $newid=0;
+            $sql = "SELECT max(".$tabrowid[$id].") newid from ".$tabname[$id];
+            $result = $db->query($sql);
+            if ($result)
+            {
+                $obj = $db->fetch_object($result);
+                $newid=($obj->newid + 1);
+
+            } else {
+                dol_print_error($db);
+            }
+        }
+
+        // Add new entry
+        $sql = "INSERT INTO ".$tabname[$id]." (";
+        // List of fields
+        if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldinsert))
+        	$sql.= $tabrowid[$id].",";
+        $sql.= $tabfieldinsert[$id];
+        $sql.=",active)";
+        $sql.= " VALUES(";
+
+        // List of values
+        if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldinsert))
+        	$sql.= $newid.",";
+        $i=0;
+        foreach ($listfieldinsert as $f => $value)
+        {
+            if ($value == 'entity') {
+            	$_POST[$listfieldvalue[$i]] = $conf->entity;
+            }
+            if ($i) $sql.=",";
+            if ($_POST[$listfieldvalue[$i]] == '' && ! ($listfieldvalue[$i] == 'code' && $id == 10)) $sql.="null";  // For vat, we want/accept code = ''
+            else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'";
+            $i++;
+        }
+        $sql.=",1)";
+
+        dol_syslog("actionadd", LOG_DEBUG);
+        $result = $db->query($sql);
+        if ($result)	// Add is ok
+        {
+            setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs');
+        	$_POST=array('id'=>$id);	// Clean $_POST array, we keep only
+        }
+        else
+        {
+            if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
+                setEventMessages($langs->transnoentities("ErrorRecordAlreadyExists"), null, 'errors');
+            }
+            else {
+                dol_print_error($db);
+            }
+        }
+    }
+
+    // Si verif ok et action modify, on modifie la ligne
+    if ($ok && GETPOST('actionmodify'))
+    {
+        if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; }
+        else { $rowidcol="rowid"; }
+
+        // Modify entry
+        $sql = "UPDATE ".$tabname[$id]." SET ";
+        // Modifie valeur des champs
+        if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldmodify))
+        {
+            $sql.= $tabrowid[$id]."=";
+            $sql.= "'".$db->escape($rowid)."', ";
+        }
+        $i = 0;
+        foreach ($listfieldmodify as $field)
+        {
+            if ($field == 'price' || preg_match('/^amount/i',$field) || $field == 'taux') {
+            	$_POST[$listfieldvalue[$i]] = price2num($_POST[$listfieldvalue[$i]],'MU');
+            }
+            else if ($field == 'entity') {
+            	$_POST[$listfieldvalue[$i]] = $conf->entity;
+            }
+            if ($i) $sql.=",";
+            $sql.= $field."=";
+            if ($_POST[$listfieldvalue[$i]] == '' && ! ($listfieldvalue[$i] == 'code' && $id == 10)) $sql.="null";  // For vat, we want/accept code = ''
+            else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'";
+            $i++;
+        }
+        $sql.= " WHERE ".$rowidcol." = '".$rowid."'";
+
+        dol_syslog("actionmodify", LOG_DEBUG);
+        //print $sql;
+        $resql = $db->query($sql);
+        if (! $resql)
+        {
+            setEventMessages($db->error(), null, 'errors');
+        }
+    }
+    //$_GET["id"]=GETPOST('id', 'int');       // Force affichage dictionnaire en cours d'edition
+}
+
+if (GETPOST('actioncancel'))
+{
+    //$_GET["id"]=GETPOST('id', 'int');       // Force affichage dictionnaire en cours d'edition
+}
+
+if ($action == 'confirm_delete' && $confirm == 'yes')       // delete
+{
+    if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; }
+    else { $rowidcol="rowid"; }
+
+    $sql = "DELETE from ".$tabname[$id]." WHERE ".$rowidcol."='".$rowid."'";
+
+    dol_syslog("delete", LOG_DEBUG);
+    $result = $db->query($sql);
+    if (! $result)
+    {
+        if ($db->errno() == 'DB_ERROR_CHILD_EXISTS')
+        {
+            setEventMessages($langs->transnoentities("ErrorRecordIsUsedByChild"), null, 'errors');
+        }
+        else
+        {
+            dol_print_error($db);
+        }
+    }
+}
+
+// activate
+if ($action == $acts[0])
+{
+    if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; }
+    else { $rowidcol="rowid"; }
+
+    if ($rowid) {
+        $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol."='".$rowid."'";
+    }
+    elseif ($_GET["code"]) {
+        $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE code='".$_GET["code"]."'";
+    }
+
+    $result = $db->query($sql);
+    if (!$result)
+    {
+        dol_print_error($db);
+    }
+}
+
+// disable
+if ($action == $acts[1])
+{
+    if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; }
+    else { $rowidcol="rowid"; }
+
+    if ($rowid) {
+        $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol."='".$rowid."'";
+    }
+    elseif ($_GET["code"]) {
+        $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE code='".$_GET["code"]."'";
+    }
+
+    $result = $db->query($sql);
+    if (!$result)
+    {
+        dol_print_error($db);
+    }
+}
+
+/*
+ * View
+ */
+
+$form = new Form($db);
+$formadmin=new FormAdmin($db);
+
+llxHeader();
+
+$titre=$langs->trans("DictionarySetup");
+$linkback='';
+if ($id)
+{
+    $titre.=' - '.$langs->trans($tablib[$id]);
+    $titlepicto='title_accountancy';
+}
+
+print load_fiche_titre($titre,$linkback,$titlepicto);
+
+if (empty($id))
+{
+    print $langs->trans("DictionaryDesc");
+    print " ".$langs->trans("OnlyActiveElementsAreShown")."<br>\n";
+}
+print "<br>\n";
+
+
+// Confirmation de la suppression de la ligne
+if ($action == 'delete')
+{
+    print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid.'&code='.$_GET["code"].'&id='.$id, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete','',0,1);
+}
+//var_dump($elementList);
+
+/*
+ * Show a dictionary
+ */
+if ($id)
+{
+    // Complete requete recherche valeurs avec critere de tri
+    $sql=$tabsql[$id];
+
+    if ($search_country_id > 0)
+    {
+        if (preg_match('/ WHERE /',$sql)) $sql.= " AND ";
+        else $sql.=" WHERE ";
+        $sql.= " c.rowid = ".$search_country_id;
+    }
+    
+    if ($sortfield)
+    {
+        // If sort order is "country", we use country_code instead
+    	if ($sortfield == 'country') $sortfield='country_code';
+        $sql.= " ORDER BY ".$sortfield;
+        if ($sortorder)
+        {
+            $sql.=" ".strtoupper($sortorder);
+        }
+        $sql.=", ";
+        // Clear the required sort criteria for the tabsqlsort to be able to force it with selected value
+        $tabsqlsort[$id]=preg_replace('/([a-z]+\.)?'.$sortfield.' '.$sortorder.',/i','',$tabsqlsort[$id]);
+        $tabsqlsort[$id]=preg_replace('/([a-z]+\.)?'.$sortfield.',/i','',$tabsqlsort[$id]);
+    }
+    else {
+        $sql.=" ORDER BY ";
+    }
+    $sql.=$tabsqlsort[$id];
+    $sql.=$db->plimit($listlimit+1,$offset);
+    //print $sql;
+
+    $fieldlist=explode(',',$tabfield[$id]);
+
+    print '<form action="'.$_SERVER['PHP_SELF'].'?id='.$id.'" method="POST">';
+    print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
+    print '<input type="hidden" name="from" value="'.dol_escape_htmltag(GETPOST('from','alpha')).'">';
+    
+    print '<table class="noborder" width="100%">';
+
+    // Form to add a new line
+    if ($tabname[$id])
+    {
+        $alabelisused=0;
+        $var=false;
+
+        $fieldlist=explode(',',$tabfield[$id]);
+
+        // Line for title
+        print '<tr class="liste_titre">';
+        foreach ($fieldlist as $field => $value)
+        {
+            // Determine le nom du champ par rapport aux noms possibles
+            // dans les dictionnaires de donnees
+            $valuetoshow=ucfirst($fieldlist[$field]);   // Par defaut
+            $valuetoshow=$langs->trans($valuetoshow);   // try to translate
+            $align="left";
+            if ($fieldlist[$field]=='code')            { $valuetoshow=$langs->trans("Code"); }
+            if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label')
+            {
+            	$valuetoshow=$langs->trans("Label");
+            }
+            if ($fieldlist[$field]=='nature')          { $valuetoshow=$langs->trans("Nature"); }
+				
+            if ($valuetoshow != '')
+            {
+                print '<td align="'.$align.'">';
+            	if (! empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i',$tabhelp[$id][$value])) print '<a href="'.$tabhelp[$id][$value].'" target="_blank">'.$valuetoshow.' '.img_help(1,$valuetoshow).'</a>';
+            	else if (! empty($tabhelp[$id][$value])) print $form->textwithpicto($valuetoshow,$tabhelp[$id][$value]);
+            	else print $valuetoshow;
+                print '</td>';
+             }
+             if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') $alabelisused=1;
+        }
+
+        print '<td>';
+        print '<input type="hidden" name="id" value="'.$id.'">';
+        print '</td>';
+        print '<td style="min-width: 26px;"></td>';
+        print '<td style="min-width: 26px;"></td>';
+        print '<td style="min-width: 26px;"></td>';
+        print '</tr>';
+
+        // Line to enter new values
+        print '<tr class="oddeven nodrag nodrap nohover">';
+
+        $obj = new stdClass();
+        // If data was already input, we define them in obj to populate input fields.
+        if (GETPOST('actionadd'))
+        {
+            foreach ($fieldlist as $key=>$val)
+            {
+                if (GETPOST($val) != '')
+                	$obj->$val=GETPOST($val);
+            }
+        }
+
+        $tmpaction = 'create';
+        $parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]);
+        $reshook=$hookmanager->executeHooks('createDictionaryFieldlist',$parameters, $obj, $tmpaction);    // Note that $action and $object may have been modified by some hooks
+        $error=$hookmanager->error; $errors=$hookmanager->errors;
+
+        if (empty($reshook))
+        {
+       		fieldList($fieldlist,$obj,$tabname[$id],'add');
+        }
+
+        print '<td colspan="4" align="right">';
+       	print '<input type="submit" class="button" name="actionadd" value="'.$langs->trans("Add").'">';
+        print '</td>';
+        print "</tr>";
+
+        print '<tr><td colspan="7">&nbsp;</td></tr>';	// Keep &nbsp; to have a line with enough height
+    }
+
+
+
+    // List of available record in database
+    dol_syslog("htdocs/admin/dict", LOG_DEBUG);
+    $resql=$db->query($sql);
+    if ($resql)
+    {
+        $num = $db->num_rows($resql);
+        $i = 0;
+        $var=true;
+
+        $param = '&id='.$id;
+        if ($search_country_id > 0) $param.= '&search_country_id='.$search_country_id;
+        $paramwithsearch = $param;
+        if ($sortorder) $paramwithsearch.= '&sortorder='.$sortorder;
+        if ($sortfield) $paramwithsearch.= '&sortfield='.$sortfield;
+        if (GETPOST('from')) $paramwithsearch.= '&from='.GETPOST('from','alpha');
+        
+        // There is several pages
+        if ($num > $listlimit)
+        {
+            print '<tr class="none"><td align="right" colspan="'.(3+count($fieldlist)).'">';
+            print_fleche_navigation($page, $_SERVER["PHP_SELF"], $paramwithsearch, ($num > $listlimit), '<li class="pagination"><span>'.$langs->trans("Page").' '.($page+1).'</span></li>');
+            print '</td></tr>';
+        }
+
+        // Title of lines
+        print '<tr class="liste_titre liste_titre_add">';
+        foreach ($fieldlist as $field => $value)
+        {
+            // Determine le nom du champ par rapport aux noms possibles
+            // dans les dictionnaires de donnees
+            $showfield=1;							  	// By defaut
+            $align="left";
+            $sortable=1;
+            $valuetoshow='';
+            /*
+            $tmparray=getLabelOfField($fieldlist[$field]);
+            $showfield=$tmp['showfield'];
+            $valuetoshow=$tmp['valuetoshow'];
+            $align=$tmp['align'];
+            $sortable=$tmp['sortable'];
+			*/
+            $valuetoshow=ucfirst($fieldlist[$field]);   // By defaut
+            $valuetoshow=$langs->trans($valuetoshow);   // try to translate
+            if ($fieldlist[$field]=='code')            { $valuetoshow=$langs->trans("Code"); }
+            if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') { $valuetoshow=$langs->trans("Label"); }
+            if ($fieldlist[$field]=='nature')          { $valuetoshow=$langs->trans("Nature"); }
+
+            // Affiche nom du champ
+            if ($showfield)
+            {
+                print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable?$fieldlist[$field]:''), ($page?'page='.$page.'&':''), $param, "align=".$align, $sortfield, $sortorder);
+            }
+        }
+		print getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], "active", ($page?'page='.$page.'&':''), $param, 'align="center"', $sortfield, $sortorder);
+        print getTitleFieldOfList('');
+        print getTitleFieldOfList('');
+        print getTitleFieldOfList('');
+        print '</tr>';
+
+        // Title line with search boxes
+        print '<tr class="liste_titre_filter">';
+        print '<td class="liste_titre"></td>';
+        print '<td class="liste_titre"></td>';
+        print '<td class="liste_titre"></td>';
+        print '<td class="liste_titre"></td>';
+        print '<td class="liste_titre"></td>';
+        print '<td class="liste_titre"></td>';
+        print '<td class="liste_titre" align="center">';
+    	if ($filterfound)
+    	{
+        	$searchpitco=$form->showFilterAndCheckAddButtons(0);
+        	print $searchpitco;
+    	}
+    	print '</td>';
+    	print '</tr>';
+            
+        if ($num)
+        {
+            // Lines with values
+            while ($i < $num)
+            {
+                $obj = $db->fetch_object($resql);
+                //print_r($obj);
+                print '<tr class="oddeven" id="rowid-'.$obj->rowid.'">';
+                if ($action == 'edit' && ($rowid == (! empty($obj->rowid)?$obj->rowid:$obj->code)))
+                {
+                    $tmpaction='edit';
+                    $parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]);
+                    $reshook=$hookmanager->executeHooks('editDictionaryFieldlist',$parameters,$obj, $tmpaction);    // Note that $action and $object may have been modified by some hooks
+                    $error=$hookmanager->error; $errors=$hookmanager->errors;
+
+                    // Show fields
+                    if (empty($reshook)) fieldList($fieldlist,$obj,$tabname[$id],'edit');
+
+                    print '<td align="center" colspan="4">';
+                    print '<input type="hidden" name="page" value="'.$page.'">';
+                    print '<input type="hidden" name="rowid" value="'.$rowid.'">';
+                    print '<input type="submit" class="button" name="actionmodify" value="'.$langs->trans("Modify").'">';
+                    print '<input type="submit" class="button" name="actioncancel" value="'.$langs->trans("Cancel").'">';
+                    print '<div name="'.(! empty($obj->rowid)?$obj->rowid:$obj->code).'"></div>';
+                    print '</td>';
+                }
+                else
+                {
+	              	$tmpaction = 'view';
+                    $parameters=array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]);
+                    $reshook=$hookmanager->executeHooks('viewDictionaryFieldlist',$parameters,$obj, $tmpaction);    // Note that $action and $object may have been modified by some hooks
+
+                    $error=$hookmanager->error; $errors=$hookmanager->errors;
+
+                    if (empty($reshook))
+                    {
+                        foreach ($fieldlist as $field => $value)
+                        {
+                            
+                            $showfield=1;
+                        	$align="left";
+                            $valuetoshow=$obj->{$fieldlist[$field]};
+                            if ($valuetoshow=='all') {
+                                $valuetoshow=$langs->trans('All');
+                            }
+                            else if ($fieldlist[$field]=='nature' && $tabname[$id]==MAIN_DB_PREFIX.'accounting_journal') {
+                                $langs->load("accountancy");
+                                $key=$langs->trans("AccountingJournalType".strtoupper($obj->nature));
+                                $valuetoshow=($obj->nature && $key != "AccountingJournalType".strtoupper($obj->nature)?$key:$obj->{$fieldlist[$field]});
+                            }
+
+                            $class='tddict';
+							// Show value for field
+							if ($showfield) print '<!-- '.$fieldlist[$field].' --><td align="'.$align.'" class="'.$class.'">'.$valuetoshow.'</td>';
+                        }
+                    }
+
+                    // Can an entry be erased or disabled ?
+                    $iserasable=1;$canbedisabled=1;$canbemodified=1;	// true by default
+                    if (isset($obj->code) && $id != 10)
+                    {
+                    	if (($obj->code == '0' || $obj->code == '' || preg_match('/unknown/i',$obj->code))) { $iserasable = 0; $canbedisabled = 0; }
+                    	else if ($obj->code == 'RECEP') { $iserasable = 0; $canbedisabled = 0; }
+                    	else if ($obj->code == 'EF0')   { $iserasable = 0; $canbedisabled = 0; }
+                    }
+
+                    $canbemodified=$iserasable;
+
+                    $url = $_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(! empty($obj->rowid)?$obj->rowid:(! empty($obj->code)?$obj->code:'')).'&code='.(! empty($obj->code)?urlencode($obj->code):'');
+                    if ($param) $url .= '&'.$param;
+                    $url.='&';
+
+                    // Active
+                    print '<td align="center" class="nowrap">';
+                    if ($canbedisabled) print '<a href="'.$url.'action='.$acts[$obj->active].'">'.$actl[$obj->active].'</a>';
+                    else
+                 	{
+                 		if (in_array($obj->code, array('AC_OTH','AC_OTH_AUTO'))) print $langs->trans("AlwaysActive");
+                 		else if (isset($obj->type) && in_array($obj->type, array('systemauto')) && empty($obj->active)) print $langs->trans("Deprecated");
+                  		else if (isset($obj->type) && in_array($obj->type, array('system')) && ! empty($obj->active) && $obj->code != 'AC_OTH') print $langs->trans("UsedOnlyWithTypeOption");
+                    	else print $langs->trans("AlwaysActive");
+                    }
+                    print "</td>";
+
+                    // Modify link
+                    if ($canbemodified) print '<td align="center"><a class="reposition" href="'.$url.'action=edit">'.img_edit().'</a></td>';
+                    else print '<td>&nbsp;</td>';
+
+                    // Delete link
+                    if ($iserasable)
+                    {
+                        print '<td align="center">';
+                        if ($user->admin) print '<a href="'.$url.'action=delete">'.img_delete().'</a>';
+                        //else print '<a href="#">'.img_delete().'</a>';    // Some dictionnary can be edited by other profile than admin
+                        print '</td>';
+                    }
+                    else print '<td>&nbsp;</td>';
+
+                    print '<td></td>';
+                                         
+                    print '</td>';
+                }
+                
+                print "</tr>\n";
+                $i++;
+            }
+        }
+    }
+    else {
+        dol_print_error($db);
+    }
+
+    print '</table>';
+
+    print '</form>';
+}
+
+print '<br>';
+
+
+llxFooter();
+$db->close();
+
+
+/**
+ *	Show fields in insert/edit mode
+ *
+ * 	@param		array	$fieldlist		Array of fields
+ * 	@param		Object	$obj			If we show a particular record, obj is filled with record fields
+ *  @param		string	$tabname		Name of SQL table
+ *  @param		string	$context		'add'=Output field for the "add form", 'edit'=Output field for the "edit form", 'hide'=Output field for the "add form" but we dont want it to be rendered
+ *	@return		void
+ */
+function fieldList($fieldlist, $obj='', $tabname='', $context='')
+{
+	global $conf,$langs,$db;
+	global $form, $mysoc;
+	global $region_id;
+	global $elementList,$sourceList,$localtax_typeList;
+	global $bc;
+
+	$formadmin = new FormAdmin($db);
+	$formcompany = new FormCompany($db);
+
+	foreach ($fieldlist as $field => $value)
+	{
+		if ($fieldlist[$field] == 'nature')
+		{
+			print '<td>';
+			print $form->selectarray('nature', $sourceList,(! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:''));
+			print '</td>';
+		}
+		elseif ($fieldlist[$field] == 'code' && isset($obj->{$fieldlist[$field]})) {
+			print '<td><input type="text" class="flat minwidth100" value="'.(! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:'').'" name="'.$fieldlist[$field].'"></td>';
+		}
+		else
+		{
+			print '<td>';
+			$size=''; $class='';
+			if ($fieldlist[$field]=='code')  $class='maxwidth100';
+			if ($fieldlist[$field]=='label') $class='quatrevingtpercent';
+			if ($fieldlist[$field]=='sortorder' || $fieldlist[$field]=='sens' || $fieldlist[$field]=='category_type') $size='size="2" ';
+			print '<input type="text" '.$size.'class="flat'.($class?' '.$class:'').'" value="'.(isset($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:'').'" name="'.$fieldlist[$field].'">';
+			print '</td>';
+		}
+	}
+}
\ No newline at end of file
diff --git a/htdocs/accountancy/bookkeeping/card.php b/htdocs/accountancy/bookkeeping/card.php
index 116e071e42fab6942a31ea4ff3b1c58e587ddc75..ce0bd4d3aa2982025a0b6096a61bbb134743c5f9 100644
--- a/htdocs/accountancy/bookkeeping/card.php
+++ b/htdocs/accountancy/bookkeeping/card.php
@@ -305,6 +305,8 @@ if ($action == 'create') {
 
 		dol_fiche_head();
 		
+		print '<div class="fichecenter">';
+		
 		print '<table class="border" width="100%">';
 		print '<tr class="pair">';
 		print '<td class="titlefield">' . $langs->trans("NumMvts") . '</td>';
@@ -328,6 +330,8 @@ if ($action == 'create') {
 		print '</tr>';
 		print '</table>';
 		
+		print '</div>';
+		
 		dol_fiche_end();
 
 		print '<br>';
@@ -427,8 +431,8 @@ if ($action == 'create') {
 					print $formventilation->select_auxaccount($code_tiers, 'code_tiers', 1);
 					print '</td>';
 					print '<td><input type="text" size="15" name="label_compte" value="' . $label_compte . '"/></td>';
-					print '<td align="right"><input type="text" size="6" name="debit" value="' . price($debit) . '"/></td>';
-					print '<td align="right"><input type="text" size="6" name="credit" value="' . price($credit) . '"/></td>';
+					print '<td align="right"><input type="text" class="right maxwidth50" name="debit" value="' . price($debit) . '"/></td>';
+					print '<td align="right"><input type="text" class="right maxwidth50" name="credit" value="' . price($credit) . '"/></td>';
 					print '<td></td>';
 					print '<td></td>';
 					print '<td><input type="submit" class="button" name="save" value="' . $langs->trans("Add") . '"></td>';
diff --git a/htdocs/accountancy/bookkeeping/list.php b/htdocs/accountancy/bookkeeping/list.php
index 9cd649ce4bee1707b13527b4fd4eb00d4facdbdc..75d0a63bf3946b1eca615fb42051cbee2ae4a7f2 100644
--- a/htdocs/accountancy/bookkeeping/list.php
+++ b/htdocs/accountancy/bookkeeping/list.php
@@ -360,7 +360,7 @@ if (count($filter)) $button.= $langs->trans("ExportFilteredList");
 else $button.= $langs->trans("ExportList");
 $button.= '</a>';
 
-$groupby = ' <a href="./listbyaccount.php">' . $langs->trans("GroupByAccountAccounting") . '</a>';
+$groupby = ' <a class="nohover" href="'.DOL_URL_ROOT.'/accountancy/bookkeeping/listbyaccount.php"">' . $langs->trans("GroupByAccountAccounting") . '</a>';
 
 print_barre_liste($title_page, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $button, $result, $nbtotalofrecords, 'title_accountancy', 0, $groupby, '', $limit);
 
@@ -437,7 +437,7 @@ foreach ($object->lines as $line ) {
 
 	print '<td><a href="./card.php?piece_num=' . $line->piece_num . '">' . $line->piece_num . '</a></td>';
 	print '<td align="center">' . dol_print_date($line->doc_date, 'day') . '</td>';
-	print '<td>' . $line->doc_ref . '</td>';
+	print '<td class="nowrap">' . $line->doc_ref . '</td>';
 	print '<td>' . length_accountg($line->numero_compte) . '</td>';
 	print '<td>' . length_accounta($line->code_tiers) . '</td>';
 	print '<td>' . $line->label_compte . '</td>';
diff --git a/htdocs/accountancy/bookkeeping/listbyaccount.php b/htdocs/accountancy/bookkeeping/listbyaccount.php
index cbb83ba269e0c29038c6a802fd8d800e98e3e8ac..2323f3afcb88ae288edce400103f1f3a6732760e 100644
--- a/htdocs/accountancy/bookkeeping/listbyaccount.php
+++ b/htdocs/accountancy/bookkeeping/listbyaccount.php
@@ -207,7 +207,7 @@ if ($action == 'delbookkeepingyear') {
 
 print '<form method="GET" id="searchFormList" action="' . $_SERVER["PHP_SELF"] . '">';
 
-$viewflat = ' <a href="./list.php">' . $langs->trans("ViewFlatList") . '</a>';
+$viewflat = ' <a class="nohover" href="'.DOL_URL_ROOT.'/accountancy/bookkeeping/list.php">' . $langs->trans("ViewFlatList") . '</a>';
 
 print_barre_liste($title_page, $page, $_SERVER["PHP_SELF"], $options, $sortfield, $sortorder, '', $result, $nbtotalofrecords,'title_accountancy',0,$viewflat,'',$limit);
 
@@ -222,17 +222,6 @@ print '<div class="inline-block divButAction"><a class="butAction" href="./card.
 print '</div>';
 
 print '<table class="noborder" width="100%">';
-print '<tr class="liste_titre">';
-print '<td>' . $langs->trans("AccountAccounting") . '</td>';
-print_liste_field_titre($langs->trans("TransactionNumShort"), $_SERVER['PHP_SELF'], "t.piece_num", "", $options, 'align="right"', $sortfield, $sortorder);
-print_liste_field_titre($langs->trans("Docdate"), $_SERVER['PHP_SELF'], "t.doc_date", "", $options, 'align="center"', $sortfield, $sortorder);
-print_liste_field_titre($langs->trans("Docref"), $_SERVER['PHP_SELF'], "t.doc_ref", "", $options, "", $sortfield, $sortorder);
-print_liste_field_titre($langs->trans("SuppliersInvoices") . ' / ' . $langs->trans("CustomersInvoices"));
-print_liste_field_titre($langs->trans("Debit"), $_SERVER['PHP_SELF'], "t.debit", "", $options, 'align="right"', $sortfield, $sortorder);
-print_liste_field_titre($langs->trans("Credit"), $_SERVER['PHP_SELF'], "t.credit", "", $options, 'align="right"', $sortfield, $sortorder);
-print_liste_field_titre($langs->trans("Codejournal"), $_SERVER['PHP_SELF'], "t.code_journal", "", $options, 'align="right"', $sortfield, $sortorder);
-print_liste_field_titre('', $_SERVER["PHP_SELF"], "", $options, "", 'width="60" align="center"', $sortfield, $sortorder);
-print "</tr>\n";
 
 print '<tr class="liste_titre">';
 print '<td class="liste_titre">' . $object->select_account($search_accountancy_code_start, 'search_accountancy_code_start', 1, array (), 1, 1, '') . '</td>';
@@ -254,6 +243,18 @@ $searchpitco=$form->showFilterAndCheckAddButtons(0);
 print $searchpitco;
 print '</td>';
 
+print '<tr class="liste_titre">';
+print_liste_field_titre($langs->trans("AccountAccountingShort"), $_SERVER['PHP_SELF']);
+print_liste_field_titre($langs->trans("TransactionNumShort"), $_SERVER['PHP_SELF'], "t.piece_num", "", $options, 'align="right"', $sortfield, $sortorder);
+print_liste_field_titre($langs->trans("Docdate"), $_SERVER['PHP_SELF'], "t.doc_date", "", $options, 'align="center"', $sortfield, $sortorder);
+print_liste_field_titre($langs->trans("Docref"), $_SERVER['PHP_SELF'], "t.doc_ref", "", $options, "", $sortfield, $sortorder);
+print_liste_field_titre($langs->trans("Label"));
+print_liste_field_titre($langs->trans("Debit"), $_SERVER['PHP_SELF'], "t.debit", "", $options, 'align="right"', $sortfield, $sortorder);
+print_liste_field_titre($langs->trans("Credit"), $_SERVER['PHP_SELF'], "t.credit", "", $options, 'align="right"', $sortfield, $sortorder);
+print_liste_field_titre($langs->trans("Codejournal"), $_SERVER['PHP_SELF'], "t.code_journal", "", $options, 'align="right"', $sortfield, $sortorder);
+print_liste_field_titre('', $_SERVER["PHP_SELF"], "", $options, "", 'width="60" align="center"', $sortfield, $sortorder);
+print "</tr>\n";
+
 print '</tr>';
 
 $var = True;
@@ -277,9 +278,10 @@ foreach ( $object->lines as $line ) {
         
         // Affiche un Sous-Total par compte comptable
         if (isset($displayed_account_number)) {
-          print '<tr class="liste_total"><td align="right" colspan="4">'.$langs->trans("SubTotal").':</td><td class="nowrap" align="right">'.price($sous_total_debit).'</td><td class="nowrap" align="right">'.price($sous_total_credit).'</td>';
-          print "<td>&nbsp;</td>\n";
-          print '</tr>';
+            print '<tr class="liste_total"><td align="right" colspan="5">'.$langs->trans("SubTotal").':</td><td class="nowrap" align="right">'.price($sous_total_debit).'</td><td class="nowrap" align="right">'.price($sous_total_credit).'</td>';
+            print "<td>&nbsp;</td>\n";
+            print "<td>&nbsp;</td>\n";
+            print '</tr>';
         }
         
         // Show the break account
@@ -299,17 +301,18 @@ foreach ( $object->lines as $line ) {
 
 	print '<tr class="oddeven">';
 	print '<td>&nbsp;</td>';
-	print '<td align="right">'.$line->piece_num.'</td>';
+	print '<td align="right"><a href="./card.php?piece_num=' . $line->piece_num . '">'.$line->piece_num.'</a></td>';
 	print '<td align="center">' . dol_print_date($line->doc_date, 'day') . '</td>';
-	print '<td><a href="./card.php?piece_num=' . $line->piece_num . '">' . $line->doc_ref . '</a></td>';
+	
+	// TODO Add a link according to doc_type and fk_doc
+	print '<td class="nowrap">';
+    //if ($line->doc_type == 'supplier_invoice')
+    //if ($line->doc_type == 'customer_invoice')
+	print $line->doc_ref;
+    print '</td>';
     
     // Affiche un lien vers la facture client/fournisseur
     $doc_ref = preg_replace('/\(.*\)/', '', $line->doc_ref);
-    if ($line->doc_type == 'supplier_invoice')
-     print strlen(length_accounta($line->code_tiers)) == 0 ? '<td><a href="/fourn/facture/list.php?search_ref_supplier=' . $doc_ref . '">' . $line->label_compte . '</a></td>' : '<td><a href="/fourn/facture/list.php?search_ref_supplier=' . $doc_ref . '">' . $line->label_compte . '</a><br /><span style="font-size:0.8em">(' . length_accounta($line->code_tiers) . ')</span></td>';
-    elseif ($line->doc_type == 'customer_invoice')
-    print strlen(length_accounta($line->code_tiers)) == 0 ? '<td><a href="/compta/facture/list.php?search_ref=' . $doc_ref . '">' . $line->label_compte . '</a></td>' : '<td><a href="/compta/facture/list.php?search_ref=' . $doc_ref . '">' . $line->label_compte . '</a><br /><span style="font-size:0.8em">(' . length_accounta($line->code_tiers) . ')</span></td>';
-    else
     print strlen(length_accounta($line->code_tiers)) == 0 ? '<td>' . $line->label_compte . '</td>' : '<td>' . $line->label_compte . '<br /><span style="font-size:0.8em">(' . length_accounta($line->code_tiers) . ')</span></td>';
 
 
@@ -332,6 +335,7 @@ foreach ( $object->lines as $line ) {
 print '<tr class="liste_total">';
 print '<td align="right" colspan="5">'.$langs->trans("SubTotal").':</td><td class="nowrap" align="right">'.price($sous_total_debit).'</td><td class="nowrap" align="right">'.price($sous_total_credit).'</td>';
 print "<td>&nbsp;</td>\n";
+print "<td>&nbsp;</td>\n";
 print '</tr>';
 
 
diff --git a/htdocs/accountancy/class/accountancyexport.class.php b/htdocs/accountancy/class/accountancyexport.class.php
index 524326e320c1cd595e1fa4e2c18dfd885d4c8e05..1af9e5d1a6b61cd4a5cb586b50976c6861e03213 100644
--- a/htdocs/accountancy/class/accountancyexport.class.php
+++ b/htdocs/accountancy/class/accountancyexport.class.php
@@ -47,6 +47,7 @@ class AccountancyExport
 	public static $EXPORT_TYPE_QUADRATUS = 6;
 	public static $EXPORT_TYPE_EBP = 7;
 	public static $EXPORT_TYPE_COGILOG = 8;
+	public static $EXPORT_TYPE_AGIRIS = 9;
 
 	/**
 	 *
@@ -96,6 +97,7 @@ class AccountancyExport
 				self::$EXPORT_TYPE_QUADRATUS => $langs->trans('Modelcsv_quadratus'),
 				self::$EXPORT_TYPE_EBP => $langs->trans('Modelcsv_ebp'),
 				self::$EXPORT_TYPE_COGILOG => $langs->trans('Modelcsv_cogilog'),
+				self::$EXPORT_TYPE_AGIRIS => $langs->trans('Modelcsv_agiris')
 		);
 	}
 
@@ -145,6 +147,9 @@ class AccountancyExport
 			case self::$EXPORT_TYPE_COGILOG :
 				$this->exportCogilog($TData);
 				break;
+			case self::$EXPORT_TYPE_AGIRIS :
+				$this->exportAgiris($TData);
+				break;
 			default:
 				$this->errors[] = $langs->trans('accountancy_error_modelnotfound');
 				break;
@@ -382,7 +387,7 @@ class AccountancyExport
 
 
 	/**
-	 * Export format : Normal
+	 * Export format : EBP
 	 *
 	 * @param array $objectLines data
 	 *
@@ -412,6 +417,47 @@ class AccountancyExport
 	}
 
 
+	/**
+	 * Export format : Agiris
+	 *
+	 * @param array $objectLines data
+	 *
+	 * @return void
+	 */
+	public function exportAgiris($objectLines) {
+
+		$this->separator = ';';
+
+		foreach ( $objectLines as $line ) {
+
+			$date = dol_print_date($line->doc_date, '%d%m%Y');
+
+			print $line->id . $this->separator;
+			print '"'.dol_trunc($line->piece_num,15,'right','UTF-8',1).'"'.$this->separator;
+			print $date . $this->separator;
+			print '"'.dol_trunc($line->piece_num,15,'right','UTF-8',1).'"'.$this->separator;
+			
+			if (empty($line->code_tiers)) {
+				print length_accountg($line->numero_compte) . $this->separator;
+			} else {
+				if (substr($line->numero_compte, 0, 1) == 'C' || substr($line->numero_compte, 0, 1) == '9') {
+					print '411' . substr(str_replace(" ", "", $line->code_tiers), 0, 5) . $this->separator;
+				}
+				if (substr($line->numero_compte, 0, 1) == 'F' || substr($line->numero_compte, 0, 1) == '0') {
+					print '401' . substr(str_replace(" ", "", $line->code_tiers), 0, 5) . $this->separator;
+				}
+			}
+			
+			print length_accounta($line->code_tiers) . $this->separator;
+			print price($line->debit) . $this->separator;
+			print price($line->credit) . $this->separator;
+			print price($line->montant).$this->separator;
+			print $line->sens.$this->separator;
+			print $line->code_journal . $this->separator;
+			print $this->end_line;
+		}
+	}
+
 
 	/**
 	 *
diff --git a/htdocs/accountancy/class/accountingaccount.class.php b/htdocs/accountancy/class/accountingaccount.class.php
index 4174ee7809f7b4c28f1ce2a44b4ee5cc69109b90..8bf7dfe0c44ea57ff1c05ed7c0c5f786980ba0a9 100644
--- a/htdocs/accountancy/class/accountingaccount.class.php
+++ b/htdocs/accountancy/class/accountingaccount.class.php
@@ -364,28 +364,63 @@ class AccountingAccount extends CommonObject
 	/**
 	 * Return clicable name (with picto eventually)
 	 *
-	 * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto
-	 * @return string Chaine avec URL
+	 * @param	int		$withpicto		0=No picto, 1=Include picto into link, 2=Only picto
+	 * @param	int		$withlabel		0=No label, 1=Include label of account
+	 * @param	int  	$nourl			1=Disable url
+	 * @param	string  $moretitle		Add more text to title tooltip
+	 * @param	int  	$notooltip		1=Disable tooltip
+	 * @return	string	String with URL
 	 */
-	function getNomUrl($withpicto = 0) {
-		global $langs;
+	function getNomUrl($withpicto = 0, $withlabel = 0, $nourl = 0, $moretitle='',$notooltip=0)
+	{
+		global $langs, $conf, $user;
+		require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
+		
+		if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
 
 		$result = '';
 
-		$link = '<a href="' . DOL_URL_ROOT . '/accountancy/admin/card.php?id=' . $this->id . '">';
-		$linkend = '</a>';
+		$url = DOL_URL_ROOT . '/accountancy/admin/card.php?id=' . $this->id;
 
 		$picto = 'billr';
+		$label='';
+
+		$label = '<u>' . $langs->trans("ShowAccountingAccount") . '</u>';
+		if (! empty($this->account_number))
+			$label .= '<br><b>'.$langs->trans('AccountAccounting') . ':</b> ' . length_accountg($this->account_number);
+		if (! empty($this->label))
+			$label .= '<br><b>'.$langs->trans('Label') . ':</b> ' . $this->label;
+		if ($moretitle) $label.=' - '.$moretitle;
+
+		$linkclose='';
+		if (empty($notooltip))
+		{
+		    if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
+		    {
+		        $label=$langs->trans("ShowAccoutingAccount");
+		        $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
+		    }
+		    $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
+		    $linkclose.=' class="classfortooltip"';
+		}
+
+        $linkstart='<a href="'.$url.'"';
+        $linkstart.=$linkclose.'>';
+		$linkend='</a>';
+
+		if ($nourl)
+		{
+			$linkstart = '';
+			$linkclose = '';
+			$linkend = '';			
+		}
 
-		$label = $langs->trans("Show") . ': ' . $this->account_number . ' - ' . $this->label;
+		$label_link = length_accountg($this->account_number);
+		if ($withlabel) $label_link .= ' - ' . $this->label;
 
-		if ($withpicto)
-			$result .= ($link . img_object($label, $picto) . $linkend);
-		if ($withpicto && $withpicto != 2)
-			$result .= ' ';
-		if ($withpicto != 2)
-			require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
-			$result .= $link . length_accountg($this->account_number) . ' - ' . $this->label . $linkend;
+		if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend);
+		if ($withpicto && $withpicto != 2) $result .= ' ';
+		if ($withpicto != 2) $result.=$linkstart . $label_link . $linkend;
 		return $result;
 	}
 	
diff --git a/htdocs/accountancy/class/accountingjournal.class.php b/htdocs/accountancy/class/accountingjournal.class.php
index d7cc61d641892b2d22187c46398d067e2724f4f8..064f56bddd6d60586d21ef74fcea3c5389fcc00f 100644
--- a/htdocs/accountancy/class/accountingjournal.class.php
+++ b/htdocs/accountancy/class/accountingjournal.class.php
@@ -82,208 +82,6 @@ class AccountingJournal extends CommonObject
 		}
 	}
 	
-	/**
-	 * Insert journal in database
-	 *
-	 * @param	User	$user		Use making action
-	 * @param	int		$notrigger	Disable triggers
-	 * @return 	int 				<0 if KO, >0 if OK
-	 */
-	function create($user, $notrigger = 0)
-	{
-		global $conf;
-		$error = 0;
-		$now = dol_now();
-		
-		// Clean parameters
-		if (isset($this->code))
-			$this->code = trim($this->code);
-		if (isset($this->label))
-			$this->label = trim($this->label);
-
-		// Check parameters
-		if (empty($this->nature) || $this->nature == '-1')
-		{
-		    $this->nature = '0';
-		}
-
-		// Insert request
-		$sql = "INSERT INTO " . MAIN_DB_PREFIX . "accounting_journal(";
-		$sql .= "code";
-		$sql .= ", label";
-		$sql .= ", nature";
-		$sql .= ", active";
-		$sql .= ") VALUES (";
-		$sql .= " " . (empty($this->code) ? 'NULL' : "'" . $this->db->escape($this->code) . "'");
-		$sql .= ", " . (empty($this->label) ? 'NULL' : "'" . $this->db->escape($this->label) . "'");
-		$sql .= ", " . (empty($this->nature) ? '0' : "'" . $this->db->escape($this->nature) . "'");
-		$sql .= ", " . (! isset($this->active) ? 'NULL' : $this->db->escape($this->active));
-		$sql .= ")";
-		
-		$this->db->begin();
-		
-		dol_syslog(get_class($this) . "::create sql=" . $sql, LOG_DEBUG);
-		$resql = $this->db->query($sql);
-		if (! $resql) {
-			$error ++;
-			$this->errors[] = "Error " . $this->db->lasterror();
-		}
-		
-		if (! $error) {
-			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . "accounting_journal");
-			
-			// if (! $notrigger) {
-			// Uncomment this and change MYOBJECT to your own tag if you
-			// want this action calls a trigger.
-			
-			// // Call triggers
-			// include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
-			// $interface=new Interfaces($this->db);
-			// $result=$interface->run_triggers('MYOBJECT_CREATE',$this,$user,$langs,$conf);
-			// if ($result < 0) { $error++; $this->errors=$interface->errors; }
-			// // End call triggers
-			// }
-		}
-		
-		// Commit or rollback
-		if ($error) {
-			foreach ( $this->errors as $errmsg ) {
-				dol_syslog(get_class($this) . "::create " . $errmsg, LOG_ERR);
-				$this->error .= ($this->error ? ', ' . $errmsg : $errmsg);
-			}
-			$this->db->rollback();
-			return - 1 * $error;
-		} else {
-			$this->db->commit();
-			return $this->id;
-		}
-	}
-	
-	/**
-	 * Update record
-	 *
-	 * @param  User $user      Use making update
-	 * @return int             <0 if KO, >0 if OK
-	 */
-	function update($user) 
-	{
-	    // Check parameters
-	    if (empty($this->nature) || $this->nature == '-1')
-	    {
-	        $this->nature = '0';
-	    }
-
-	    $this->db->begin();
-		
-		$sql = "UPDATE " . MAIN_DB_PREFIX . "accounting_journal ";
-		$sql .= " SET code = " . ($this->code ? "'" . $this->db->escape($this->code) . "'" : "null");
-		$sql .= " , label = " . ($this->label ? "'" . $this->db->escape($this->label) . "'" : "null");
-		$sql .= " , nature = " . ($this->nature ? "'" . $this->db->escape($this->nature) . "'" : "0");
-		$sql .= " , active = '" . $this->active . "'";
-		$sql .= " WHERE rowid = " . $this->id;
-		
-		dol_syslog(get_class($this) . "::update sql=" . $sql, LOG_DEBUG);
-		$result = $this->db->query($sql);
-		if ($result) {
-			$this->db->commit();
-			return 1;
-		} else {
-			$this->error = $this->db->lasterror();
-			$this->db->rollback();
-			return - 1;
-		}
-	}
-	
-	/**
-	 * Check usage of accounting journal
-	 *
-	 * @return int <0 if KO, >0 if OK
-	 */
-	function checkUsage() {
-		global $langs;
-		
-		$sql = "(SELECT fk_code_ventilation FROM " . MAIN_DB_PREFIX . "facturedet";
-		$sql .= " WHERE  fk_code_ventilation=" . $this->id . ")";
-		$sql .= "UNION";
-		$sql .= "(SELECT fk_code_ventilation FROM " . MAIN_DB_PREFIX . "facture_fourn_det";
-		$sql .= " WHERE  fk_code_ventilation=" . $this->id . ")";
-		
-		dol_syslog(get_class($this) . "::checkUsage sql=" . $sql, LOG_DEBUG);
-		$resql = $this->db->query($sql);
-		
-		if ($resql) {
-			$num = $this->db->num_rows($resql);
-			if ($num > 0) {
-				$this->error = $langs->trans('ErrorAccountingJournalIsAlreadyUse');
-				return 0;
-			} else {
-				return 1;
-			}
-		} else {
-			$this->error = $this->db->lasterror();
-			return - 1;
-		}
-	}
-	
-	/**
-	 * Delete object in database
-	 *
-	 * @param User $user User that deletes
-	 * @param int $notrigger 0=triggers after, 1=disable triggers
-	 * @return int <0 if KO, >0 if OK
-	 */
-	function delete($user, $notrigger = 0) {
-		$error = 0;
-		
-		$result = $this->checkUsage();
-		
-		if ($result > 0) {
-			
-			$this->db->begin();
-			
-			// if (! $error) {
-			// if (! $notrigger) {
-			// Uncomment this and change MYOBJECT to your own tag if you
-			// want this action calls a trigger.
-			
-			// // Call triggers
-			// include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
-			// $interface=new Interfaces($this->db);
-			// $result=$interface->run_triggers('ACCOUNTANCY_ACCOUNT_DELETE',$this,$user,$langs,$conf);
-			// if ($result < 0) { $error++; $this->errors=$interface->errors; }
-			// // End call triggers
-			// }
-			// }
-			
-			if (! $error) {
-				$sql = "DELETE FROM " . MAIN_DB_PREFIX . "accounting_journal";
-				$sql .= " WHERE rowid=" . $this->id;
-				
-				dol_syslog(get_class($this) . "::delete sql=" . $sql);
-				$resql = $this->db->query($sql);
-				if (! $resql) {
-					$error ++;
-					$this->errors[] = "Error " . $this->db->lasterror();
-				}
-			}
-			
-			// Commit or rollback
-			if ($error) {
-				foreach ( $this->errors as $errmsg ) {
-					dol_syslog(get_class($this) . "::delete " . $errmsg, LOG_ERR);
-					$this->error .= ($this->error ? ', ' . $errmsg : $errmsg);
-				}
-				$this->db->rollback();
-				return - 1 * $error;
-			} else {
-				$this->db->commit();
-				return 1;
-			}
-		} else {
-			return - 1;
-		}
-	}
-	
 	/**
 	 * Return clicable name (with picto eventually)
 	 *
@@ -311,64 +109,6 @@ class AccountingJournal extends CommonObject
 		return $result;
 	}
 	
-	/**
-	 * Deactivate journal
-	 *
-	 * @param int $id Id
-	 * @return int <0 if KO, >0 if OK
-	 */
-	function journal_deactivate($id) {
-		$result = $this->checkUsage();
-		
-		if ($result > 0) {
-			$this->db->begin();
-			
-			$sql = "UPDATE " . MAIN_DB_PREFIX . "accounting_journal ";
-			$sql .= "SET active = '0'";
-			$sql .= " WHERE rowid = " . $this->db->escape($id);
-			
-			dol_syslog(get_class($this) . "::deactivate sql=" . $sql, LOG_DEBUG);
-			$result = $this->db->query($sql);
-			
-			if ($result) {
-				$this->db->commit();
-				return 1;
-			} else {
-				$this->error = $this->db->lasterror();
-				$this->db->rollback();
-				return - 1;
-			}
-		} else {
-			return - 1;
-		}
-	}
-	
-	/**
-	 * Activate journal
-	 *
-	 * @param int $id Id
-	 * @return int <0 if KO, >0 if OK
-	 */
-	function journal_activate($id) {
-		$this->db->begin();
-		
-		$sql = "UPDATE " . MAIN_DB_PREFIX . "accounting_journal ";
-		$sql .= "SET active = '1'";
-		$sql .= " WHERE rowid = " . $this->db->escape($id);
-		
-		dol_syslog(get_class($this) . "::activate sql=" . $sql, LOG_DEBUG);
-		$result = $this->db->query($sql);
-		if ($result) {
-			$this->db->commit();
-			return 1;
-		} else {
-			$this->error = $this->db->lasterror();
-			$this->db->rollback();
-			return - 1;
-		}
-	}
-	
-	
 	/**
 	 *  Retourne le libelle du statut d'un user (actif, inactif)
 	 *
diff --git a/htdocs/accountancy/class/bookkeeping.class.php b/htdocs/accountancy/class/bookkeeping.class.php
index 754dd262369e556ca6ed190f58f4c23a8571e3bd..8f31b40bc54fee586a0fcd350d9888584cf547df 100644
--- a/htdocs/accountancy/class/bookkeeping.class.php
+++ b/htdocs/accountancy/class/bookkeeping.class.php
@@ -169,7 +169,15 @@ class BookKeeping extends CommonObject
 		if (empty($this->numero_compte) || $this->numero_compte == '-1')
 		{
 		    $langs->load("errors");
-            $this->errors[]=$langs->trans('ErrorFieldAccountNotDefinedForBankLine', $this->fk_docdet);		    
+            if (in_array($this->doc_type, array('bank', 'expense_report')))
+            {
+		        $this->errors[]=$langs->trans('ErrorFieldAccountNotDefinedForBankLine', $this->fk_docdet,  $this->doc_type);
+            }
+            else
+            {
+                $this->errors[]=$langs->trans('ErrorFieldAccountNotDefinedForInvoiceLine', $this->fk_doc,  $this->doc_type);		    
+            }
+		    
 		    return -1;
 		}
 		
@@ -178,11 +186,12 @@ class BookKeeping extends CommonObject
 		
 		$this->piece_num = 0;
 		
-		// first check if line not yet in bookkeeping
+		// First check if line not yet already in bookkeeping
 		$sql = "SELECT count(*) as nb";
 		$sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element;
 		$sql .= " WHERE doc_type = '" . $this->doc_type . "'";
-		$sql .= " AND fk_docdet = " . $this->fk_docdet;
+		$sql .= " AND fk_doc = " . $this->fk_doc;
+		$sql .= " AND fk_docdet = " . $this->fk_docdet;                   // This field can be 0 is record is for several lines 
 		$sql .= " AND numero_compte = '" . $this->numero_compte . "'";
 	    $sql .= " AND entity IN (" . getEntity("accountancy", 1) . ")";
 		
diff --git a/htdocs/accountancy/customer/lines.php b/htdocs/accountancy/customer/lines.php
index a015fa05929b14f6a4793b19a4e59339e13cb20e..428e490aff7057455476ae9dfc3688ea520f3ad0 100644
--- a/htdocs/accountancy/customer/lines.php
+++ b/htdocs/accountancy/customer/lines.php
@@ -43,6 +43,7 @@ $langs->load("productbatch");
 $account_parent = GETPOST('account_parent');
 $changeaccount = GETPOST('changeaccount');
 // Search Getpost
+$search_lineid = GETPOST('search_lineid', 'int');
 $search_ref = GETPOST('search_ref', 'alpha');
 $search_invoice = GETPOST('search_invoice', 'alpha');
 $search_label = GETPOST('search_label', 'alpha');
@@ -86,6 +87,7 @@ $formventilation = new FormVentilation($db);
 // Purge search criteria
 if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // All tests are required to be compatible with all browsers
 {
+    $search_lineid = '';
 	$search_ref = '';
 	$search_invoice = '';
 	$search_label = '';
@@ -151,7 +153,7 @@ print '<script type="text/javascript">
  * Customer Invoice lines
  */
 $sql = "SELECT f.rowid, f.facnumber, f.type, f.datef, f.ref_client,";
-$sql .= " fd.rowid as fdid, fd.description, fd.product_type, fd.total_ht, fd.total_tva, fd.tva_tx, fd.total_ttc,";
+$sql .= " fd.rowid, fd.description, fd.product_type, fd.total_ht, fd.total_tva, fd.tva_tx, fd.total_ttc,";
 $sql .= " s.rowid as socid, s.nom as name, s.code_compta, s.code_client,";
 $sql .= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.accountancy_code_sell, aa.rowid as fk_compte, aa.account_number, aa.label as label_compte,";
 $sql .= " fd.situation_percent, co.label as country, s.tva_intra";
@@ -169,6 +171,9 @@ if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
 } else {
 	$sql .= " AND f.type IN (" . Facture::TYPE_STANDARD . "," . Facture::TYPE_STANDARD . "," . Facture::TYPE_CREDIT_NOTE . "," . Facture::TYPE_DEPOSIT . "," . Facture::TYPE_SITUATION . ")";
 }
+if ($search_lineid) {
+    $sql .= natural_search("fd.rowid", $search_lineid, 1);
+}
 if (strlen(trim($search_invoice))) {
 	$sql .= natural_search("f.facnumber", $search_invoice);
 }
@@ -257,7 +262,7 @@ if ($result) {
 	print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n";
 	
 	print '<tr class="liste_titre_filter">';
-	print '<td class="liste_titre"></td>';
+	print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_lineid" value="' . dol_escape_htmltag($search_lineid) . '""></td>';
 	print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_invoice" value="' . dol_escape_htmltag($search_invoice) . '"></td>';
 	print '<td class="liste_titre"></td>';
 	print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_ref" value="' . dol_escape_htmltag($search_ref) . '"></td>';
@@ -328,13 +333,16 @@ if ($result) {
 		print '<td align="right">' . price($objp->total_ht) . '</td>';
 		print '<td align="center">' . price($objp->tva_tx) . '</td>';
 		print '<td>';
-		print $codecompta . ' <a href="./card.php?id=' . $objp->fdid . '">';
+		print $codecompta . ' <a href="./card.php?id=' . $objp->rowid . '">';
 		print img_edit();
 		print '</a>';
 		print '</td>';
+		
 		print '<td>' . $objp->country .'</td>';
+		
 		print '<td>' . $objp->tva_intra . '</td>';
-		print '<td class="center"><input type="checkbox" class="checkforaction" name="changeaccount[]" value="' . $objp->fdid . '"/></td>';
+		
+		print '<td class="center"><input type="checkbox" class="checkforaction" name="changeaccount[]" value="' . $objp->rowid . '"/></td>';
 
 		print "</tr>";
 		$i ++;
diff --git a/htdocs/accountancy/customer/list.php b/htdocs/accountancy/customer/list.php
index c5830b0b003d06a38765b7c62e954f36ff34cb47..46cb19c2ae1382af8406f18381682dc80705a66b 100644
--- a/htdocs/accountancy/customer/list.php
+++ b/htdocs/accountancy/customer/list.php
@@ -52,6 +52,7 @@ $toselect = GETPOST('toselect', 'array');
 $mesCasesCochees = GETPOST('toselect', 'array');
 
 // Search Getpost
+$search_lineid = GETPOST('search_lineid', 'int');
 $search_invoice = GETPOST('search_invoice', 'alpha');
 $search_ref = GETPOST('search_ref', 'alpha');
 $search_label = GETPOST('search_label', 'alpha');
@@ -100,6 +101,7 @@ if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction !=
 // Purge search criteria
 if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // All test are required to be compatible with all browsers
 {
+    $search_lineid = '';
 	$search_ref = '';
 	$search_invoice = '';
 	$search_label = '';
@@ -177,7 +179,7 @@ llxHeader('', $langs->trans("Ventilation"));
 
 // Customer Invoice lines
 $sql = "SELECT f.facnumber, f.rowid as facid, f.datef, f.type as ftype,";
-$sql .= " l.fk_product, l.description, l.total_ht, l.rowid, l.fk_code_ventilation, l.product_type as type_l, l.tva_tx as tva_tx_line,";
+$sql .= " l.rowid, l.fk_product, l.description, l.total_ht, l.fk_code_ventilation, l.product_type as type_l, l.tva_tx as tva_tx_line,";
 $sql .= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.fk_product_type as type, p.accountancy_code_sell as code_sell, p.tva_tx as tva_tx_prod,";
 $sql .= " aa.rowid as aarowid";
 $sql .= " FROM " . MAIN_DB_PREFIX . "facture as f";
@@ -189,6 +191,9 @@ $sql .= " WHERE f.fk_statut > 0 AND l.fk_code_ventilation <= 0";
 $sql .= " AND product_type <= 2";
 $sql .= " AND (accsys.rowid='" . $conf->global->CHARTOFACCOUNTS . "' OR p.accountancy_code_sell IS NULL OR p.accountancy_code_sell ='')";
 // Add search filter like
+if ($search_lineid) {
+    $sql .= natural_search("l.rowid", $search_lineid, 1);
+}
 if (strlen(trim($search_invoice))) {
     $sql .= natural_search("f.facnumber",$search_invoice);
 }
@@ -274,7 +279,7 @@ if ($result) {
 
 	// We add search filter
 	print '<tr class="liste_titre_filter">';
-	print '<td class="liste_titre"></td>';
+	print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_lineid" value="' . dol_escape_htmltag($search_lineid) . '""></td>';
 	print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_invoice" value="' . dol_escape_htmltag($search_invoice) . '"></td>';
 	print '<td class="liste_titre"></td>';
 	print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_ref" value="' . dol_escape_htmltag($search_ref) . '"></td>';
diff --git a/htdocs/accountancy/index.php b/htdocs/accountancy/index.php
index ff9ca6fa1a341309a5f3a6226ed2abfd45aad17a..c7caa5daac3daa184f90c45d989a5314c9387329 100644
--- a/htdocs/accountancy/index.php
+++ b/htdocs/accountancy/index.php
@@ -71,6 +71,10 @@ print "<br>\n";
 
 // STEPS
 $step++;
+print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescJournalSetup", $step, '<strong>'.$langs->transnoentitiesnoconv("MenuFinancial").'-'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("AccountingJournals").'</strong>');
+print "<br>\n";
+print "<br>\n";
+$step++;
 print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescChartModel", $step, '<strong>'.$langs->transnoentitiesnoconv("MenuFinancial").'-'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("Pcg_version").'</strong>');
 print "<br>\n";
 print "<br>\n";
@@ -148,24 +152,26 @@ print '<hr>';
 print "<br>\n";
 $step = 0;
 
+$langs->loadLangs(array('bills', 'trips'));
+
 $step++;
-print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescCustomer", $step, '<strong>'.$langs->transnoentitiesnoconv("MenuFinancial").'-'.$langs->transnoentitiesnoconv("MenuAccountancy")."-".$langs->transnoentitiesnoconv("CustomersVentilation").'</strong>')."<br>\n";
+print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescBind", chr(64+$step), $langs->transnoentitiesnoconv("BillsCustomers"), '<strong>'.$langs->transnoentitiesnoconv("MenuFinancial").'-'.$langs->transnoentitiesnoconv("MenuAccountancy")."-".$langs->transnoentitiesnoconv("CustomersVentilation").'</strong>')."<br>\n";
 print "<br>\n";
 
 $step++;
-print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescSupplier", $step, '<strong>'.$langs->transnoentitiesnoconv("MenuFinancial").'-'.$langs->transnoentitiesnoconv("MenuAccountancy")."-".$langs->transnoentitiesnoconv("SuppliersVentilation").'</strong>')."<br>\n";
+print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescBind", chr(64+$step), $langs->transnoentitiesnoconv("BillsSuppliers"), '<strong>'.$langs->transnoentitiesnoconv("MenuFinancial").'-'.$langs->transnoentitiesnoconv("MenuAccountancy")."-".$langs->transnoentitiesnoconv("SuppliersVentilation").'</strong>')."<br>\n";
 print "<br>\n";
 
 $step++;
-print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescExpenseReport", $step, '<strong>'.$langs->transnoentitiesnoconv("MenuFinancial").'-'.$langs->transnoentitiesnoconv("MenuAccountancy")."-".$langs->transnoentitiesnoconv("ExpenseReportsVentilation").'</strong>')."<br>\n";
+print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescBind", chr(64+$step), $langs->transnoentitiesnoconv("ExpenseReports"), '<strong>'.$langs->transnoentitiesnoconv("MenuFinancial").'-'.$langs->transnoentitiesnoconv("MenuAccountancy")."-".$langs->transnoentitiesnoconv("ExpenseReportsVentilation").'</strong>')."<br>\n";
 print "<br>\n";
 
 $step++;
-print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescWriteRecords", $step)."<br>\n";
+print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescWriteRecords", chr(64+$step), $langs->transnoentitiesnoconv("Journalization"), $langs->transnoentitiesnoconv("WriteBookKeeping"))."<br>\n";
 print "<br>\n";
 
 $step++;
-print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescAnalyze", $step)."<br>\n";
+print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescAnalyze", chr(64+$step))."<br>\n";
 print "<br>\n";
 
 llxFooter();
diff --git a/htdocs/accountancy/journal/bankjournal.php b/htdocs/accountancy/journal/bankjournal.php
index b9567cd50a7847ec3af305544429b6cac519f4d6..a68798869a2f2efad9531aba1de75ad9d65dca0b 100644
--- a/htdocs/accountancy/journal/bankjournal.php
+++ b/htdocs/accountancy/journal/bankjournal.php
@@ -106,7 +106,7 @@ if (empty($date_start) || empty($date_end)) // We define date_start and date_end
 $p = explode(":", $conf->global->MAIN_INFO_SOCIETE_COUNTRY);
 $idpays = $p[0];
 
-$sql  = "SELECT b.rowid , b.dateo as do, b.datev as dv, b.amount, b.label, b.rappro, b.num_releve, b.num_chq, b.fk_type,";
+$sql  = "SELECT b.rowid, b.dateo as do, b.datev as dv, b.amount, b.label, b.rappro, b.num_releve, b.num_chq, b.fk_type,";
 $sql .= " ba.courant, ba.ref as baref, ba.account_number,";
 $sql .= " soc.code_compta, soc.code_compta_fournisseur, soc.rowid as socid, soc.nom as name, bu1.type as typeop,";
 $sql .= " u.accountancy_code, u.rowid as userid, u.lastname as name, u.firstname as firstname, bu2.type as typeop";
@@ -341,79 +341,81 @@ if (! $error && $action == 'writebookkeeping') {
 		    // Line into bank account
     		foreach ( $tabbq[$key] as $k => $mt ) 
     		{
-    			$bookkeeping = new BookKeeping($db);
-    			$bookkeeping->doc_date = $val["date"];
-    			$bookkeeping->doc_ref = $val["ref"];
-    			$bookkeeping->doc_type = 'bank';
-    			$bookkeeping->fk_doc = $key;
-    			$bookkeeping->fk_docdet = $val["fk_bank"];
-    			$bookkeeping->numero_compte = $k;
-    			$bookkeeping->label_compte = $compte->label;
-    			$bookkeeping->montant = ($mt < 0 ? - $mt : $mt);
-    			$bookkeeping->sens = ($mt >= 0) ? 'D' : 'C';
-    			$bookkeeping->debit = ($mt >= 0 ? $mt : 0);
-    			$bookkeeping->credit = ($mt < 0 ? - $mt : 0);
-    			$bookkeeping->code_journal = $journal;
-    			$bookkeeping->fk_user_author = $user->id;
-    			$bookkeeping->date_create = $now;
+    			if ($mt) {
+        		    $bookkeeping = new BookKeeping($db);
+        			$bookkeeping->doc_date = $val["date"];
+        			$bookkeeping->doc_ref = $val["ref"];
+        			$bookkeeping->doc_type = 'bank';
+        			$bookkeeping->fk_doc = $key;
+        			$bookkeeping->fk_docdet = $val["fk_bank"];
+        			$bookkeeping->numero_compte = $k;
+        			$bookkeeping->label_compte = $compte->label;
+        			$bookkeeping->montant = ($mt < 0 ? - $mt : $mt);
+        			$bookkeeping->sens = ($mt >= 0) ? 'D' : 'C';
+        			$bookkeeping->debit = ($mt >= 0 ? $mt : 0);
+        			$bookkeeping->credit = ($mt < 0 ? - $mt : 0);
+        			$bookkeeping->code_journal = $journal;
+        			$bookkeeping->fk_user_author = $user->id;
+        			$bookkeeping->date_create = $now;
+        
+        			if ($tabtype[$key] == 'payment') {
+        			    $bookkeeping->code_tiers = $tabcompany[$key]['code_compta'];
     
-    			if ($tabtype[$key] == 'payment') {
-    			    $bookkeeping->code_tiers = $tabcompany[$key]['code_compta'];
-
-    				$sqlmid = 'SELECT fac.facnumber';
-    				$sqlmid .= " FROM " . MAIN_DB_PREFIX . "facture fac";
-    				$sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement_facture as payfac ON payfac.fk_facture=fac.rowid";
-    				$sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement as pay ON  payfac.fk_paiement=pay.rowid";
-    				$sqlmid .= " WHERE pay.fk_bank=" . $key;
-    				dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG);
-    				$resultmid = $db->query($sqlmid);
-    				if ($resultmid) {
-    					$objmid = $db->fetch_object($resultmid);
-    					$bookkeeping->doc_ref = $objmid->facnumber;    // Ref of invoice
-    				}
-    			} else if ($tabtype[$key] == 'payment_supplier') {
-    			    $bookkeeping->code_tiers = $tabcompany[$key]['code_compta'];
-
-    				$sqlmid = 'SELECT facf.ref_supplier, facf.ref';
-    				$sqlmid .= " FROM " . MAIN_DB_PREFIX . "facture_fourn facf";
-    				$sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiementfourn_facturefourn as payfacf ON payfacf.fk_facturefourn=facf.rowid";
-    				$sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiementfourn as payf ON  payfacf.fk_paiementfourn=payf.rowid";
-    				$sqlmid .= " WHERE payf.fk_bank=" . $key;
-    				dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG);
-    				$resultmid = $db->query($sqlmid);
-    				if ($resultmid) {
-    					$objmid = $db->fetch_object($resultmid);
-    					$bookkeeping->doc_ref = $objmid->ref_supplier . ' (' . $objmid->ref . ')'; // Ref on invoice
-    				}
-    			} else if ($tabtype[$key] == 'payment_expensereport') {
-    			    $bookkeeping->code_tiers = $tabuser[$key]['accountancy_code'];
-
-    				$sqlmid = 'SELECT e.ref';
-    				$sqlmid .= " FROM " . MAIN_DB_PREFIX . "expensereport as e";
-    				$sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "payment_expensereport as payer ON payer.fk_expensereport=e.rowid";
-    				$sqlmid .= " WHERE payer.fk_expensereport=" . $val["fk_expensereport"];
-    				dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG);
-    				$resultmid = $db->query($sqlmid);
-    				if ($resultmid) {
-    					$objmid = $db->fetch_object($resultmid);
-    					$bookkeeping->doc_ref = $objmid->ref; // Ref of expensereport
-    				}
-    			}
+        				$sqlmid = 'SELECT fac.facnumber';
+        				$sqlmid .= " FROM " . MAIN_DB_PREFIX . "facture fac";
+        				$sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement_facture as payfac ON payfac.fk_facture=fac.rowid";
+        				$sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement as pay ON  payfac.fk_paiement=pay.rowid";
+        				$sqlmid .= " WHERE pay.fk_bank=" . $key;
+        				dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG);
+        				$resultmid = $db->query($sqlmid);
+        				if ($resultmid) {
+        					$objmid = $db->fetch_object($resultmid);
+        					$bookkeeping->doc_ref = $objmid->facnumber;    // Ref of invoice
+        				}
+        			} else if ($tabtype[$key] == 'payment_supplier') {
+        			    $bookkeeping->code_tiers = $tabcompany[$key]['code_compta'];
+    
+        				$sqlmid = 'SELECT facf.ref_supplier, facf.ref';
+        				$sqlmid .= " FROM " . MAIN_DB_PREFIX . "facture_fourn facf";
+        				$sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiementfourn_facturefourn as payfacf ON payfacf.fk_facturefourn=facf.rowid";
+        				$sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiementfourn as payf ON  payfacf.fk_paiementfourn=payf.rowid";
+        				$sqlmid .= " WHERE payf.fk_bank=" . $key;
+        				dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG);
+        				$resultmid = $db->query($sqlmid);
+        				if ($resultmid) {
+        					$objmid = $db->fetch_object($resultmid);
+        					$bookkeeping->doc_ref = $objmid->ref_supplier . ' (' . $objmid->ref . ')'; // Ref on invoice
+        				}
+        			} else if ($tabtype[$key] == 'payment_expensereport') {
+        			    $bookkeeping->code_tiers = $tabuser[$key]['accountancy_code'];
     
-    			$result = $bookkeeping->create($user);
-    			if ($result < 0) {
-    				if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists')	// Already exists
-    				{
-    					$error++;
-    					$errorforline++;
-    					//setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->doc_ref.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
-    				}
-    				else
-    				{
-	    				$error++;
-	    				$errorforline++;
-	    				setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
-    				}
+        				$sqlmid = 'SELECT e.ref';
+        				$sqlmid .= " FROM " . MAIN_DB_PREFIX . "expensereport as e";
+        				$sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "payment_expensereport as payer ON payer.fk_expensereport=e.rowid";
+        				$sqlmid .= " WHERE payer.fk_expensereport=" . $val["fk_expensereport"];
+        				dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG);
+        				$resultmid = $db->query($sqlmid);
+        				if ($resultmid) {
+        					$objmid = $db->fetch_object($resultmid);
+        					$bookkeeping->doc_ref = $objmid->ref; // Ref of expensereport
+        				}
+        			}
+        
+        			$result = $bookkeeping->create($user);
+        			if ($result < 0) {
+        				if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists')	// Already exists
+        				{
+        					$error++;
+        					$errorforline++;
+        					//setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->doc_ref.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
+        				}
+        				else
+        				{
+    	    				$error++;
+    	    				$errorforline++;
+    	    				setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
+        				}
+        			}
     			}
     		}
 		}
@@ -423,65 +425,76 @@ if (! $error && $action == 'writebookkeeping') {
 		{
 		    // Line into thirdparty account
     		foreach ( $tabtp[$key] as $k => $mt ) {
-    			$bookkeeping = new BookKeeping($db);
-    			$bookkeeping->doc_date = $val["date"];
-    			$bookkeeping->doc_ref = $val["ref"];
-    			$bookkeeping->doc_type = 'bank';
-    			$bookkeeping->fk_doc = $key;
-    			$bookkeeping->fk_docdet = $val["fk_bank"];
-    			$bookkeeping->label_compte = $tabcompany[$key]['name'];
-    			$bookkeeping->montant = ($mt < 0 ? - $mt : $mt);
-    			$bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
-    			$bookkeeping->debit = ($mt < 0 ? - $mt : 0);
-    			$bookkeeping->credit = ($mt >= 0) ? $mt : 0;
-    			$bookkeeping->code_journal = $journal;
-    			$bookkeeping->fk_user_author = $user->id;
-    			$bookkeeping->date_create = $now;
-    
-    			if (in_array($tabtype[$key], array('sc', 'payment_sc'))) {   // If payment is payment of social contribution
-    				$bookkeeping->code_tiers = '';
-    				$bookkeeping->numero_compte = $k;
-    			} else if ($tabtype[$key] == 'payment') {    // If payment is payment of customer invoice, we get ref of invoice
-    				$sqlmid = 'SELECT fac.facnumber';
-    				$sqlmid .= " FROM " . MAIN_DB_PREFIX . "facture fac ";
-    				$sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement_facture as payfac ON  payfac.fk_facture=fac.rowid";
-    				$sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement as pay ON  payfac.fk_paiement=pay.rowid";
-    				$sqlmid .= " WHERE pay.fk_bank=" . $key;
-    				dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG);
-    				$resultmid = $db->query($sqlmid);
-    				if ($resultmid) {
-    					$objmid = $db->fetch_object($resultmid);
-    					$bookkeeping->doc_ref = $objmid->facnumber;
-    				}
-    				$bookkeeping->code_tiers = $tabcompany[$key]['code_compta'];
-    				$bookkeeping->numero_compte = $k;
-    			} else if ($tabtype[$key] == 'payment_supplier') {           // If payment is payment of supplier invoice, we get ref of invoice
-    
-    				$sqlmid = 'SELECT facf.ref_supplier,facf.ref';
-    				$sqlmid .= " FROM " . MAIN_DB_PREFIX . "facture_fourn facf ";
-    				$sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiementfourn_facturefourn as payfacf ON  payfacf.fk_facturefourn=facf.rowid";
-    				$sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiementfourn as payf ON  payfacf.fk_paiementfourn=payf.rowid";
-    				$sqlmid .= " WHERE payf.fk_bank=" . $key;
-    				dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG);
-    				$resultmid = $db->query($sqlmid);
-    				if ($resultmid) {
-    					$objmid = $db->fetch_object($resultmid);
-    					$bookkeeping->doc_ref = $objmid->ref_supplier . ' (' . $objmid->ref . ')';
-    				}
-                    $bookkeeping->code_tiers = $tabcompany[$key]['code_compta'];
-    				$bookkeeping->numero_compte = $k;
-    			} else {
-    			    // FIXME Should be a temporary account ???
-    				$bookkeeping->doc_ref = $k;
-    				//$bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER;
-    				$bookkeeping->numero_compte = 'CodeNotDef';
-    			}
-    
-    			$result = $bookkeeping->create($user);
-    			if ($result < 0) {
-    				$error++;
-    				$errorforline++;
-    				setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
+    			if ($mt) {
+        		    $bookkeeping = new BookKeeping($db);
+        			$bookkeeping->doc_date = $val["date"];
+        			$bookkeeping->doc_ref = $val["ref"];
+        			$bookkeeping->doc_type = 'bank';
+        			$bookkeeping->fk_doc = $key;
+        			$bookkeeping->fk_docdet = $val["fk_bank"];
+        			$bookkeeping->label_compte = $tabcompany[$key]['name'];
+        			$bookkeeping->montant = ($mt < 0 ? - $mt : $mt);
+        			$bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
+        			$bookkeeping->debit = ($mt < 0 ? - $mt : 0);
+        			$bookkeeping->credit = ($mt >= 0) ? $mt : 0;
+        			$bookkeeping->code_journal = $journal;
+        			$bookkeeping->fk_user_author = $user->id;
+        			$bookkeeping->date_create = $now;
+        
+        			if (in_array($tabtype[$key], array('sc', 'payment_sc'))) {   // If payment is payment of social contribution
+        				$bookkeeping->code_tiers = '';
+        				$bookkeeping->numero_compte = $k;
+        			} else if ($tabtype[$key] == 'payment') {    // If payment is payment of customer invoice, we get ref of invoice
+        				$sqlmid = 'SELECT fac.facnumber';
+        				$sqlmid .= " FROM " . MAIN_DB_PREFIX . "facture fac ";
+        				$sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement_facture as payfac ON  payfac.fk_facture=fac.rowid";
+        				$sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement as pay ON  payfac.fk_paiement=pay.rowid";
+        				$sqlmid .= " WHERE pay.fk_bank=" . $key;
+        				dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG);
+        				$resultmid = $db->query($sqlmid);
+        				if ($resultmid) {
+        					$objmid = $db->fetch_object($resultmid);
+        					$bookkeeping->doc_ref = $objmid->facnumber;
+        				}
+        				$bookkeeping->code_tiers = $tabcompany[$key]['code_compta'];
+        				$bookkeeping->numero_compte = $k;
+        			} else if ($tabtype[$key] == 'payment_supplier') {           // If payment is payment of supplier invoice, we get ref of invoice
+        
+        				$sqlmid = 'SELECT facf.ref_supplier,facf.ref';
+        				$sqlmid .= " FROM " . MAIN_DB_PREFIX . "facture_fourn facf ";
+        				$sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiementfourn_facturefourn as payfacf ON  payfacf.fk_facturefourn=facf.rowid";
+        				$sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiementfourn as payf ON  payfacf.fk_paiementfourn=payf.rowid";
+        				$sqlmid .= " WHERE payf.fk_bank=" . $key;
+        				dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG);
+        				$resultmid = $db->query($sqlmid);
+        				if ($resultmid) {
+        					$objmid = $db->fetch_object($resultmid);
+        					$bookkeeping->doc_ref = $objmid->ref_supplier . ' (' . $objmid->ref . ')';
+        				}
+                        $bookkeeping->code_tiers = $tabcompany[$key]['code_compta'];
+        				$bookkeeping->numero_compte = $k;
+        			} else {
+        			    // FIXME Should be a temporary account ???
+        				$bookkeeping->doc_ref = $k;
+        				//$bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER;
+        				$bookkeeping->numero_compte = 'CodeNotDef';
+        			}
+        
+        			$result = $bookkeeping->create($user);
+        			if ($result < 0) {
+        				if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists')	// Already exists
+        				{
+        					$error++;
+        					$errorforline++;
+        					//setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->doc_ref.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
+        				}
+        				else
+        				{
+    	    				$error++;
+    	    				$errorforline++;
+    	    				setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
+        				}
+        			}
     			}
     		}
 		}
@@ -512,6 +525,7 @@ if (! $error && $action == 'writebookkeeping') {
 }
 
 // Export
+/*
 if ($action == 'export_csv') {
 	$sep = $conf->global->ACCOUNTING_EXPORT_SEPARATORCSV;
 
@@ -678,8 +692,7 @@ if ($action == 'export_csv') {
 		}
 	}
 }
-
-
+*/
 
 
 /*
@@ -702,18 +715,19 @@ if (empty($action) || $action == 'view') {
 	$period = $form->select_date($date_start, 'date_start', 0, 0, 0, '', 1, 0, 1) . ' - ' . $form->select_date($date_end, 'date_end', 0, 0, 0, '', 1, 0, 1);
 
 	$varlink = 'id_account=' . $id_bank_account;
-	report_header($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, array (
-			'action' => ''
-	), '', $varlink);
+	
+	journalHead($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, array('action' => ''), '', $varlink);
 
-	if ($conf->global->ACCOUNTING_EXPORT_MODELCSV != 1 && $conf->global->ACCOUNTING_EXPORT_MODELCSV != 2) {
+	/*if ($conf->global->ACCOUNTING_EXPORT_MODELCSV != 1 && $conf->global->ACCOUNTING_EXPORT_MODELCSV != 2) {
 		print '<input type="button" class="butActionRefused" style="float: right;" value="' . $langs->trans('Export') . '" disabled="disabled" title="' . $langs->trans('ExportNotSupported') . '"/>';
 	} else {
 		print '<input type="button" class="butAction" style="float: right;" value="' . $langs->trans("Export") . '" onclick="launch_export();" />';
-	}
+	}*/
 
+    print '<div class="tabsAction">';
 	print '<input type="button" class="butAction" value="' . $langs->trans("WriteBookKeeping") . '" onclick="writebookkeeping();" />';
-
+    print '</div>';
+    
 	// TODO Avoid using js. We can use a direct link with $param
 	print '
 	<script type="text/javascript">
@@ -734,7 +748,7 @@ if (empty($action) || $action == 'view') {
 	/*
 	 * Show result array
 	 */
-	print '<br><br>';
+	print '<br>';
 
 	$i = 0;
 	print "<table class=\"noborder\" width=\"100%\">";
diff --git a/htdocs/accountancy/journal/expensereportsjournal.php b/htdocs/accountancy/journal/expensereportsjournal.php
index a281b7fef8d380688b9e4728f41746cd681162c2..8e343bcbb0866b28f84156c7d77b428c18fa204c 100644
--- a/htdocs/accountancy/journal/expensereportsjournal.php
+++ b/htdocs/accountancy/journal/expensereportsjournal.php
@@ -157,100 +157,140 @@ if ($action == 'writebookkeeping') {
 	{
 		$errorforline = 0;
 
-		foreach ( $tabttc[$key] as $k => $mt ) {
-			// get compte id and label
-
-			$bookkeeping = new BookKeeping($db);
-			$bookkeeping->doc_date = $val["date"];
-			$bookkeeping->doc_ref = $val["ref"];
-			$bookkeeping->date_create = $now;
-			$bookkeeping->doc_type = 'expense_report';
-			$bookkeeping->fk_doc = $key;
-			$bookkeeping->fk_docdet = $val["fk_expensereportdet"];
-			$bookkeeping->code_tiers = $tabuser[$key]['user_accountancy_code'];
-			$bookkeeping->label_compte = $tabuser[$key]['name'];
-			$bookkeeping->numero_compte = $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT;
-			$bookkeeping->montant = $mt;
-			$bookkeeping->sens = ($mt >= 0) ? 'C' : 'D';
-			$bookkeeping->debit = ($mt <= 0) ? $mt : 0;
-			$bookkeeping->credit = ($mt > 0) ? $mt : 0;
-			$bookkeeping->code_journal = $conf->global->ACCOUNTING_EXPENSEREPORT_JOURNAL;
-			$bookkeeping->fk_user_author = $user->id;
-
-			$result = $bookkeeping->create($user);
-			if ($result < 0) {
-				$error++;
-				$errorforline++;
-				setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
-			}
-		}
-
-		// Fees
-		foreach ( $tabht[$key] as $k => $mt ) {
-			$accountingaccount = new AccountingAccount($db);
-			$accountingaccount->fetch(null, $k, true);
-			if ($mt) {
-				// get compte id and label
-				$accountingaccount = new AccountingAccount($db);
-				if ($accountingaccount->fetch(null, $k, true)) {
-					$bookkeeping = new BookKeeping($db);
-					$bookkeeping->doc_date = $val["date"];
-					$bookkeeping->doc_ref = $val["ref"];
-					$bookkeeping->date_create = $now;
-					$bookkeeping->doc_type = 'expense_report';
-					$bookkeeping->fk_doc = $key;
-					$bookkeeping->fk_docdet = $val["fk_expensereportdet"];
-					$bookkeeping->code_tiers = '';
-					$bookkeeping->label_compte = $accountingaccount->label;
-					$bookkeeping->numero_compte = $k;
-					$bookkeeping->montant = $mt;
-					$bookkeeping->sens = ($mt < 0) ? 'C' : 'D';
-					$bookkeeping->debit = ($mt > 0) ? $mt : 0;
-					$bookkeeping->credit = ($mt <= 0) ? $mt : 0;
-					$bookkeeping->code_journal = $conf->global->ACCOUNTING_EXPENSEREPORT_JOURNAL;
-					$bookkeeping->fk_user_author = $user->id;
-
-					$result = $bookkeeping->create($user);
-					if ($result < 0) {
-						$error++;
-						$errorforline++;
-						setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
-					}
-				}
-			}
-		}
-
-		// VAT
-		// var_dump($tabtva);
-		foreach ( $tabtva[$key] as $k => $mt ) {
-			if ($mt) {
-				// get compte id and label
-				$bookkeeping = new BookKeeping($db);
-				$bookkeeping->doc_date = $val["date"];
-				$bookkeeping->doc_ref = $val["ref"];
-				$bookkeeping->date_create = $now;
-				$bookkeeping->doc_type = 'expense_report';
-				$bookkeeping->fk_doc = $key;
-				$bookkeeping->fk_docdet = $val["fk_expensereportdet"];
-				$bookkeeping->code_tiers = '';
-				$bookkeeping->label_compte = $langs->trans("VAT"). ' '.$def_tva[$key];
-				$bookkeeping->numero_compte = $k;
-				$bookkeeping->montant = $mt;
-				$bookkeeping->sens = ($mt < 0) ? 'C' : 'D';
-				$bookkeeping->debit = ($mt > 0) ? $mt : 0;
-				$bookkeeping->credit = ($mt <= 0) ? $mt : 0;
-				$bookkeeping->code_journal = $conf->global->ACCOUNTING_EXPENSEREPORT_JOURNAL;
-				$bookkeeping->fk_user_author = $user->id;
-
-				$result = $bookkeeping->create($user);
-				if ($result < 0) {
-					$error++;
-					$errorforline++;
-					setEventMessages($object->error, $object->errors, 'errors');
-				}
-			}
-		}
-
+	    $db->begin();
+	     
+        if (! $errorforline)
+        {
+    	    foreach ( $tabttc[$key] as $k => $mt ) {
+    			if ($mt) {
+        	        // get compte id and label
+        
+        			$bookkeeping = new BookKeeping($db);
+        			$bookkeeping->doc_date = $val["date"];
+        			$bookkeeping->doc_ref = $val["ref"];
+        			$bookkeeping->date_create = $now;
+        			$bookkeeping->doc_type = 'expense_report';
+        			$bookkeeping->fk_doc = $key;
+        			$bookkeeping->fk_docdet = $val["fk_expensereportdet"];
+        			$bookkeeping->code_tiers = $tabuser[$key]['user_accountancy_code'];
+        			$bookkeeping->label_compte = $tabuser[$key]['name'];
+        			$bookkeeping->numero_compte = $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT;
+        			$bookkeeping->montant = $mt;
+        			$bookkeeping->sens = ($mt >= 0) ? 'C' : 'D';
+        			$bookkeeping->debit = ($mt <= 0) ? $mt : 0;
+        			$bookkeeping->credit = ($mt > 0) ? $mt : 0;
+        			$bookkeeping->code_journal = $conf->global->ACCOUNTING_EXPENSEREPORT_JOURNAL;
+        			$bookkeeping->fk_user_author = $user->id;
+        
+        			$result = $bookkeeping->create($user);
+        			if ($result < 0) {
+        			    if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists')	// Already exists
+        			    {
+        			        $error++;
+        			        $errorforline++;
+        			        //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->doc_ref.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
+        			    }
+        			    else
+        			    {
+        			        $error++;
+        			        $errorforline++;
+        			        setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
+        			    }
+        			}
+    			}
+    		}
+        }
+        
+        if (! $errorforline)
+        {
+            // Fees
+    		foreach ( $tabht[$key] as $k => $mt ) {
+    			$accountingaccount = new AccountingAccount($db);
+    			$accountingaccount->fetch(null, $k, true);
+    			if ($mt) {
+    				// get compte id and label
+    				$accountingaccount = new AccountingAccount($db);
+    				if ($accountingaccount->fetch(null, $k, true)) {
+    					$bookkeeping = new BookKeeping($db);
+    					$bookkeeping->doc_date = $val["date"];
+    					$bookkeeping->doc_ref = $val["ref"];
+    					$bookkeeping->date_create = $now;
+    					$bookkeeping->doc_type = 'expense_report';
+    					$bookkeeping->fk_doc = $key;
+    					$bookkeeping->fk_docdet = $val["fk_expensereportdet"];
+    					$bookkeeping->code_tiers = '';
+    					$bookkeeping->label_compte = $accountingaccount->label;
+    					$bookkeeping->numero_compte = $k;
+    					$bookkeeping->montant = $mt;
+    					$bookkeeping->sens = ($mt < 0) ? 'C' : 'D';
+    					$bookkeeping->debit = ($mt > 0) ? $mt : 0;
+    					$bookkeeping->credit = ($mt <= 0) ? $mt : 0;
+    					$bookkeeping->code_journal = $conf->global->ACCOUNTING_EXPENSEREPORT_JOURNAL;
+    					$bookkeeping->fk_user_author = $user->id;
+    
+    					$result = $bookkeeping->create($user);
+	        			if ($result < 0) {
+            			    if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists')	// Already exists
+            			    {
+            			        $error++;
+            			        $errorforline++;
+            			        //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->doc_ref.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
+            			    }
+            			    else
+            			    {
+            			        $error++;
+            			        $errorforline++;
+            			        setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
+            			    }
+	        			}
+    				}
+    			}
+    		}
+        }
+        
+        if (! $errorforline)
+        {
+            // VAT
+    		// var_dump($tabtva);
+    		foreach ( $tabtva[$key] as $k => $mt ) {
+    			if ($mt) {
+    				// get compte id and label
+    				$bookkeeping = new BookKeeping($db);
+    				$bookkeeping->doc_date = $val["date"];
+    				$bookkeeping->doc_ref = $val["ref"];
+    				$bookkeeping->date_create = $now;
+    				$bookkeeping->doc_type = 'expense_report';
+    				$bookkeeping->fk_doc = $key;
+    				$bookkeeping->fk_docdet = $val["fk_expensereportdet"];
+    				$bookkeeping->code_tiers = '';
+    				$bookkeeping->label_compte = $langs->trans("VAT"). ' '.$def_tva[$key];
+    				$bookkeeping->numero_compte = $k;
+    				$bookkeeping->montant = $mt;
+    				$bookkeeping->sens = ($mt < 0) ? 'C' : 'D';
+    				$bookkeeping->debit = ($mt > 0) ? $mt : 0;
+    				$bookkeeping->credit = ($mt <= 0) ? $mt : 0;
+    				$bookkeeping->code_journal = $conf->global->ACCOUNTING_EXPENSEREPORT_JOURNAL;
+    				$bookkeeping->fk_user_author = $user->id;
+    
+    				$result = $bookkeeping->create($user);
+    				if ($result < 0) {
+           			    if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists')	// Already exists
+        			    {
+        			        $error++;
+        			        $errorforline++;
+        			        //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->doc_ref.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
+        			    }
+        			    else
+        			    {
+        			        $error++;
+        			        $errorforline++;
+        			        setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
+        			    }
+    				}
+    			}
+    		}
+        }
+        
 		if (! $errorforline)
 		{
 		    $db->commit();
@@ -286,7 +326,7 @@ $form = new Form($db);
 $userstatic = new User($db);
 
 // Export
-if ($action == 'export_csv') {
+/*if ($action == 'export_csv') {
 	$sep = $conf->global->ACCOUNTING_EXPORT_SEPARATORCSV;
 	$journal = $conf->global->ACCOUNTING_EXPENSEREPORT_JOURNAL;
 
@@ -393,6 +433,7 @@ if ($action == 'export_csv') {
 		}
 	}
 }
+*/
 
 if (empty($action) || $action == 'view') {
 
@@ -406,18 +447,19 @@ if (empty($action) || $action == 'view') {
 	$description.= $langs->trans("DescJournalOnlyBindedVisible").'<br>';
 
 	$period = $form->select_date($date_start, 'date_start', 0, 0, 0, '', 1, 0, 1) . ' - ' . $form->select_date($date_end, 'date_end', 0, 0, 0, '', 1, 0, 1);
-	report_header($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, array (
-			'action' => ''
-	));
 
-	if ($conf->global->ACCOUNTING_EXPORT_MODELCSV != 1 && $conf->global->ACCOUNTING_EXPORT_MODELCSV != 2) {
+	journalHead($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, array('action' => ''));
+
+	/*if ($conf->global->ACCOUNTING_EXPORT_MODELCSV != 1 && $conf->global->ACCOUNTING_EXPORT_MODELCSV != 2) {
 		print '<input type="button" class="butActionRefused" style="float: right;" value="' . $langs->trans("Export") . '" disabled="disabled" title="' . $langs->trans('ExportNotSupported') . '"/>';
 	} else {
 		print '<input type="button" class="butAction" style="float: right;" value="' . $langs->trans("Export") . '" onclick="launch_export();" />';
-	}
+	}*/
 
+    print '<div class="tabsAction">';
 	print '<input type="button" class="butAction" value="' . $langs->trans("WriteBookKeeping") . '" onclick="writebookkeeping();" />';
-
+    print '</div>';
+    
 	print '
 	<script type="text/javascript">
 		function launch_export() {
@@ -435,7 +477,7 @@ if (empty($action) || $action == 'view') {
 	/*
 	 * Show result array
 	 */
-	print '<br><br>';
+	print '<br>';
 
 	$i = 0;
 	print "<table class=\"noborder\" width=\"100%\">";
@@ -511,11 +553,11 @@ if (empty($action) || $action == 'view') {
 				print "</tr>";
 			}
 		}
-		print '<tr class="oddeven">';
 
 		// Third party
 		foreach ( $tabttc[$key] as $k => $mt ) {
-			print "<td><!-- Thirdparty --></td>";
+		    print '<tr class="oddeven">';
+		    print "<td><!-- Thirdparty --></td>";
 		    print "<td>" . $date . "</td>";
 			print "<td>" . $expensereportstatic->getNomUrl(1) . "</td>";
 			$userstatic->id = $tabuser[$key]['id'];
@@ -531,8 +573,8 @@ if (empty($action) || $action == 'view') {
 			print "<td>" . $userstatic->getNomUrl(0, 'user', 16) . ' - ' . $langs->trans("Code_tiers") . "</td>";
 			print '<td align="right">' . ($mt < 0 ? - price(- $mt) : '') . "</td>";
 			print '<td align="right">' . ($mt >= 0 ? price($mt) : '') . "</td>";
+		    print "</tr>";
 		}
-		print "</tr>";
 	}
 
 	print "</table>";
diff --git a/htdocs/accountancy/journal/purchasesjournal.php b/htdocs/accountancy/journal/purchasesjournal.php
index a00fc9a70d815ebda760ca33f0f557764a2fea05..c5069644cef8089ad1f08862bc7b9e353181aabf 100644
--- a/htdocs/accountancy/journal/purchasesjournal.php
+++ b/htdocs/accountancy/journal/purchasesjournal.php
@@ -109,6 +109,7 @@ dol_syslog('accountancy/journal/purchasesjournal.php:: $sql=' . $sql);
 $result = $db->query($sql);
 if ($result) {
 	$num = $db->num_rows($result);
+
 	// les variables
 	$cptfour = (! empty($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER)) ? $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER : $langs->trans("CodeNotDef");
 	$cpttva = (! empty($conf->global->ACCOUNTING_VAT_BUY_ACCOUNT)) ? $conf->global->ACCOUNTING_VAT_BUY_ACCOUNT : $langs->trans("CodeNotDef");
@@ -123,8 +124,10 @@ if ($result) {
 	$i = 0;
 	while ( $i < $num ) {
 		$obj = $db->fetch_object($result);
+
 		// contrôles
 		$compta_soc = (! empty($obj->code_compta_fournisseur)) ? $obj->code_compta_fournisseur : $cptfour;
+		
 		$compta_prod = $obj->compte;
 		if (empty($compta_prod)) {
 			if ($obj->product_type == 0)
@@ -144,14 +147,21 @@ if ($result) {
 
 		$tabfac[$obj->rowid]["type"] = $obj->type;
 		$tabfac[$obj->rowid]["description"] = $obj->description;
-		$tabfac[$obj->rowid]["fk_facturefourndet"] = $obj->fdid;
+		//$tabfac[$obj->rowid]["fk_facturefourndet"] = $obj->fdid;
+		
+        // Avoid warnings
+        if (! isset($tabttc[$obj->rowid][$compta_soc])) $tabttc[$obj->rowid][$compta_soc] = 0;
+        if (! isset($tabht[$obj->rowid][$compta_prod])) $tabht[$obj->rowid][$compta_prod] = 0;
+        if (! isset($tabtva[$obj->rowid][$compta_tva])) $tabtva[$obj->rowid][$compta_tva] = 0;
+
 		$tabttc[$obj->rowid][$compta_soc] += $obj->total_ttc;
 		$tabht[$obj->rowid][$compta_prod] += $obj->total_ht;
 		$tabtva[$obj->rowid][$compta_tva] += $obj->total_tva;
 		$tabcompany[$obj->rowid] = array (
 				'id' => $obj->socid,
 				'name' => $obj->name,
-				'code_fournisseur' => $obj->code_compta_fournisseur
+				'code_fournisseur' => $obj->code_fournisseur,
+				'code_compta_fournisseur' => $compta_soc
 		);
 
 		$i ++;
@@ -165,7 +175,7 @@ if ($action == 'writebookkeeping') {
 	$now = dol_now();
 	$error = 0;
 
-	foreach ($tabfac as $key => $val)
+	foreach ($tabfac as $key => $val)  // Loop on each invoice
 	{
 	    $errorforline = 0;
 	     
@@ -188,101 +198,136 @@ if ($action == 'writebookkeeping') {
 		$companystatic->code_fournisseur = $tabcompany[$key]['code_fournisseur'];
 		$companystatic->client = $tabcompany[$key]['code_client'];
 
-		foreach ( $tabttc[$key] as $k => $mt ) {
-			// get compte id and label
-
-			$bookkeeping = new BookKeeping($db);
-			$bookkeeping->doc_date = $val["date"];
-			$bookkeeping->doc_ref = $val["ref"];
-			$bookkeeping->date_create = $now;
-			$bookkeeping->doc_type = 'supplier_invoice';
-			$bookkeeping->fk_doc = $key;
-			$bookkeeping->fk_docdet = $val["fk_facturefourndet"];
-			$bookkeeping->code_tiers = $tabcompany[$key]['code_fournisseur'];
-			$bookkeeping->label_compte = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->refsupplier . ' - ' . $langs->trans("Code_tiers");
-			$bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER;
-			$bookkeeping->montant = $mt;
-			$bookkeeping->sens = ($mt >= 0) ? 'C' : 'D';
-			$bookkeeping->debit = ($mt <= 0) ? $mt : 0;
-			$bookkeeping->credit = ($mt > 0) ? $mt : 0;
-			$bookkeeping->code_journal = $conf->global->ACCOUNTING_PURCHASE_JOURNAL;
-			$bookkeeping->fk_user_author = $user->id;
-
-			$result = $bookkeeping->create($user);
-			if ($result < 0) {
-			    $error++;
-			    $errorforline++;
-			    setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
-			}
-		}
-
+        if (! $errorforline)
+        {
+    		foreach ( $tabttc[$key] as $k => $mt ) {
+    			// get compte id and label
+    		    if ($mt) {
+        			$bookkeeping = new BookKeeping($db);
+        			$bookkeeping->doc_date = $val["date"];
+        			$bookkeeping->doc_ref = $val["ref"];
+        			$bookkeeping->date_create = $now;
+        			$bookkeeping->doc_type = 'supplier_invoice';
+        			$bookkeeping->fk_doc = $key;
+        			$bookkeeping->fk_docdet = 0;    // Useless, can be several lines that are source of this record to add
+        			$bookkeeping->code_tiers = $tabcompany[$key]['code_fournisseur'];
+        			$bookkeeping->label_compte = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->refsupplier . ' - ' . $langs->trans("Code_tiers");
+        			$bookkeeping->numero_compte = $tabcompany[$key]['code_compta_fournisseur'];
+        			$bookkeeping->montant = $mt;
+        			$bookkeeping->sens = ($mt >= 0) ? 'C' : 'D';
+        			$bookkeeping->debit = ($mt <= 0) ? $mt : 0;
+        			$bookkeeping->credit = ($mt > 0) ? $mt : 0;
+        			$bookkeeping->code_journal = $conf->global->ACCOUNTING_PURCHASE_JOURNAL;
+        			$bookkeeping->fk_user_author = $user->id;
+        
+        			$result = $bookkeeping->create($user);
+           			if ($result < 0) {
+                        if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists')	// Already exists
+                        {
+                            $error++;
+                            $errorforline++;
+                            //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->doc_ref.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
+                        }
+                        else
+                        {
+                            $error++;
+                            $errorforline++;
+                            setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
+                        }
+        			}
+    		    }
+    		}
+        }
+        
 		// Product / Service
-		foreach ( $tabht[$key] as $k => $mt ) {
-			$accountingaccount = new AccountingAccount($db);
-			$accountingaccount->fetch(null, $k, true);
-			if ($mt) {
-				// get compte id and label
-				$accountingaccount = new AccountingAccount($db);
-				if ($accountingaccount->fetch(null, $k, true)) {
-					$bookkeeping = new BookKeeping($db);
-					$bookkeeping->doc_date = $val["date"];
-					$bookkeeping->doc_ref = $val["ref"];
-					$bookkeeping->date_create = $now;
-					$bookkeeping->doc_type = 'supplier_invoice';
-					$bookkeeping->fk_doc = $key;
-					$bookkeeping->fk_docdet = $val["fk_facturefourndet"];
-					$bookkeeping->code_tiers = '';
-					$bookkeeping->label_compte = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->refsupplier . ' - ' . $accountingaccount->label;
-					$bookkeeping->numero_compte = $k;
-					$bookkeeping->montant = $mt;
-					$bookkeeping->sens = ($mt < 0) ? 'C' : 'D';
-					$bookkeeping->debit = ($mt > 0) ? $mt : 0;
-					$bookkeeping->credit = ($mt <= 0) ? $mt : 0;
-					$bookkeeping->code_journal = $conf->global->ACCOUNTING_PURCHASE_JOURNAL;
-					$bookkeeping->fk_user_author = $user->id;
-
-					$result = $bookkeeping->create($user);
-					if ($result < 0) {
-						$error++;
-						$errorforline++;
-						setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
-					}
-				}
-			}
-		}
-
+        if (! $errorforline)
+        {
+            foreach ( $tabht[$key] as $k => $mt ) {
+    			$accountingaccount = new AccountingAccount($db);
+    			$accountingaccount->fetch(null, $k, true);
+    			if ($mt) {
+    				// get compte id and label
+    				$accountingaccount = new AccountingAccount($db);
+    				if ($accountingaccount->fetch(null, $k, true)) {
+    					$bookkeeping = new BookKeeping($db);
+    					$bookkeeping->doc_date = $val["date"];
+    					$bookkeeping->doc_ref = $val["ref"];
+    					$bookkeeping->date_create = $now;
+    					$bookkeeping->doc_type = 'supplier_invoice';
+    					$bookkeeping->fk_doc = $key;
+    					$bookkeeping->fk_docdet = 0;    // Useless, can be several lines that are source of this record to add
+    					$bookkeeping->code_tiers = '';
+    					$bookkeeping->label_compte = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->refsupplier . ' - ' . $accountingaccount->label;
+    					$bookkeeping->numero_compte = $k;
+    					$bookkeeping->montant = $mt;
+    					$bookkeeping->sens = ($mt < 0) ? 'C' : 'D';
+    					$bookkeeping->debit = ($mt > 0) ? $mt : 0;
+    					$bookkeeping->credit = ($mt <= 0) ? $mt : 0;
+    					$bookkeeping->code_journal = $conf->global->ACCOUNTING_PURCHASE_JOURNAL;
+    					$bookkeeping->fk_user_author = $user->id;
+    
+    					$result = $bookkeeping->create($user);
+    					if ($result < 0) {
+    					    if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists')	// Already exists
+            			    {
+            			        $error++;
+            			        $errorforline++;
+            			        //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->doc_ref.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
+            			    }
+            			    else
+            			    {
+            			        $error++;
+            			        $errorforline++;
+            			        setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
+            			    }
+    					}
+    				}
+    			}
+    		}
+        }
+        
 		// VAT
 		// var_dump($tabtva);
-		foreach ( $tabtva[$key] as $k => $mt ) {
-			if ($mt) {
-				// get compte id and label
-				$bookkeeping = new BookKeeping($db);
-				$bookkeeping->doc_date = $val["date"];
-				$bookkeeping->doc_ref = $val["ref"];
-				$bookkeeping->date_create = $now;
-				$bookkeeping->doc_type = 'supplier_invoice';
-				$bookkeeping->fk_doc = $key;
-				$bookkeeping->fk_docdet = $val["fk_facturefourndet"];
-				$bookkeeping->code_tiers = '';
-				$bookkeeping->label_compte = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->refsupplier . ' - ' . $langs->trans("VAT"). ' '.$def_tva[$key];
-				$bookkeeping->numero_compte = $k;
-				$bookkeeping->montant = $mt;
-				$bookkeeping->sens = ($mt < 0) ? 'C' : 'D';
-				$bookkeeping->debit = ($mt > 0) ? $mt : 0;
-				$bookkeeping->credit = ($mt <= 0) ? $mt : 0;
-				$bookkeeping->code_journal = $conf->global->ACCOUNTING_PURCHASE_JOURNAL;
-				$bookkeeping->fk_user_author = $user->id;
-
-				$result = $bookkeeping->create($user);
-				if ($result < 0) {
-					$error++;
-					$errorforline++;
-					setEventMessages($object->error, $object->errors, 'errors');
-				}
-			}
-		}
-		
-
+        if (! $errorforline)
+        {
+            foreach ( $tabtva[$key] as $k => $mt ) {
+    			if ($mt) {
+    				// get compte id and label
+    				$bookkeeping = new BookKeeping($db);
+    				$bookkeeping->doc_date = $val["date"];
+    				$bookkeeping->doc_ref = $val["ref"];
+    				$bookkeeping->date_create = $now;
+    				$bookkeeping->doc_type = 'supplier_invoice';
+    				$bookkeeping->fk_doc = $key;
+    				$bookkeeping->fk_docdet = 0;    // Useless, can be several lines that are source of this record to add
+    				$bookkeeping->code_tiers = '';
+    				$bookkeeping->label_compte = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->refsupplier . ' - ' . $langs->trans("VAT"). ' '.$def_tva[$key];
+    				$bookkeeping->numero_compte = $k;
+    				$bookkeeping->montant = $mt;
+    				$bookkeeping->sens = ($mt < 0) ? 'C' : 'D';
+    				$bookkeeping->debit = ($mt > 0) ? $mt : 0;
+    				$bookkeeping->credit = ($mt <= 0) ? $mt : 0;
+    				$bookkeeping->code_journal = $conf->global->ACCOUNTING_PURCHASE_JOURNAL;
+    				$bookkeeping->fk_user_author = $user->id;
+    
+    				$result = $bookkeeping->create($user);
+    				if ($result < 0) {
+    				    if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists')	// Already exists
+    				    {
+    				        $error++;
+    				        $errorforline++;
+    				        //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->doc_ref.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
+    				    }
+    				    else
+    				    {
+    				        $error++;
+    				        $errorforline++;
+    				        setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
+    				    }
+    				}
+    			}
+    		}
+        }
 
 		if (! $errorforline)
 		{
@@ -319,7 +364,7 @@ $form = new Form($db);
 $companystatic = new Fournisseur($db);
 
 // Export
-if ($action == 'export_csv') {
+/*if ($action == 'export_csv') {
 	$sep = $conf->global->ACCOUNTING_EXPORT_SEPARATORCSV;
 	$journal = $conf->global->ACCOUNTING_PURCHASE_JOURNAL;
 
@@ -437,6 +482,7 @@ if ($action == 'export_csv') {
 		}
 	}
 }
+*/
 
 if (empty($action) || $action == 'view') {
 
@@ -456,18 +502,19 @@ if (empty($action) || $action == 'view') {
 	}
 
 	$period = $form->select_date($date_start, 'date_start', 0, 0, 0, '', 1, 0, 1) . ' - ' . $form->select_date($date_end, 'date_end', 0, 0, 0, '', 1, 0, 1);
-	report_header($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, array (
-			'action' => ''
-	));
+	
+	journalHead($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, array('action' => ''));
 
-	if ($conf->global->ACCOUNTING_EXPORT_MODELCSV != 1 && $conf->global->ACCOUNTING_EXPORT_MODELCSV != 2) {
+	/*if ($conf->global->ACCOUNTING_EXPORT_MODELCSV != 1 && $conf->global->ACCOUNTING_EXPORT_MODELCSV != 2) {
 		print '<input type="button" class="butActionRefused" style="float: right;" value="' . $langs->trans("Export") . '" disabled="disabled" title="' . $langs->trans('ExportNotSupported') . '"/>';
 	} else {
 		print '<input type="button" class="butAction" style="float: right;" value="' . $langs->trans("Export") . '" onclick="launch_export();" />';
-	}
+	}*/
 
+    print '<div class="tabsAction">';
 	print '<input type="button" class="butAction" value="' . $langs->trans("WriteBookKeeping") . '" onclick="writebookkeeping();" />';
-
+    print '</div>';
+    
 	print '
 	<script type="text/javascript">
 		function launch_export() {
@@ -485,7 +532,7 @@ if (empty($action) || $action == 'view') {
 	/*
 	 * Show result array
 	 */
-	print '<br><br>';
+	print '<br>';
 
 	$i = 0;
 	print "<table class=\"noborder\" width=\"100%\">";
@@ -562,11 +609,11 @@ if (empty($action) || $action == 'view') {
 				print "</tr>";
 			}
 		}
-		print '<tr class="oddeven">';
 
 		// Third party
 		foreach ( $tabttc[$key] as $k => $mt ) {
-			print "<td><!-- Thirdparty --></td>";
+		    print '<tr class="oddeven">';
+		    print "<td><!-- Thirdparty --></td>";
 		    print "<td>" . $date . "</td>";
 			print "<td>" . $invoicestatic->getNomUrl(1) . "</td>";
 			$companystatic->id = $tabcompany[$key]['id'];
@@ -585,8 +632,8 @@ if (empty($action) || $action == 'view') {
 			// print "</td>";
 			print '<td align="right">' . ($mt < 0 ? - price(- $mt) : '') . "</td>";
 			print '<td align="right">' . ($mt >= 0 ? price($mt) : '') . "</td>";
+		    print "</tr>";
 		}
-		print "</tr>";
 	}
 
 	print "</table>";
diff --git a/htdocs/accountancy/journal/sellsjournal.php b/htdocs/accountancy/journal/sellsjournal.php
index 235af8eeb41d95118849149f79999b68a194c359..beb0c777e27061fb29b4cef52e961bd7e3588ff5 100644
--- a/htdocs/accountancy/journal/sellsjournal.php
+++ b/htdocs/accountancy/journal/sellsjournal.php
@@ -100,7 +100,7 @@ $sql .= " JOIN " . MAIN_DB_PREFIX . "societe as s ON s.rowid = f.fk_soc";
 $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_tva as ct ON fd.tva_tx = ct.taux AND ct.fk_pays = '" . $idpays . "'";
 $sql .= " WHERE fd.fk_code_ventilation > 0";
 $sql .= " AND f.entity IN (".getEntity('facture', 0).')';    // We don't share object for accountancy
-$sql .= " AND f.fk_statut > 0";
+$sql .= " AND f.fk_statut > 0"; // TODO Facture annulée ?
 if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
     $sql .= " AND f.type IN (" . Facture::TYPE_STANDARD . "," . Facture::TYPE_REPLACEMENT . "," . Facture::TYPE_CREDIT_NOTE . "," . Facture::TYPE_SITUATION . ")";
 } else {
@@ -124,10 +124,12 @@ if ($result) {
     $num = $db->num_rows($result);
     $i = 0;
 
+    $cptcli = (! empty($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER)) ? $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER : $langs->trans("CodeNotDef");
+    
     while ( $i < $num ) {
         $obj = $db->fetch_object($result);
+        
         // les variables
-        $cptcli = (! empty($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER)) ? $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER : $langs->trans("CodeNotDef");
         $compta_soc = (! empty($obj->code_compta)) ? $obj->code_compta : $cptcli;
 
         $compta_prod = $obj->compte;
@@ -164,23 +166,24 @@ if ($result) {
         $tabfac[$obj->rowid]["ref"] = $obj->facnumber;
         $tabfac[$obj->rowid]["type"] = $obj->type;
         $tabfac[$obj->rowid]["description"] = $obj->label_compte;
-        $tabfac[$obj->rowid]["fk_facturedet"] = $obj->fdid;
-        if (! isset($tabttc[$obj->rowid][$compta_soc]))
-            $tabttc[$obj->rowid][$compta_soc] = 0;
-            if (! isset($tabht[$obj->rowid][$compta_prod]))
-                $tabht[$obj->rowid][$compta_prod] = 0;
-                if (! isset($tabtva[$obj->rowid][$compta_tva]))
-                    $tabtva[$obj->rowid][$compta_tva] = 0;
-                    $tabttc[$obj->rowid][$compta_soc] += $obj->total_ttc * $situation_ratio;
-                    $tabht[$obj->rowid][$compta_prod] += $obj->total_ht * $situation_ratio;
-                    $tabtva[$obj->rowid][$compta_tva] += $obj->total_tva * $situation_ratio;
-                    $tabcompany[$obj->rowid] = array (
-                        'id' => $obj->socid,
-                        'name' => $obj->name,
-                        'code_client' => $obj->code_compta
-                    );
-
-                    $i ++;
+        //$tabfac[$obj->rowid]["fk_facturedet"] = $obj->fdid;
+       
+        // Avoid warnings
+        if (! isset($tabttc[$obj->rowid][$compta_soc])) $tabttc[$obj->rowid][$compta_soc] = 0;
+        if (! isset($tabht[$obj->rowid][$compta_prod])) $tabht[$obj->rowid][$compta_prod] = 0;
+        if (! isset($tabtva[$obj->rowid][$compta_tva])) $tabtva[$obj->rowid][$compta_tva] = 0;
+
+        $tabttc[$obj->rowid][$compta_soc] += $obj->total_ttc * $situation_ratio;
+        $tabht[$obj->rowid][$compta_prod] += $obj->total_ht * $situation_ratio;
+        $tabtva[$obj->rowid][$compta_tva] += $obj->total_tva * $situation_ratio;
+        $tabcompany[$obj->rowid] = array (
+            'id' => $obj->socid,
+            'name' => $obj->name,
+            'code_client' => $obj->code_client,
+            'code_compta' => $compta_soc
+        );
+
+        $i ++;
     }
 } else {
     dol_print_error($db);
@@ -191,7 +194,7 @@ if ($action == 'writebookkeeping') {
     $now = dol_now();
     $error = 0;
 
-    foreach ( $tabfac as $key => $val ) {
+    foreach ( $tabfac as $key => $val ) {   // Loop on each invoice
          
         $errorforline = 0;
 
@@ -211,97 +214,135 @@ if ($action == 'writebookkeeping') {
         $invoicestatic->id = $key;
         $invoicestatic->ref = (string) $val["ref"];
 
-        foreach ( $tabttc[$key] as $k => $mt ) {
-            $bookkeeping = new BookKeeping($db);
-            $bookkeeping->doc_date = $val["date"];
-            $bookkeeping->doc_ref = $val["ref"];
-            $bookkeeping->date_create = $now;
-            $bookkeeping->doc_type = 'customer_invoice';
-            $bookkeeping->fk_doc = $key;
-            $bookkeeping->fk_docdet = $val["fk_facturedet"];
-            $bookkeeping->code_tiers = $tabcompany[$key]['code_client'];
-            $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER;
-            // $bookkeeping->label_compte = $tabcompany[$key]['name'];
-            $bookkeeping->label_compte = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("Code_tiers");
-            $bookkeeping->montant = $mt;
-            $bookkeeping->sens = ($mt >= 0) ? 'D' : 'C';
-            $bookkeeping->debit = ($mt >= 0) ? $mt : 0;
-            $bookkeeping->credit = ($mt < 0) ? $mt : 0;
-            $bookkeeping->code_journal = $conf->global->ACCOUNTING_SELL_JOURNAL;
-            $bookkeeping->fk_user_author = $user->id;
-
-            $result = $bookkeeping->create($user);
-            if ($result < 0) {
-                $error++;
-                $errorforline++;
-                setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
+        // Thirdparty
+        if (! $errorforline)
+        {
+            foreach ( $tabttc[$key] as $k => $mt ) {
+                if ($mt) {
+                    $bookkeeping = new BookKeeping($db);
+                    $bookkeeping->doc_date = $val["date"];
+                    $bookkeeping->doc_ref = $val["ref"];
+                    $bookkeeping->date_create = $now;
+                    $bookkeeping->doc_type = 'customer_invoice';
+                    $bookkeeping->fk_doc = $key;
+                    $bookkeeping->fk_docdet = 0;    // Useless, can be several lines that are source of this record to add
+                    $bookkeeping->code_tiers = $tabcompany[$key]['code_client'];
+                    $bookkeeping->numero_compte = $tabcompany[$key]['code_compta'];
+                    // $bookkeeping->label_compte = $tabcompany[$key]['name'];
+                    $bookkeeping->label_compte = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("Code_tiers");
+                    $bookkeeping->montant = $mt;
+                    $bookkeeping->sens = ($mt >= 0) ? 'D' : 'C';
+                    $bookkeeping->debit = ($mt >= 0) ? $mt : 0;
+                    $bookkeeping->credit = ($mt < 0) ? $mt : 0;
+                    $bookkeeping->code_journal = $conf->global->ACCOUNTING_SELL_JOURNAL;
+                    $bookkeeping->fk_user_author = $user->id;
+    
+                    $result = $bookkeeping->create($user);
+           			if ($result < 0) {
+                        if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists')	// Already exists
+                        {
+                            $error++;
+                            $errorforline++;
+                            //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->doc_ref.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
+                        }
+                        else
+                        {
+                            $error++;
+                            $errorforline++;
+                            setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
+                        }
+        			}
+                }
             }
         }
-
+        
         // Product / Service
-        foreach ( $tabht[$key] as $k => $mt ) {
-            if ($mt) {
-                // get compte id and label
-                $accountingaccount = new AccountingAccount($db);
-                if ($accountingaccount->fetch(null, $k, true)) {
+        if (! $errorforline)
+        {
+            foreach ( $tabht[$key] as $k => $mt ) {
+                if ($mt) {
+                    // get compte id and label
+                    $accountingaccount = new AccountingAccount($db);
+                    if ($accountingaccount->fetch(null, $k, true)) {
+                        $bookkeeping = new BookKeeping($db);
+                        $bookkeeping->doc_date = $val["date"];
+                        $bookkeeping->doc_ref = $val["ref"];
+                        $bookkeeping->date_create = $now;
+                        $bookkeeping->doc_type = 'customer_invoice';
+                        $bookkeeping->fk_doc = $key;
+                        $bookkeeping->fk_docdet = 0;    // Useless, can be several lines that are source of this record to add;
+                        $bookkeeping->code_tiers = '';
+                        $bookkeeping->numero_compte = $k;
+                        $bookkeeping->label_compte = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $accountingaccount->label;
+                        $bookkeeping->montant = $mt;
+                        $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
+                        $bookkeeping->debit = ($mt < 0) ? $mt : 0;
+                        $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
+                        $bookkeeping->code_journal = $conf->global->ACCOUNTING_SELL_JOURNAL;
+                        $bookkeeping->fk_user_author = $user->id;
+    
+                        $result = $bookkeeping->create($user);
+            			if ($result < 0) {
+                            if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists')	// Already exists
+                            {
+                                $error++;
+                                $errorforline++;
+                                //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->doc_ref.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
+                            }
+                            else
+                            {
+                                $error++;
+                                $errorforline++;
+                                setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
+                            }
+            			}                        
+                    }
+                }
+            }
+        }
+        
+        // VAT
+        // var_dump($tabtva);
+        if (! $errorforline)
+        {
+            foreach ( $tabtva[$key] as $k => $mt ) {
+                if ($mt) {
                     $bookkeeping = new BookKeeping($db);
                     $bookkeeping->doc_date = $val["date"];
                     $bookkeeping->doc_ref = $val["ref"];
                     $bookkeeping->date_create = $now;
                     $bookkeeping->doc_type = 'customer_invoice';
                     $bookkeeping->fk_doc = $key;
-                    $bookkeeping->fk_docdet = $val["fk_facturedet"];
+                    $bookkeeping->fk_docdet = 0;    // Useless, can be several lines that are source of this record to add
                     $bookkeeping->code_tiers = '';
                     $bookkeeping->numero_compte = $k;
-                    $bookkeeping->label_compte = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $accountingaccount->label;
+                    $bookkeeping->label_compte = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT").' '.$def_tva[$key];
                     $bookkeeping->montant = $mt;
                     $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
                     $bookkeeping->debit = ($mt < 0) ? $mt : 0;
                     $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
                     $bookkeeping->code_journal = $conf->global->ACCOUNTING_SELL_JOURNAL;
                     $bookkeeping->fk_user_author = $user->id;
-
+    
                     $result = $bookkeeping->create($user);
                     if ($result < 0) {
-                        $error++;
-                        $errorforline++;
-                        setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
+           			    if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists')	// Already exists
+        			    {
+        			        $error++;
+        			        $errorforline++;
+        			        //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->doc_ref.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
+        			    }
+        			    else
+        			    {
+        			        $error++;
+        			        $errorforline++;
+        			        setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
+        			    }
                     }
                 }
             }
         }
 
-        // VAT
-        // var_dump($tabtva);
-        foreach ( $tabtva[$key] as $k => $mt ) {
-            if ($mt) {
-                $bookkeeping = new BookKeeping($db);
-                $bookkeeping->doc_date = $val["date"];
-                $bookkeeping->doc_ref = $val["ref"];
-                $bookkeeping->date_create = $now;
-                $bookkeeping->doc_type = 'customer_invoice';
-                $bookkeeping->fk_doc = $key;
-                $bookkeeping->fk_docdet = $val["fk_facturedet"];
-                $bookkeeping->code_tiers = '';
-                $bookkeeping->numero_compte = $k;
-                $bookkeeping->label_compte = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT").' '.$def_tva[$key];
-                $bookkeeping->montant = $mt;
-                $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
-                $bookkeeping->debit = ($mt < 0) ? $mt : 0;
-                $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
-                $bookkeeping->code_journal = $conf->global->ACCOUNTING_SELL_JOURNAL;
-                $bookkeeping->fk_user_author = $user->id;
-
-                $result = $bookkeeping->create($user);
-                if ($result < 0) {
-                    $error++;
-                    $errorforline++;
-                    setEventMessages($object->error, $object->errors, 'errors');
-                }
-            }
-        }
-
-
         if (! $errorforline)
         {
             $db->commit();
@@ -337,7 +378,7 @@ if ($action == 'writebookkeeping') {
 $form = new Form($db);
 
 // Export
-if ($action == 'export_csv') {
+/*if ($action == 'export_csv') {
 
     $sep = $conf->global->ACCOUNTING_EXPORT_SEPARATORCSV;
     $sell_journal = $conf->global->ACCOUNTING_SELL_JOURNAL;
@@ -457,6 +498,8 @@ if ($action == 'export_csv') {
         }
     }
 }
+*/
+
 
 if (empty($action) || $action == 'view') {
 
@@ -474,18 +517,18 @@ if (empty($action) || $action == 'view') {
 	else
 		$description .= $langs->trans("DepositsAreIncluded");
 	$period = $form->select_date($date_start, 'date_start', 0, 0, 0, '', 1, 0, 1) . ' - ' . $form->select_date($date_end, 'date_end', 0, 0, 0, '', 1, 0, 1);
-	report_header($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, array (
-			'action' => ''
-	));
+	
+	journalHead($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, array('action' => ''));
 
-	if ($conf->global->ACCOUNTING_EXPORT_MODELCSV != 1 && $conf->global->ACCOUNTING_EXPORT_MODELCSV != 2) {
+	/*if ($conf->global->ACCOUNTING_EXPORT_MODELCSV != 1 && $conf->global->ACCOUNTING_EXPORT_MODELCSV != 2) {
 		print '<input type="button" class="butActionRefused" style="float: right;" value="' . $langs->trans("Export") . '" disabled="disabled" title="' . $langs->trans('ExportNotSupported') . '"/>';
 	} else {
 		print '<input type="button" class="butAction" style="float: right;" value="' . $langs->trans("Export") . '" onclick="launch_export();" />';
-	}
-
+	}*/
+    print '<div class="tabsAction">';
 	print '<input type="button" class="butAction" value="' . $langs->trans("WriteBookKeeping") . '" onclick="writebookkeeping();" />';
-
+    print '</div>';
+    
 	print '
 	<script type="text/javascript">
 		function launch_export() {
@@ -503,7 +546,7 @@ if (empty($action) || $action == 'view') {
 	/*
 	 * Show result array
 	 */
-	print '<br><br>';
+	print '<br>';
 
 	$i = 0;
 	print "<table class=\"noborder\" width=\"100%\">";
@@ -552,8 +595,8 @@ if (empty($action) || $action == 'view') {
 			print "<td>" . $companystatic->getNomUrl(0, 'customer', 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("Code_tiers") . "</td>";
 			print "</td><td align='right'>" . ($mt >= 0 ? price($mt) : '') . "</td>";
 			print "<td align='right'>" . ($mt < 0 ? price(- $mt) : '') . "</td>";
+		    print "</tr>";
 		}
-		print "</tr>";
 
 		// Product / Service
 		foreach ( $tabht[$key] as $k => $mt ) {
diff --git a/htdocs/accountancy/supplier/lines.php b/htdocs/accountancy/supplier/lines.php
index 1f0d06fbec67b576a8236bc6eb814f458b98a3f5..09cf552c7bbe16973475858ccddc42184abbed70 100644
--- a/htdocs/accountancy/supplier/lines.php
+++ b/htdocs/accountancy/supplier/lines.php
@@ -44,6 +44,7 @@ $langs->load("productbatch");
 $account_parent = GETPOST('account_parent');
 $changeaccount = GETPOST('changeaccount');
 // Search Getpost
+$search_lineid = GETPOST('search_lineid', 'int');
 $search_ref = GETPOST('search_ref', 'alpha');
 $search_invoice = GETPOST('search_invoice', 'alpha');
 $search_label = GETPOST('search_label', 'alpha');
@@ -85,6 +86,7 @@ $formventilation = new FormVentilation($db);
 // Purge search criteria
 if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // All tests are required to be compatible with all browsers
 {
+    $search_lineid = '';
 	$search_ref = '';
 	$search_invoice = '';
 	$search_label = '';
@@ -148,7 +150,7 @@ print '<script type="text/javascript">
  * Supplier Invoice lines
  */
 $sql = "SELECT f.rowid as facid, f.ref as facnumber, f.ref_supplier, f.libelle as invoice_label, f.datef,";
-$sql.= " l.fk_product, l.description, l.total_ht , l.qty, l.rowid, l.tva_tx, aa.label, aa.account_number, ";
+$sql.= " l.rowid, l.fk_product, l.description, l.total_ht , l.qty, l.tva_tx, aa.label, aa.account_number, ";
 $sql.= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.fk_product_type as type";
 $sql.= " FROM " . MAIN_DB_PREFIX . "facture_fourn as f";
 $sql.= " , " . MAIN_DB_PREFIX . "accounting_account as aa";
@@ -156,6 +158,9 @@ $sql.= " , " . MAIN_DB_PREFIX . "facture_fourn_det as l";
 $sql.= " LEFT JOIN " . MAIN_DB_PREFIX . "product as p ON p.rowid = l.fk_product";
 $sql.= " WHERE f.rowid = l.fk_facture_fourn and f.fk_statut >= 1 AND l.fk_code_ventilation <> 0 ";
 $sql.= " AND aa.rowid = l.fk_code_ventilation";
+if ($search_lineid) {
+    $sql .= natural_search("l.rowid", $search_lineid, 1);
+}
 if (strlen(trim($search_invoice))) {
 	$sql .= natural_search("f.ref", $search_invoice);
 }
@@ -240,7 +245,7 @@ if ($result) {
 	print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n";
 	
 	print '<tr class="liste_titre_filter">';
-    print '<td class="liste_titre"></td>';
+	print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_lineid" value="' . dol_escape_htmltag($search_lineid) . '""></td>';
 	print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_invoice" value="' . dol_escape_htmltag($search_invoice) . '"></td>';
 	print '<td class="liste_titre"></td>';
 	print '<td class="liste_titre"></td>';
diff --git a/htdocs/accountancy/supplier/list.php b/htdocs/accountancy/supplier/list.php
index beae148c01b2639af558e1f4975736037fbd8b9e..e702aa8add807de7b592162543da214f37c11b30 100644
--- a/htdocs/accountancy/supplier/list.php
+++ b/htdocs/accountancy/supplier/list.php
@@ -52,6 +52,7 @@ $toselect = GETPOST('toselect', 'array');
 $mesCasesCochees = GETPOST('toselect', 'array');
 
 // Search Getpost
+$search_lineid = GETPOST('search_lineid', 'int');
 $search_invoice = GETPOST('search_invoice', 'alpha');
 $search_ref = GETPOST('search_ref', 'alpha');
 $search_label = GETPOST('search_label', 'alpha');
@@ -101,6 +102,7 @@ if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction !=
 // Purge search criteria
 if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // All test are required to be compatible with all browsers
 {
+    $search_lineid = '';
     $search_ref = '';
     $search_invoice = '';    
     $search_label = '';
@@ -179,7 +181,7 @@ llxHeader('', $langs->trans("SuppliersVentilation"));
 
 // Supplier Invoice Lines
 $sql = "SELECT f.rowid as facid, f.ref, f.ref_supplier, f.libelle as invoice_label, f.datef,";
-$sql.= " l.fk_product, l.description, l.total_ht as price, l.rowid, l.fk_code_ventilation, l.product_type as type_l, l.tva_tx as tva_tx_line, ";
+$sql.= " l.rowid, l.fk_product, l.description, l.total_ht as price, l.fk_code_ventilation, l.product_type as type_l, l.tva_tx as tva_tx_line, ";
 $sql.= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.fk_product_type as type, p.accountancy_code_buy as code_buy, p.tva_tx as tva_tx_prod,";
 $sql.= " aa.rowid as aarowid";
 $sql.= " FROM " . MAIN_DB_PREFIX . "facture_fourn as f";
@@ -191,6 +193,9 @@ $sql.= " WHERE f.fk_statut > 0 AND l.fk_code_ventilation <= 0";
 $sql.= " AND product_type <= 2";
 $sql.= " AND (accsys.rowid='" . $conf->global->CHARTOFACCOUNTS . "' OR p.accountancy_code_buy IS NULL OR p.accountancy_code_buy ='')";
 // Add search filter like
+if ($search_lineid) {
+    $sql .= natural_search("l.rowid", $search_lineid, 1);
+}
 if (strlen(trim($search_invoice))) {
     $sql .= natural_search("f.ref",$search_invoice);
 }
@@ -272,7 +277,7 @@ if ($result) {
 
 	// We add search filter
 	print '<tr class="liste_titre_filter">';
-	print '<td class="liste_titre"></td>';
+	print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_lineid" value="' . dol_escape_htmltag($search_lineid) . '""></td>';
 	print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_invoice" value="' . dol_escape_htmltag($search_invoice) . '"></td>';
 	print '<td class="liste_titre"></td>';
 	print '<td class="liste_titre"></td>';
diff --git a/htdocs/adherents/subscription.php b/htdocs/adherents/subscription.php
index 199cc6b275e92b2d76075e0db474018c46e19a8f..658cdfee3239fd2c5526c2bced58cd876a57de7b 100644
--- a/htdocs/adherents/subscription.php
+++ b/htdocs/adherents/subscription.php
@@ -89,14 +89,14 @@ if ($rowid)
     $caneditfieldmember=$user->rights->adherent->creer;
 }
 
+// Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array
+$hookmanager->initHooks(array('subscription'));
+
 // PDF
 $hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0));
 $hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0));
 $hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0));
 
-
-
-
 /*
  * 	Actions
  */
diff --git a/htdocs/admin/agenda.php b/htdocs/admin/agenda.php
index d076fcf7e26c963a0ab5a4f951d4aabe438173f4..22679ca697bdb5d1e7e137087ab2f93d91d785d6 100644
--- a/htdocs/admin/agenda.php
+++ b/htdocs/admin/agenda.php
@@ -144,13 +144,12 @@ print '<input type="hidden" name="action" value="save">';
 
 $head=agenda_prepare_head();
 
-dol_fiche_head($head, 'autoactions', $langs->trans("Agenda"), 0, 'action');
+dol_fiche_head($head, 'autoactions', $langs->trans("Agenda"), -1, 'action');
 
 print $langs->trans("AgendaAutoActionDesc")."<br>\n";
 print $langs->trans("OnlyActiveElementsAreShown").'<br>';
 print "<br>\n";
 
-$var=true;
 print '<table class="noborder" width="100%">';
 print '<tr class="liste_titre">';
 print '<td colspan="2">'.$langs->trans("ActionsEvents").'</td>';
@@ -180,7 +179,7 @@ if (! empty($triggers))
 			print '<td align="right" width="40">';
 			$key='MAIN_AGENDA_ACTIONAUTO_'.$trigger['code'];
 			$value=$conf->global->$key;
-			print '<input '.$bc[$var].' type="checkbox" name="'.$key.'" value="1"'.((($action=='selectall'||$value) && $action!="selectnone")?' checked':'').'>';
+			print '<input class="oddeven" type="checkbox" name="'.$key.'" value="1"'.((($action=='selectall'||$value) && $action!="selectnone")?' checked':'').'>';
 			print '</td></tr>'."\n";
 		}
 	}
diff --git a/htdocs/admin/agenda_extrafields.php b/htdocs/admin/agenda_extrafields.php
index 2cf3a323c219cdfe358570cd94062f02c1b22095..74ae6cb2d951dfd2483de601b9bb5b8824a1eec8 100644
--- a/htdocs/admin/agenda_extrafields.php
+++ b/htdocs/admin/agenda_extrafields.php
@@ -75,7 +75,7 @@ print "<br>\n";
 
 $head=agenda_prepare_head();
 
-dol_fiche_head($head, 'attributes', $langs->trans("Agenda"), 0, 'action');
+dol_fiche_head($head, 'attributes', $langs->trans("Agenda"), -1, 'action');
 
 require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_view.tpl.php';
 
diff --git a/htdocs/admin/agenda_extsites.php b/htdocs/admin/agenda_extsites.php
index 1e595b5088e8657e258002a990164441c705df3a..0b69b947a38917de50d1cc5a67682ca9f5d1a998 100644
--- a/htdocs/admin/agenda_extsites.php
+++ b/htdocs/admin/agenda_extsites.php
@@ -137,7 +137,7 @@ print '<input type="hidden" name="action" value="save">';
 
 $head=agenda_prepare_head();
 
-dol_fiche_head($head, 'extsites', $langs->trans("Agenda"), 0, 'action');
+dol_fiche_head($head, 'extsites', $langs->trans("Agenda"), -1, 'action');
 
 print $langs->trans("AgendaExtSitesDesc")."<br>\n";
 print "<br>\n";
diff --git a/htdocs/admin/agenda_other.php b/htdocs/admin/agenda_other.php
index 6e0a62610aa3fb10d9047ab4c340b7f1edbb3ce0..1d785e882fce73499b562a3530c60c3a8b300bdc 100644
--- a/htdocs/admin/agenda_other.php
+++ b/htdocs/admin/agenda_other.php
@@ -196,7 +196,7 @@ print "<br>\n";
 
 $head=agenda_prepare_head();
 
-dol_fiche_head($head, 'other', $langs->trans("Agenda"), 0, 'action');
+dol_fiche_head($head, 'other', $langs->trans("Agenda"), -1, 'action');
 
 
 /*
@@ -245,7 +245,6 @@ if ($conf->global->MAIN_FEATURES_LEVEL >= 2)
     
     clearstatcache();
     
-    $var=true;
     foreach ($dirmodels as $reldir)
     {
     	$dir = dol_buildpath($reldir."core/modules/action/doc/");
@@ -263,10 +262,9 @@ if ($conf->global->MAIN_FEATURES_LEVEL >= 2)
             			$classname = substr($file, 0, dol_strlen($file) -12);
             			
             			require_once $dir.'/'.$file;
-            			$module = new $classname($db, new ActionComm($db));
+            			$module = new $classname($db, new ActionComm($db));           			
             			
-            			
-            			print "<tr ".$bc[$var].">\n";
+            			print '<tr class="oddeven">'."\n";
             			print "<td>";
             			print (empty($module->name)?$name:$module->name);
             			print "</td>\n";
@@ -338,8 +336,6 @@ if ($conf->global->MAIN_FEATURES_LEVEL >= 2)
     print '</table><br>';
 }
 
-$var=true;
-
 print '<form action="'.$_SERVER["PHP_SELF"].'" name="agenda">';
 print '<input type="hidden" name="action" value="set">';
 
@@ -380,7 +376,6 @@ if (! empty($conf->global->AGENDA_USE_EVENT_TYPE))
 }
 
 // AGENDA_DEFAULT_FILTER_TYPE
-
 print '<tr class="oddeven">'."\n";
 print '<td>'.$langs->trans("AGENDA_DEFAULT_FILTER_TYPE").'</td>'."\n";
 print '<td align="center">&nbsp;</td>'."\n";
@@ -389,7 +384,6 @@ $formactions->select_type_actions($conf->global->AGENDA_DEFAULT_FILTER_TYPE, "AG
 print '</td></tr>'."\n";
 
 // AGENDA_DEFAULT_FILTER_STATUS
-
 print '<tr class="oddeven">'."\n";
 print '<td>'.$langs->trans("AGENDA_DEFAULT_FILTER_STATUS").'</td>'."\n";
 print '<td align="center">&nbsp;</td>'."\n";
@@ -398,7 +392,6 @@ $formactions->form_select_status_action('agenda', $conf->global->AGENDA_DEFAULT_
 print '</td></tr>'."\n";
 
 // AGENDA_DEFAULT_VIEW
-
 print '<tr class="oddeven">'."\n";
 print '<td>'.$langs->trans("AGENDA_DEFAULT_VIEW").'</td>'."\n";
 print '<td align="center">&nbsp;</td>'."\n";
diff --git a/htdocs/admin/agenda_xcal.php b/htdocs/admin/agenda_xcal.php
index cd2406e6fdc2e8a7690bec6913b592396fb01c17..0e66125ba7c585bd18be64ee365cd1b21eca3d33 100644
--- a/htdocs/admin/agenda_xcal.php
+++ b/htdocs/admin/agenda_xcal.php
@@ -83,7 +83,7 @@ print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
 
 $head=agenda_prepare_head();
 
-dol_fiche_head($head, 'xcal', $langs->trans("Agenda"), 0, 'action');
+dol_fiche_head($head, 'xcal', $langs->trans("Agenda"), -1, 'action');
 
 print $langs->trans("AgendaSetupOtherDesc")."<br>\n";
 print "<br>\n";
diff --git a/htdocs/admin/bank.php b/htdocs/admin/bank.php
index 98cecb2f44b24139a2811660a46e771042470ab7..8ed1e3cd9ac6d80dcdbb02b5669f3d9d1da7075c 100644
--- a/htdocs/admin/bank.php
+++ b/htdocs/admin/bank.php
@@ -273,7 +273,6 @@ print "</tr>\n";
 
 clearstatcache();
 
-$var = true;
 foreach ($dirmodels as $reldir) 
 {
     foreach (array('', '/doc') as $valdir) {
@@ -305,8 +304,7 @@ foreach ($dirmodels as $reldir)
                                 $modulequalified = 0;
                             
                             if ($modulequalified) {
-                                $var = ! $var;
-                                print '<tr ' . $bc[$var] . '><td width="100">';
+                                print '<tr class="oddeven"><td width="100">';
                                 print(empty($module->name) ? $name : $module->name);
                                 print "</td><td>\n";
                                 if (method_exists($module, 'info'))
diff --git a/htdocs/admin/clicktodial.php b/htdocs/admin/clicktodial.php
index 060c910753ab4f5752451d73ca7d5438557bc954..86b94d8ecf01b0a131a80f61b9072bfd9befee95 100644
--- a/htdocs/admin/clicktodial.php
+++ b/htdocs/admin/clicktodial.php
@@ -91,7 +91,8 @@ print '</td></tr>';
 
 print '<tr class="oddeven"><td>';
 print $langs->trans("DefaultLink").'</td><td>';
-print '<input style="width: 90%" type="text" name="CLICKTODIAL_URL"'.($conf->global->CLICKTODIAL_USE_TEL_LINK_ON_PHONE_NUMBERS?' disabled="disabled"':'').' value="'.$conf->global->CLICKTODIAL_URL.'"><br>';
+print '<input class="quatrevingtpercent" type="text" id="CLICKTODIAL_URL" name="CLICKTODIAL_URL"'.($conf->global->CLICKTODIAL_USE_TEL_LINK_ON_PHONE_NUMBERS?' disabled="disabled"':'').' value="'.$conf->global->CLICKTODIAL_URL.'"><br>';
+print ajax_autoselect('CLICKTODIAL_URL');
 print '<br>';
 print $langs->trans("ClickToDialUrlDesc").'<br>';
 print $langs->trans("Example").':<br>http://myphoneserver/mypage?login=__LOGIN__&password=__PASS__&caller=__PHONEFROM__&called=__PHONETO__';
diff --git a/htdocs/admin/company.php b/htdocs/admin/company.php
index 8c29fe67a1c6e77ad329792ec41c970eeb6c0bd3..ef22d8ecb4a2cdb9f55724cb9e569258c126ff2f 100644
--- a/htdocs/admin/company.php
+++ b/htdocs/admin/company.php
@@ -3,7 +3,7 @@
  * Copyright (C) 2004-2013	Laurent Destailleur		<eldy@users.sourceforge.net>
  * Copyright (C) 2005-2012	Regis Houssin			<regis.houssin@capnetworks.com>
  * Copyright (C) 2010-2014	Juanjo Menent			<jmenent@2byte.es>
- * Copyright (C) 2011-2016	Philippe Grand			<philippe.grand@atoo-net.com>
+ * Copyright (C) 2011-2017	Philippe Grand			<philippe.grand@atoo-net.com>
  * Copyright (C) 2015       Alexandre Spangaro      <aspangaro.dolibarr@gmail.com>
  *
  * This program is free software; you can redistribute it and/or modify
@@ -545,7 +545,6 @@ if ($action == 'edit' || $action == 'updateedit')
 	print '<tr class="liste_titre">';
 	print '<td class="titlefield">'.$langs->trans("FiscalYearInformation").'</td><td>'.$langs->trans("Value").'</td>';
 	print "</tr>\n";
-	$var=true;
 
 	
 	print '<tr class="oddeven"><td><label for="fiscalmonthstart">'.$langs->trans("FiscalMonthStart").'</label></td><td>';
@@ -561,10 +560,9 @@ if ($action == 'edit' || $action == 'updateedit')
 	print '<td class="titlefield">'.$langs->trans("VATManagement").'</td><td>'.$langs->trans("Description").'</td>';
 	print '<td align="right">&nbsp;</td>';
 	print "</tr>\n";
-	$var=true;
 
 	
-	print "<tr ".$bc[$var]."><td width=\"140\"><label><input type=\"radio\" name=\"optiontva\" id=\"use_vat\" value=\"1\"".(empty($conf->global->FACTURE_TVAOPTION)?"":" checked")."> ".$langs->trans("VATIsUsed")."</label></td>";
+	print "<tr class=\"oddeven\"><td width=\"140\"><label><input type=\"radio\" name=\"optiontva\" id=\"use_vat\" value=\"1\"".(empty($conf->global->FACTURE_TVAOPTION)?"":" checked")."> ".$langs->trans("VATIsUsed")."</label></td>";
 	print '<td colspan="2">';
 	print "<table>";
 	print "<tr><td><label for=\"use_vat\">".$langs->trans("VATIsUsedDesc")."</label></td></tr>";
@@ -573,7 +571,7 @@ if ($action == 'edit' || $action == 'updateedit')
 	print "</td></tr>\n";
 
 	
-	print "<tr ".$bc[$var]."><td width=\"140\"><label><input type=\"radio\" name=\"optiontva\" id=\"no_vat\" value=\"0\"".(empty($conf->global->FACTURE_TVAOPTION)?" checked":"")."> ".$langs->trans("VATIsNotUsed")."</label></td>";
+	print "<tr class=\"oddeven\"><td width=\"140\"><label><input type=\"radio\" name=\"optiontva\" id=\"no_vat\" value=\"0\"".(empty($conf->global->FACTURE_TVAOPTION)?" checked":"")."> ".$langs->trans("VATIsNotUsed")."</label></td>";
 	print '<td colspan="2">';
 	print "<table>";
 	print "<tr><td><label for=\"no_vat\">".$langs->trans("VATIsNotUsedDesc")."</label></td></tr>";
@@ -595,10 +593,9 @@ if ($action == 'edit' || $action == 'updateedit')
 		print '<td>'.$langs->transcountry("LocalTax1Management",$mysoc->country_code).'</td><td>'.$langs->trans("Description").'</td>';
 		print '<td align="right">&nbsp;</td>';
 		print "</tr>\n";
-		$var=true;
 		
 		// Note: When option is not set, it must not appears as set on on, because there is no default value for this option
-		print "<tr ".$bc[$var]."><td width=\"140\"><input type=\"radio\" name=\"optionlocaltax1\" id=\"lt1\" value=\"localtax1on\"".(($conf->global->FACTURE_LOCAL_TAX1_OPTION == '1' || $conf->global->FACTURE_LOCAL_TAX1_OPTION == "localtax1on")?" checked":"")."> ".$langs->transcountry("LocalTax1IsUsed",$mysoc->country_code)."</td>";
+		print "<tr class=\"oddeven\"><td width=\"140\"><input type=\"radio\" name=\"optionlocaltax1\" id=\"lt1\" value=\"localtax1on\"".(($conf->global->FACTURE_LOCAL_TAX1_OPTION == '1' || $conf->global->FACTURE_LOCAL_TAX1_OPTION == "localtax1on")?" checked":"")."> ".$langs->transcountry("LocalTax1IsUsed",$mysoc->country_code)."</td>";
 		print '<td colspan="2">';
 		print '<table class="nobordernopadding">';
 		print "<tr><td><label for=\"lt1\">".$langs->transcountry("LocalTax1IsUsedDesc",$mysoc->country_code)."</label></td></tr>";
@@ -620,7 +617,7 @@ if ($action == 'edit' || $action == 'updateedit')
 		print "</td></tr>\n";
 
 		
-		print "<tr ".$bc[$var]."><td width=\"140\"><input type=\"radio\" name=\"optionlocaltax1\" id=\"nolt1\" value=\"localtax1off\"".((empty($conf->global->FACTURE_LOCAL_TAX1_OPTION) || $conf->global->FACTURE_LOCAL_TAX1_OPTION == "localtax1off")?" checked":"")."> ".$langs->transcountry("LocalTax1IsNotUsed",$mysoc->country_code)."</td>";
+		print "<tr class=\"oddeven\"><td width=\"140\"><input type=\"radio\" name=\"optionlocaltax1\" id=\"nolt1\" value=\"localtax1off\"".((empty($conf->global->FACTURE_LOCAL_TAX1_OPTION) || $conf->global->FACTURE_LOCAL_TAX1_OPTION == "localtax1off")?" checked":"")."> ".$langs->transcountry("LocalTax1IsNotUsed",$mysoc->country_code)."</td>";
 		print '<td colspan="2">';
 		print "<table>";
 		print "<tr><td><label for=\"nolt1\">".$langs->transcountry("LocalTax1IsNotUsedDesc",$mysoc->country_code)."</label></td></tr>";
@@ -639,11 +636,10 @@ if ($action == 'edit' || $action == 'updateedit')
 		print '<td>'.$langs->transcountry("LocalTax2Management",$mysoc->country_code).'</td><td>'.$langs->trans("Description").'</td>';
 		print '<td align="right">&nbsp;</td>';
 		print "</tr>\n";
-		$var=true;
 
 		
 		// Note: When option is not set, it must not appears as set on on, because there is no default value for this option
-		print "<tr ".$bc[$var]."><td width=\"140\"><input type=\"radio\" name=\"optionlocaltax2\" id=\"lt2\" value=\"localtax2on\"".(($conf->global->FACTURE_LOCAL_TAX2_OPTION == '1' || $conf->global->FACTURE_LOCAL_TAX2_OPTION == "localtax2on")?" checked":"")."> ".$langs->transcountry("LocalTax2IsUsed",$mysoc->country_code)."</td>";
+		print "<tr class=\"oddeven\"><td width=\"140\"><input type=\"radio\" name=\"optionlocaltax2\" id=\"lt2\" value=\"localtax2on\"".(($conf->global->FACTURE_LOCAL_TAX2_OPTION == '1' || $conf->global->FACTURE_LOCAL_TAX2_OPTION == "localtax2on")?" checked":"")."> ".$langs->transcountry("LocalTax2IsUsed",$mysoc->country_code)."</td>";
 		print '<td colspan="2">';
 		print '<table class="nobordernopadding">';
 		print "<tr><td><label for=\"lt2\">".$langs->transcountry("LocalTax2IsUsedDesc",$mysoc->country_code)."</label></td></tr>";
@@ -662,7 +658,7 @@ if ($action == 'edit' || $action == 'updateedit')
 		print "</td></tr>\n";
 
 		
-		print "<tr ".$bc[$var]."><td width=\"140\"><input type=\"radio\" name=\"optionlocaltax2\" id=\"nolt2\" value=\"localtax2off\"".((empty($conf->global->FACTURE_LOCAL_TAX2_OPTION) || $conf->global->FACTURE_LOCAL_TAX2_OPTION == "localtax2off")?" checked":"")."> ".$langs->transcountry("LocalTax2IsNotUsed",$mysoc->country_code)."</td>";
+		print "<tr class=\"oddeven\"><td width=\"140\"><input type=\"radio\" name=\"optionlocaltax2\" id=\"nolt2\" value=\"localtax2off\"".((empty($conf->global->FACTURE_LOCAL_TAX2_OPTION) || $conf->global->FACTURE_LOCAL_TAX2_OPTION == "localtax2off")?" checked":"")."> ".$langs->transcountry("LocalTax2IsNotUsed",$mysoc->country_code)."</td>";
 		print '<td colspan="2">';
 		print "<table>";
 		print "<tr><td><label for=\"nolt2\">".$langs->transcountry("LocalTax2IsNotUsedDesc",$mysoc->country_code)."</label></td></tr>";
@@ -696,7 +692,6 @@ else
 
 	print '<table class="noborder" width="100%">';
 	print '<tr class="liste_titre"><td>'.$langs->trans("CompanyInfo").'</td><td>'.$langs->trans("Value").'</td></tr>';
-	$var=true;
 
 	
 	print '<tr class="oddeven"><td class="titlefield">'.$langs->trans("CompanyName").'</td><td>';
@@ -799,7 +794,6 @@ else
 	print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
 	print '<table class="noborder" width="100%">';
 	print '<tr class="liste_titre"><td class="titlefield">'.$langs->trans("CompanyIds").'</td><td>'.$langs->trans("Value").'</td></tr>';
-	$var=true;
 
 	// Managing Director(s)
 	
@@ -965,7 +959,6 @@ else
 	print '<tr class="liste_titre">';
 	print '<td class="titlefield">'.$langs->trans("FiscalYearInformation").'</td><td>'.$langs->trans("Value").'</td>';
 	print "</tr>\n";
-	$var=true;
 
 	
 	print '<tr class="oddeven"><td>'.$langs->trans("FiscalMonthStart").'</td><td>';
@@ -983,10 +976,9 @@ else
 	print '<td>'.$langs->trans("VATManagement").'</td><td>'.$langs->trans("Description").'</td>';
 	print '<td align="right">&nbsp;</td>';
 	print "</tr>\n";
-	$var=true;
 
 	
-	print "<tr ".$bc[$var]."><td width=\"160\"><input ".$bc[$var]." type=\"radio\" name=\"optiontva\" id=\"use_vat\" disabled value=\"1\"".(empty($conf->global->FACTURE_TVAOPTION)?"":" checked")."> ".$langs->trans("VATIsUsed")."</td>";
+	print "<tr class=\"oddeven\"><td width=\"160\"><input class=\"oddeven\" type=\"radio\" name=\"optiontva\" id=\"use_vat\" disabled value=\"1\"".(empty($conf->global->FACTURE_TVAOPTION)?"":" checked")."> ".$langs->trans("VATIsUsed")."</td>";
 	print '<td colspan="2">';
 	print "<table>";
 	print "<tr><td><label for=\"use_vat\">".$langs->trans("VATIsUsedDesc")."</label></td></tr>";
@@ -995,7 +987,7 @@ else
 	print "</td></tr>\n";
 
 	
-	print "<tr ".$bc[$var]."><td width=\"160\"><input ".$bc[$var]." type=\"radio\" name=\"optiontva\" id=\"no_vat\" disabled value=\"0\"".(empty($conf->global->FACTURE_TVAOPTION)?" checked":"")."> ".$langs->trans("VATIsNotUsed")."</td>";
+	print "<tr class=\"oddeven\"><td width=\"160\"><input class=\"oddeven\" type=\"radio\" name=\"optiontva\" id=\"no_vat\" disabled value=\"0\"".(empty($conf->global->FACTURE_TVAOPTION)?" checked":"")."> ".$langs->trans("VATIsNotUsed")."</td>";
 	print '<td colspan="2">';
 	print "<table>";
 	print "<tr><td><label=\"no_vat\">".$langs->trans("VATIsNotUsedDesc")."</label></td></tr>";
@@ -1018,10 +1010,9 @@ else
 		print '<td>'.$langs->transcountry("LocalTax1Management",$mysoc->country_code).'</td><td>'.$langs->trans("Description").'</td>';
 		print '<td align="right">&nbsp;</td>';
 		print "</tr>\n";
-		$var=true;
 
 		
-		print "<tr ".$bc[$var]."><td width=\"160\"><input ".$bc[$var]." type=\"radio\" name=\"optionlocaltax1\" id=\"lt1\" disabled value=\"localtax1on\"".(($conf->global->FACTURE_LOCAL_TAX1_OPTION == '1' || $conf->global->FACTURE_LOCAL_TAX1_OPTION == "localtax1on")?" checked":"")."> ".$langs->transcountry("LocalTax1IsUsed",$mysoc->country_code)."</td>";
+		print "<tr class=\"oddeven\"><td width=\"160\"><input class=\"oddeven\" type=\"radio\" name=\"optionlocaltax1\" id=\"lt1\" disabled value=\"localtax1on\"".(($conf->global->FACTURE_LOCAL_TAX1_OPTION == '1' || $conf->global->FACTURE_LOCAL_TAX1_OPTION == "localtax1on")?" checked":"")."> ".$langs->transcountry("LocalTax1IsUsed",$mysoc->country_code)."</td>";
 		print '<td colspan="2">';
 		print "<table>";
 		print "<tr><td></label for=\"lt1\">".$langs->transcountry("LocalTax1IsUsedDesc",$mysoc->country_code)."</label></td></tr>";
@@ -1049,7 +1040,7 @@ else
 		print "</td></tr>\n";
 
 		
-		print "<tr ".$bc[$var]."><td width=\"160\"><input ".$bc[$var]." type=\"radio\" name=\"optionlocaltax1\" id=\"nolt1\" disabled value=\"localtax1off\"".((empty($conf->global->FACTURE_LOCAL_TAX1_OPTION) || $conf->global->FACTURE_LOCAL_TAX1_OPTION == "localtax1off")?" checked":"")."> ".$langs->transcountry("LocalTax1IsNotUsed",$mysoc->country_code)."</td>";
+		print "<tr class=\"oddeven\"><td width=\"160\"><input class=\"oddeven\" type=\"radio\" name=\"optionlocaltax1\" id=\"nolt1\" disabled value=\"localtax1off\"".((empty($conf->global->FACTURE_LOCAL_TAX1_OPTION) || $conf->global->FACTURE_LOCAL_TAX1_OPTION == "localtax1off")?" checked":"")."> ".$langs->transcountry("LocalTax1IsNotUsed",$mysoc->country_code)."</td>";
 		print '<td colspan="2">';
 		print "<table>";
 		print "<tr><td><label for=\"no_lt1\">".$langs->transcountry("LocalTax1IsNotUsedDesc",$mysoc->country_code)."</label></td></tr>";
@@ -1069,10 +1060,9 @@ else
 		print '<td>'.$langs->transcountry("LocalTax2Management",$mysoc->country_code).'</td><td>'.$langs->trans("Description").'</td>';
 		print '<td align="right">&nbsp;</td>';
 		print "</tr>\n";
-		$var=true;
 
 		
-		print "<tr ".$bc[$var]."><td width=\"160\"><input ".$bc[$var]." type=\"radio\" name=\"optionlocaltax2\" id=\"lt2\" disabled value=\"localtax2on\"".(($conf->global->FACTURE_LOCAL_TAX2_OPTION == '1' || $conf->global->FACTURE_LOCAL_TAX2_OPTION == "localtax2on")?" checked":"")."> ".$langs->transcountry("LocalTax2IsUsed",$mysoc->country_code)."</td>";
+		print "<tr class=\"oddeven\"><td width=\"160\"><input class=\"oddeven\" type=\"radio\" name=\"optionlocaltax2\" id=\"lt2\" disabled value=\"localtax2on\"".(($conf->global->FACTURE_LOCAL_TAX2_OPTION == '1' || $conf->global->FACTURE_LOCAL_TAX2_OPTION == "localtax2on")?" checked":"")."> ".$langs->transcountry("LocalTax2IsUsed",$mysoc->country_code)."</td>";
 		print '<td colspan="2">';
 		print "<table>";
 		print "<tr><td><label for=\"lt2\">".$langs->transcountry("LocalTax2IsUsedDesc",$mysoc->country_code)."</label></td></tr>";
@@ -1101,7 +1091,7 @@ else
 		print "</td></tr>\n";
 
 		
-		print "<tr ".$bc[$var]."><td width=\"160\"><input ".$bc[$var]." type=\"radio\" name=\"optionlocaltax2\" id=\"nolt2\" disabled value=\"localtax2off\"".((empty($conf->global->FACTURE_LOCAL_TAX2_OPTION) || $conf->global->FACTURE_LOCAL_TAX2_OPTION == "localtax2off")?" checked":"")."> ".$langs->transcountry("LocalTax2IsNotUsed",$mysoc->country_code)."</td>";
+		print "<tr class=\"oddeven\"><td width=\"160\"><input class=\"oddeven\" type=\"radio\" name=\"optionlocaltax2\" id=\"nolt2\" disabled value=\"localtax2off\"".((empty($conf->global->FACTURE_LOCAL_TAX2_OPTION) || $conf->global->FACTURE_LOCAL_TAX2_OPTION == "localtax2off")?" checked":"")."> ".$langs->transcountry("LocalTax2IsNotUsed",$mysoc->country_code)."</td>";
 		print '<td colspan="2">';
 		print "<table>";
 		print "<tr><td><label for=\"nolt2\">".$langs->transcountry("LocalTax2IsNotUsedDesc",$mysoc->country_code)."</label></td></tr>";
diff --git a/htdocs/admin/compta.php b/htdocs/admin/compta.php
index c097b9f39b13ed14635f3b22990bda0f04b76899..0c42659357a956998f1af4db06fecaa461f599a9 100644
--- a/htdocs/admin/compta.php
+++ b/htdocs/admin/compta.php
@@ -3,7 +3,7 @@
  * Copyright (C) 2004-2008 Laurent Destailleur  <eldy@users.sourceforge.net>
  * Copyright (C) 2005-2009 Regis Houssin        <regis.houssin@capnetworks.com>
  * Copyright (C) 2011-2013 Juanjo Menent	    <jmenent@2byte.es>
- * Copyright (C) 2013-2016 Philippe Grand	    <philippe.grand@atoo-net.com>
+ * Copyright (C) 2013-2017 Philippe Grand	    <philippe.grand@atoo-net.com>
  * Copyright (C) 2014      Marcos García        <marcosgdf@gmail.com>
  *
  * This program is free software; you can redistribute it and/or modify
@@ -119,7 +119,7 @@ print '<table class="noborder" width="100%">';
 print '<tr class="liste_titre">';
 print '<td>'.$langs->trans('OptionMode').'</td><td>'.$langs->trans('Description').'</td>';
 print "</tr>\n";
-print '<tr '.$bc[false].'><td width="200"><input type="radio" name="accounting_mode" value="RECETTES-DEPENSES"'.($accounting_mode != 'CREANCES-DETTES' ? ' checked' : '').'> '.$langs->trans('OptionModeTrue').'</td>';
+print '<tr class="oddeven"><td width="200"><input type="radio" name="accounting_mode" value="RECETTES-DEPENSES"'.($accounting_mode != 'CREANCES-DETTES' ? ' checked' : '').'> '.$langs->trans('OptionModeTrue').'</td>';
 print '<td colspan="2">'.nl2br($langs->trans('OptionModeTrueDesc'));
 // Write info on way to count VAT
 //if (! empty($conf->global->MAIN_MODULE_COMPTABILITE))
@@ -133,7 +133,7 @@ print '<td colspan="2">'.nl2br($langs->trans('OptionModeTrueDesc'));
 //	//	print nl2br($langs->trans('OptionModeTrueInfoExpert'));
 //}
 print "</td></tr>\n";
-print '<tr '.$bc[true].'><td width="200"><input type="radio" name="accounting_mode" value="CREANCES-DETTES"'.($accounting_mode == 'CREANCES-DETTES' ? ' checked' : '').'> '.$langs->trans('OptionModeVirtual').'</td>';
+print '<tr class="oddeven"><td width="200"><input type="radio" name="accounting_mode" value="CREANCES-DETTES"'.($accounting_mode == 'CREANCES-DETTES' ? ' checked' : '').'> '.$langs->trans('OptionModeVirtual').'</td>';
 print '<td colspan="2">'.nl2br($langs->trans('OptionModeVirtualDesc'))."</td></tr>\n";
 
 print "</table>\n";
@@ -149,8 +149,7 @@ print "</tr>\n";
 foreach ($list as $key)
 {
 	
-
-	print '<tr '.$bc[$var].' class="value">';
+	print '<tr class="oddeven value">';
 
 	// Param
 	$libelle = $langs->trans($key);
diff --git a/htdocs/admin/defaultvalues.php b/htdocs/admin/defaultvalues.php
index 8a9bd4f209bd56dd2be0211bcd9df70ac61f7f7b..dd37e4987e5399e34f3a06f855bcb749c7287fc9 100644
--- a/htdocs/admin/defaultvalues.php
+++ b/htdocs/admin/defaultvalues.php
@@ -37,7 +37,7 @@ if (!$user->admin) accessforbidden();
 $id=GETPOST('rowid','int');
 $action=GETPOST('action','alpha');
 
-$mode = GETPOST('mode')?GETPOST('mode'):'createform';   // 'createform', 'filters', 'sortorder'
+$mode = GETPOST('mode')?GETPOST('mode'):'createform';   // 'createform', 'filters', 'sortorder', 'focus'
 
 $limit = GETPOST("limit")?GETPOST("limit","int"):$conf->liste_limit;
 $sortfield = GETPOST("sortfield",'alpha');
@@ -84,6 +84,11 @@ if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETP
     $search_array_options=array();
 }
 
+if ($action == 'setMAIN_ENABLE_DEFAULT_VALUES')
+{
+    if (GETPOST('value')) dolibarr_set_const($db, 'MAIN_ENABLE_DEFAULT_VALUES', 1, 'chaine', 0, '', $conf->entity);
+    else dolibarr_set_const($db, 'MAIN_ENABLE_DEFAULT_VALUES', 0, 'chaine', 0, '', $conf->entity);
+}
 
 if (($action == 'add' || (GETPOST('add') && $action != 'update')) || GETPOST('actionmodify'))
 {
@@ -185,6 +190,23 @@ print load_fiche_titre($langs->trans("DefaultValues"),'','title_setup');
 print $langs->trans("DefaultValuesDesc")."<br>\n";
 print "<br>\n";
 
+print $langs->trans("EnableDefaultValues").' ';
+if (empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES))
+{
+    // Button off, click to enable
+    print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?action=setMAIN_ENABLE_DEFAULT_VALUES&amp;value=1">';
+    print img_picto($langs->trans("Disabled"),'switch_off');
+    print '</a>';
+}
+else
+{
+    // Button on, click to disable
+    print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?action=setMAIN_ENABLE_DEFAULT_VALUES&amp;value=0">';
+    print img_picto($langs->trans("Activated"),'switch_on');
+    print '</a>';
+}
+print "<br><br>\n";
+
 $param='&mode='.$mode;
 if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage;
 if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit;
@@ -210,6 +232,10 @@ if ($mode == 'sortorder')
 {
     print info_admin($langs->trans("WarningSettingSortOrder")).'<br>';
 }
+if ($mode == 'focus')
+{
+    print info_admin($langs->trans("FeatureNotYetAvailable")).'<br>';
+}
 
 print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
 print '<input type="hidden" id="action" name="action" value="">';
@@ -217,11 +243,13 @@ print '<input type="hidden" id="mode" name="mode" value="'.dol_escape_htmltag($m
 
 print '<table class="noborder" width="100%">';
 print '<tr class="liste_titre">';
+// Page
 $texthelp=$langs->trans("PageUrlForDefaultValues");
 if ($mode == 'createform') $texthelp.=$langs->trans("PageUrlForDefaultValuesCreate", 'societe/card.php');
 else $texthelp.=$langs->trans("PageUrlForDefaultValuesList", 'societe/list.php');
 $texturl=$form->textwithpicto($langs->trans("Url"), $texthelp);
 print_liste_field_titre($texturl,$_SERVER["PHP_SELF"],'page,param','',$param,'',$sortfield,$sortorder);
+// Field
 $texthelp=$langs->trans("TheKeyIsTheNameOfHtmlField");
 if ($mode != 'sortorder') 
 {
@@ -233,26 +261,32 @@ else
     $textkey=$form->textwithpicto($langs->trans("Field"), $texthelp);
 }
 print_liste_field_titre($textkey,$_SERVER["PHP_SELF"],'param','',$param,'',$sortfield,$sortorder);
-if ($mode != 'sortorder')
-{
-    $texthelp=$langs->trans("FollowingConstantsWillBeSubstituted").'<br>';
-    // See list into GETPOST
-    $texthelp.='__USERID__<br>';
-    $texthelp.='__SUPERVISORID__<br>';
-    $texthelp.='__MYCOUNTRYID__<br>';
-    $texthelp.='__DAY__<br>';
-    $texthelp.='__MONTH__<br>';
-    $texthelp.='__YEAR__<br>';
-    if (! empty($conf->multicompany->enabled)) $texthelp.='__ENTITYID__<br>';
-    $textvalue=$form->textwithpicto($langs->trans("Value"), $texthelp, 1, 'help', '', 0, 2, '');
-}
-else
+// Value
+if ($mode != 'focus')
 {
-    $texthelp='ASC or DESC';
-    $textvalue=$form->textwithpicto($langs->trans("SortOrder"), $texthelp);
+    if ($mode != 'sortorder')
+    {
+        $texthelp=$langs->trans("FollowingConstantsWillBeSubstituted").'<br>';
+        // See list into GETPOST
+        $texthelp.='__USERID__<br>';
+        $texthelp.='__SUPERVISORID__<br>';
+        $texthelp.='__MYCOUNTRYID__<br>';
+        $texthelp.='__DAY__<br>';
+        $texthelp.='__MONTH__<br>';
+        $texthelp.='__YEAR__<br>';
+        if (! empty($conf->multicompany->enabled)) $texthelp.='__ENTITYID__<br>';
+        $textvalue=$form->textwithpicto($langs->trans("Value"), $texthelp, 1, 'help', '', 0, 2, '');
+    }
+    else
+    {
+        $texthelp='ASC or DESC';
+        $textvalue=$form->textwithpicto($langs->trans("SortOrder"), $texthelp);
+    }
+    print_liste_field_titre($textvalue, $_SERVER["PHP_SELF"], 'value', '', $param, '', $sortfield, $sortorder);
 }
-print_liste_field_titre($textvalue, $_SERVER["PHP_SELF"], 'value', '', $param, '', $sortfield, $sortorder);
+// Entity
 if (! empty($conf->multicompany->enabled) && !$user->entity) print_liste_field_titre($langs->trans("Entity"),$_SERVER["PHP_SELF"],'entity,page','',$param,'',$sortfield,$sortorder);
+// Actions
 print '<td align="center"></td>';
 print "</tr>\n";
 
@@ -261,15 +295,21 @@ print "</tr>\n";
 print "\n";
 
 print '<tr class="oddeven">';
+// Page
 print '<td>';
 print '<input type="text" class="flat minwidth200 maxwidthonsmartphone" name="defaulturl" value="">';
 print '</td>'."\n";
+// Field
 print '<td>';
 print '<input type="text" class="flat maxwidth100" name="defaultkey" value="">';
 print '</td>';
-print '<td>';
-print '<input type="text" class="flat maxwidthonsmartphone" name="defaultvalue" value="">';
-print '</td>';
+// Value
+if ($mode != 'focus')
+{
+    print '<td>';
+    print '<input type="text" class="flat maxwidthonsmartphone" name="defaultvalue" value="">';
+    print '</td>';
+}
 // Limit to superadmin
 if (! empty($conf->multicompany->enabled) && !$user->entity)
 {
@@ -311,28 +351,33 @@ if ($result)
 
 		print '<tr class="oddeven">';
 		
+		// Page
 		print '<td>';
 		if ($action != 'edit' || GETPOST('rowid') != $obj->rowid) print $obj->page;
 		else print '<input type="text" name="urlpage" value="'.dol_escape_htmltag($obj->page).'">';
 		print '</td>'."\n";
    	    
-		// Key
+		// Field
 		print '<td>';
 		if ($action != 'edit' || GETPOST('rowid') != $obj->rowid) print $obj->param;
 		else print '<input type="text" name="key" value="'.dol_escape_htmltag($obj->param).'">';
 		print '</td>'."\n";
 
 		// Value
-		print '<td>';
-		/*print '<input type="hidden" name="const['.$i.'][rowid]" value="'.$obj->rowid.'">';
-		print '<input type="hidden" name="const['.$i.'][lang]" value="'.$obj->lang.'">';
-		print '<input type="hidden" name="const['.$i.'][name]" value="'.$obj->transkey.'">';
-		print '<input type="text" id="value_'.$i.'" class="flat inputforupdate" size="30" name="const['.$i.'][value]" value="'.dol_escape_htmltag($obj->transvalue).'">';
-		*/
-		if ($action != 'edit' || GETPOST('rowid') != $obj->rowid) print $obj->value;
-		else print '<input type="text" name="value" value="'.dol_escape_htmltag($obj->value).'">';
-		print '</td>';
-
+		if ($mode != 'focus')
+		{
+    		print '<td>';
+    		/*print '<input type="hidden" name="const['.$i.'][rowid]" value="'.$obj->rowid.'">';
+    		print '<input type="hidden" name="const['.$i.'][lang]" value="'.$obj->lang.'">';
+    		print '<input type="hidden" name="const['.$i.'][name]" value="'.$obj->transkey.'">';
+    		print '<input type="text" id="value_'.$i.'" class="flat inputforupdate" size="30" name="const['.$i.'][value]" value="'.dol_escape_htmltag($obj->transvalue).'">';
+    		*/
+    		if ($action != 'edit' || GETPOST('rowid') != $obj->rowid) print $obj->value;
+    		else print '<input type="text" name="value" value="'.dol_escape_htmltag($obj->value).'">';
+    		print '</td>';
+		}
+		
+		// Actions
 		print '<td align="center">';
 		if ($action != 'edit' || GETPOST('rowid') != $obj->rowid)
 		{
@@ -349,7 +394,7 @@ if ($result)
 		    print '<input type="submit" class="button" name="actioncancel" value="'.$langs->trans("Cancel").'">';
 		}
 		print '</td>';
-		
+        
 		print "</tr>\n";
 		print "\n";
 		$i++;
diff --git a/htdocs/admin/dict.php b/htdocs/admin/dict.php
index 125f913eb8db6f4e0425a84c8714d3ca4c61e573..c2730e6c0348beabc21675b145ed43901d5d9be5 100644
--- a/htdocs/admin/dict.php
+++ b/htdocs/admin/dict.php
@@ -918,10 +918,19 @@ if (empty($id))
 print "<br>\n";
 
 
+$param = '&id='.$id;
+if ($search_country_id > 0) $param.= '&search_country_id='.$search_country_id;
+if ($search_code != '')     $param.= '&search_code='.urlencode($search_country_id);
+$paramwithsearch = $param;
+if ($sortorder) $paramwithsearch.= '&sortorder='.$sortorder;
+if ($sortfield) $paramwithsearch.= '&sortfield='.$sortfield;
+if (GETPOST('from')) $paramwithsearch.= '&from='.GETPOST('from','alpha');
+
+
 // Confirmation de la suppression de la ligne
 if ($action == 'delete')
 {
-    print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid.'&code='.urlencode($_GET["code"]).'&id='.$id, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete','',0,1);
+    print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'rowid='.$rowid.'&code='.urlencode($_GET["code"]).$paramwithsearch, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete','',0,1);
 }
 //var_dump($elementList);
 
@@ -1073,7 +1082,7 @@ if ($id)
         print '</tr>';
 
         // Line to enter new values
-        print '<tr class="oddeven nodrag nodrop nohover">';
+        print '<!-- line to add new entry --><tr class="oddeven nodrag nodrop nohover">';
 
         $obj = new stdClass();
         // If data was already input, we define them in obj to populate input fields.
@@ -1134,14 +1143,6 @@ if ($id)
         $num = $db->num_rows($resql);
         $i = 0;
 
-        $param = '&id='.$id;
-        if ($search_country_id > 0) $param.= '&search_country_id='.$search_country_id;
-        if ($search_code != '')     $param.= '&search_code='.urlencode($search_country_id);
-        $paramwithsearch = $param;
-        if ($sortorder) $paramwithsearch.= '&sortorder='.$sortorder;
-        if ($sortfield) $paramwithsearch.= '&sortfield='.$sortfield;
-        if (GETPOST('from')) $paramwithsearch.= '&from='.GETPOST('from','alpha');
-        
         // There is several pages
         if ($num > $listlimit)
         {
@@ -1814,13 +1815,14 @@ function fieldList($fieldlist, $obj='', $tabname='', $context='')
 			if ($fieldlist[$field]=='affect') $class='maxwidth50';
 			if ($fieldlist[$field]=='delay') $class='maxwidth50';
 			if ($fieldlist[$field]=='position') $class='maxwidth50';
-			if ($fieldlist[$field]=='libelle') $class='quatrevingtpercent';
+			if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') $class='quatrevingtpercent';
 			if ($fieldlist[$field]=='tracking') $class='quatrevingtpercent';
 			if ($fieldlist[$field]=='sortorder' || $fieldlist[$field]=='sens' || $fieldlist[$field]=='category_type') $class='maxwidth50';
 			print '<td class="'.$classtd.'">';
 			$transfound=0;
 			if (in_array($fieldlist[$field], array('label','libelle')))
 			{
+			    $transkey='';
 			    // Special case for labels
 			    if ($tabname == MAIN_DB_PREFIX.'c_civility') {
 			        $transkey="Civility".strtoupper($obj->code);
@@ -1829,7 +1831,7 @@ function fieldList($fieldlist, $obj='', $tabname='', $context='')
 			        $langs->load("bills");
 			        $transkey="PaymentCondition".strtoupper($obj->code);
 			    }
-			    if ($langs->trans($transkey) != $transkey)
+			    if ($transkey && $langs->trans($transkey) != $transkey)
 			    {
 			        $transfound=1;
 			        print $form->textwithpicto($langs->trans($transkey), $langs->trans("GoIntoTranslationMenuToChangeThis"));
diff --git a/htdocs/admin/events.php b/htdocs/admin/events.php
index 161b1aac45d9ee83cb7d7079351df48dd65282e4..74525a6855b36e1bb73a076373e93c6aa4e6cd5a 100644
--- a/htdocs/admin/events.php
+++ b/htdocs/admin/events.php
@@ -105,7 +105,7 @@ foreach ($eventstolog as $key => $arr)
 		print '<td>';
 		$key='MAIN_LOGEVENTS_'.$arr['id'];
 		$value=$conf->global->$key;
-		print '<input '.$bc[$var].' type="checkbox" name="'.$key.'" value="1"'.($value?' checked':'').'>';
+		print '<input class="oddeven" type="checkbox" name="'.$key.'" value="1"'.($value?' checked':'').'>';
 		print '</td></tr>'."\n";
 	}
 }
diff --git a/htdocs/admin/expensereport.php b/htdocs/admin/expensereport.php
index dad17585e2ecfc21c9eaaf5dbcef1cb85faba886..b8626827595d51f869135745ea683b69e54f55c9 100644
--- a/htdocs/admin/expensereport.php
+++ b/htdocs/admin/expensereport.php
@@ -230,7 +230,7 @@ print load_fiche_titre($langs->trans("ExpenseReportsSetup"),$linkback,'title_set
 
 $head=expensereport_admin_prepare_head();
 
-dol_fiche_head($head, 'expensereport', $langs->trans("ExpenseReports"), 0, 'trip');
+dol_fiche_head($head, 'expensereport', $langs->trans("ExpenseReports"), -1, 'trip');
 
 // Interventions numbering model
 /*
diff --git a/htdocs/admin/expensereport_extrafields.php b/htdocs/admin/expensereport_extrafields.php
index 65e1592eff866634e73bafe91e0d22e811b5a1c2..d1d3aacc9ccbb08154cb8cf62e75ccb8696b95fe 100644
--- a/htdocs/admin/expensereport_extrafields.php
+++ b/htdocs/admin/expensereport_extrafields.php
@@ -74,7 +74,7 @@ print load_fiche_titre($langs->trans("ExpenseReportsSetup"),$linkback,'title_set
 
 $head = expensereport_admin_prepare_head();
 
-dol_fiche_head($head, 'attributes', $langs->trans("ExpenseReports"), 0, 'trip');
+dol_fiche_head($head, 'attributes', $langs->trans("ExpenseReports"), -1, 'trip');
 
 require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_view.tpl.php';
 
diff --git a/htdocs/admin/fichinter.php b/htdocs/admin/fichinter.php
index 0b01f56857ea67dc5b16d9339c09ae1a1ab5c3ec..d99fd9456d97017ca7b966435d7d897ed41a566f 100644
--- a/htdocs/admin/fichinter.php
+++ b/htdocs/admin/fichinter.php
@@ -6,7 +6,7 @@
  * Copyright (C) 2005-2014 Regis Houssin                <regis.houssin@capnetworks.com>
  * Copyright (C) 2008      Raphael Bertrand (Resultic)  <raphael.bertrand@resultic.fr>
  * Copyright (C) 2011-2013 Juanjo Menent			    <jmenent@2byte.es>
- * Copyright (C) 2011-2015 Philippe Grand			    <philippe.grand@atoo-net.com>
+ * Copyright (C) 2011-2017 Philippe Grand			    <philippe.grand@atoo-net.com>
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -265,7 +265,7 @@ print load_fiche_titre($langs->trans("InterventionsSetup"),$linkback,'title_setu
 
 $head=fichinter_admin_prepare_head();
 
-dol_fiche_head($head, 'ficheinter', $langs->trans("Interventions"), 0, 'intervention');
+dol_fiche_head($head, 'ficheinter', $langs->trans("Interventions"), -1, 'intervention');
 
 // Interventions numbering model
 
@@ -291,7 +291,6 @@ foreach ($dirmodels as $reldir)
 		$handle = opendir($dir);
 		if (is_resource($handle))
 		{
-			$var=true;
 
 			while (($file = readdir($handle))!==false)
 			{
@@ -410,7 +409,6 @@ print "</tr>\n";
 
 clearstatcache();
 
-$var=true;
 foreach ($dirmodels as $reldir)
 {
 	$dir = dol_buildpath($reldir."core/modules/fichinter/doc/");
@@ -532,7 +530,6 @@ print '<td>'.$langs->trans("Parameter").'</td>';
 print '<td align="center" width="60">'.$langs->trans("Value").'</td>';
 print "<td>&nbsp;</td>\n";
 print "</tr>\n";
-$var=true;
 
 $substitutionarray=pdf_getSubstitutionArray($langs);
 $substitutionarray['__(AnyTranslationKey)__']=$langs->trans("Translation");
@@ -540,7 +537,6 @@ $htmltext = '<i>'.$langs->trans("AvailableVariables").':<br>';
 foreach($substitutionarray as $key => $val)	$htmltext.=$key.'<br>';
 $htmltext.='</i>';
 
-$var=! $var;
 print '<form action="'.$_SERVER["PHP_SELF"].'" method="post">';
 print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
 print '<input type="hidden" name="action" value="set_FICHINTER_FREE_TEXT">';
@@ -590,11 +586,10 @@ print '</td><td align="right">';
 print '<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
 print "</td></tr>\n";
 // Use services duration
-$var = !$var;
 print '<form action="' . $_SERVER["PHP_SELF"] . '" method="post">';
 print '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
 print '<input type="hidden" name="action" value="set_FICHINTER_USE_SERVICE_DURATION">';
-print '<tr ' . $bc[$var] . '>';
+print '<tr class="oddeven">';
 print '<td>';
 print $langs->trans("UseServicesDurationOnFichinter");
 print '</td>';
diff --git a/htdocs/admin/ihm.php b/htdocs/admin/ihm.php
index 193ee35a80fe344e1bf9d8c3ec945f708643b7c7..739a6fa4c884b00c9022811a92538bc0962acb8a 100644
--- a/htdocs/admin/ihm.php
+++ b/htdocs/admin/ihm.php
@@ -50,18 +50,6 @@ $action = GETPOST('action');
 
 if (! defined("MAIN_MOTD")) define("MAIN_MOTD","");
 
-// List of supported permanent search area
-$searchform=array();
-/* deprecated
-if (empty($conf->use_javascript_ajax))
-{
-    $searchform=array("MAIN_SEARCHFORM_SOCIETE", "MAIN_SEARCHFORM_CONTACT", "MAIN_SEARCHFORM_PRODUITSERVICE", "MAIN_SEARCHFORM_ADHERENT", "MAIN_SEARCHFORM_PROJECT", "MAIN_SEARCHFORM_EMPLOYEE");
-    $searchformconst=array($conf->global->MAIN_SEARCHFORM_SOCIETE,$conf->global->MAIN_SEARCHFORM_CONTACT,$conf->global->MAIN_SEARCHFORM_PRODUITSERVICE,$conf->global->MAIN_SEARCHFORM_ADHERENT,$conf->global->MAIN_SEARCHFORM_PROJECT,$conf->global->MAIN_SEARCHFORM_EMPLOYEE);
-    $searchformtitle=array($langs->trans("Companies"), $langs->trans("Contacts"), $langs->trans("ProductsAndServices"), $langs->trans("Members"), $langs->trans("Projects"), $langs->trans("Users"));
-    $searchformmodule=array('Module1Name','Module1Name','Module50Name','Module310Name','Module400Name');
-}
-*/
-
 
 /*
  * Action
@@ -275,21 +263,6 @@ if ($action == 'edit')	// Edit
     show_theme(null,1);
     print '<br>';
 
-    // List of permanent supported search box
-    if (! empty($searchform))
-    {
-        print '<table summary="search" class="noborder" width="100%">';
-        print '<tr class="liste_titre"><td class="titlefield">'.$langs->trans("PermanentLeftSearchForm").'</td><td colspan="2">'.$langs->trans("Activated").'</td></tr>';
-        foreach ($searchform as $key => $value)
-        {
-            print '<tr><td class="titlefield">'.$searchformtitle[$key].'</td><td colspan="2">';
-            print $form->selectyesno($searchform[$key],$searchformconst[$key],1);
-            print '</td></tr>';
-        }
-        print '</table>';
-        print '<br>';
-    }
-    
     // Other
     print '<table summary="edit" class="noborder" width="100%">';
     print '<tr class="liste_titre"><td class="titlefield">'.$langs->trans("Parameters").'</td><td>'.$langs->trans("Value").'</td>';
@@ -476,23 +449,6 @@ else	// Show
     print '<br>';
 
 
-    // List of search forms to show
-    if (! empty($searchform))
-    {
-        print '<table class="noborder" width="100%">';
-        print '<tr class="liste_titre"><td class="titlefield">'.$langs->trans("PermanentLeftSearchForm").'</td><td>'.$langs->trans("Activated").'</td><td>&nbsp;</td></tr>';
-        foreach ($searchform as $key => $value)
-        {
-            
-            print '<tr class="oddeven"><td class="titlefield">'.$searchformtitle[$key].'</td><td>'.yn($searchformconst[$key]).'</td>';
-    		print '<td align="left">';
-    		if (! empty($searchformmodule[$key])) print $langs->trans("IfModuleEnabled",$langs->transnoentitiesnoconv($searchformmodule[$key]));
-            print '</td></tr>';
-        }
-        print '</table>';
-        print '<br>';
-    }
-
     // Other
     print '<table class="noborder" width="100%">';
     print '<tr class="liste_titre"><td class="titlefield">'.$langs->trans("Parameters").'</td><td colspan="2">'.$langs->trans("Value").'</td></tr>';
diff --git a/htdocs/admin/loan.php b/htdocs/admin/loan.php
index ee6b9ef74ee91f658f3b04be0fce611306b4b2ea..86d963ed54f776fe81a4fa2d79faf566ea05fa07 100644
--- a/htdocs/admin/loan.php
+++ b/htdocs/admin/loan.php
@@ -96,9 +96,7 @@ print "</tr>\n";
 
 foreach ($list as $key)
 {
-	
-
-	print '<tr '.$bc[$var].' class="value">';
+	print '<tr class="oddeven value">';
 
 	// Param
 	$label = $langs->trans($key); 
diff --git a/htdocs/admin/mails_templates.php b/htdocs/admin/mails_templates.php
index f0bf5609adf2ef805bb83cb89c70d3a1ef6397e0..a403cf1f4933035720059c472ced9a8ad68e1d46 100644
--- a/htdocs/admin/mails_templates.php
+++ b/htdocs/admin/mails_templates.php
@@ -4,7 +4,7 @@
  * Copyright (C) 2004       Benoit Mortier          <benoit.mortier@opensides.be>
  * Copyright (C) 2005-2012  Regis Houssin           <regis.houssin@capnetworks.com>
  * Copyright (C) 2010-2016  Juanjo Menent           <jmenent@2byte.es>
- * Copyright (C) 2011-2015  Philippe Grand          <philippe.grand@atoo-net.com>
+ * Copyright (C) 2011-2017  Philippe Grand          <philippe.grand@atoo-net.com>
  * Copyright (C) 2011       Remy Younes             <ryounes@gmail.com>
  * Copyright (C) 2012-2015  Marcos García           <marcosgdf@gmail.com>
  * Copyright (C) 2012       Christophe Battarel     <christophe.battarel@ltairis.fr>
@@ -118,17 +118,17 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
 $formmail=new FormMail($db);
 if (empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES))
 {
-    $tmp=$formmail->getAvailableSubstitKey('form');
+    $tmp=FormMail::getAvailableSubstitKey('formemail');
     $tmp['__(AnyTransKey)__']='__(AnyTransKey)__';
     $helpsubstit = $langs->trans("AvailableVariables").':<br>'.implode('<br>', $tmp);
     $helpsubstitforlines = $langs->trans("AvailableVariables").':<br>'.implode('<br>', $tmp);
 }
 else
 {
-    $tmp=$formmail->getAvailableSubstitKey('formwithlines');
+    $tmp=FormMail::getAvailableSubstitKey('formemailwithlines');
     $tmp['__(AnyTransKey)__']='__(AnyTransKey)__';
     $helpsubstit = $langs->trans("AvailableVariables").':<br>'.implode('<br>', $tmp);
-    $tmp=$formmail->getAvailableSubstitKey('formforlines');
+    $tmp=FormMail::getAvailableSubstitKey('formemailforlines');
     $helpsubstitforlines = $langs->trans("AvailableVariables").':<br>'.implode('<br>', $tmp);
 }
 
@@ -484,7 +484,11 @@ if ($action != 'edit')
         {
             print '<td align="'.$align.'">';
         	if (! empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i',$tabhelp[$id][$value])) print '<a href="'.$tabhelp[$id][$value].'" target="_blank">'.$valuetoshow.' '.img_help(1,$valuetoshow).'</a>';
-        	else if (! empty($tabhelp[$id][$value])) print $form->textwithpicto($valuetoshow,$tabhelp[$id][$value]);
+        	else if (! empty($tabhelp[$id][$value])) 
+        	{
+        	    if (in_array($value, array('topic'))) print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2, $value);   // Tooltip on click
+        	    else print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2);                             // Tooltip on hover
+        	}
         	else print $valuetoshow;
             print '</td>';
          }
@@ -539,8 +543,8 @@ if ($action != 'edit')
     foreach ($fieldsforcontent as $tmpfieldlist)
     {
         print '<tr class="impair nodrag nodrop nohover"><td colspan="5">';
-        if ($tmpfieldlist == 'content') print '<strong>'.$form->textwithpicto($langs->trans("Content"),$tabhelp[$id][$tmpfieldlist]).'</strong><br>';
-        if ($tmpfieldlist == 'content_lines') print '<strong>'.$form->textwithpicto($langs->trans("ContentForLines"),$tabhelp[$id][$tmpfieldlist]).'</strong><br>';
+        if ($tmpfieldlist == 'content') print '<strong>'.$form->textwithpicto($langs->trans("Content"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist).'</strong><br>';
+        if ($tmpfieldlist == 'content_lines') print '<strong>'.$form->textwithpicto($langs->trans("ContentForLines"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist).'</strong><br>';
     
         if ($context != 'hide')
         {
@@ -624,7 +628,11 @@ if ($resql)
         // Affiche nom du champ
         if ($showfield)
         {
-            if (! empty($tabhelp[$id][$value])) $valuetoshow = $form->textwithpicto($valuetoshow,$tabhelp[$id][$value]);
+            if (! empty($tabhelp[$id][$value])) 
+            {
+                if (in_array($value, array('topic'))) $valuetoshow = $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2);   // Tooltip on hover
+                else $valuetoshow = $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2);                             // Tooltip on hover
+            }
             print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable?$fieldlist[$field]:''), ($page?'page='.$page.'&':''), $param, "align=".$align, $sortfield, $sortorder);
         }
     }
@@ -651,11 +659,10 @@ if ($resql)
         // Lines with values
         while ($i < $num)
         {
-            $var = ! $var;
 
             $obj = $db->fetch_object($resql);
             //print_r($obj);
-            print '<tr '.$bc[$var].' id="rowid-'.$obj->rowid.'">';
+            print '<tr class="oddeven" id="rowid-'.$obj->rowid.'">';
             if ($action == 'edit' && ($rowid == (! empty($obj->rowid)?$obj->rowid:$obj->code)))
             {
                 $tmpaction='edit';
@@ -689,7 +696,7 @@ if ($resql)
                     // Show value for field
                     if ($showfield) {
                 
-                        print '</tr><tr '.$bc[$var].' nohover tr-'.$tmpfieldlist.'-'.$rowid.' "><td colspan="5">'; // To create an artificial CR for the current tr we are on
+                        print '</tr><tr class="oddeven" nohover tr-'.$tmpfieldlist.'-'.$rowid.' "><td colspan="5">'; // To create an artificial CR for the current tr we are on
                         $okforextended = true;
                         if (empty($conf->global->FCKEDITOR_ENABLE_MAIL))
                             $okforextended = false;
@@ -781,7 +788,7 @@ if ($resql)
                     // Show value for field
                     if ($showfield) {
                         
-                        print '</tr><tr '.$bc[$var].' nohover tr-'.$tmpfieldlist.'-'.$i.' "><td colspan="5">'; // To create an artificial CR for the current tr we are on
+                        print '</tr><tr class="oddeven" nohover tr-'.$tmpfieldlist.'-'.$i.' "><td colspan="5">'; // To create an artificial CR for the current tr we are on
                         $okforextended = true;
                         if (empty($conf->global->FCKEDITOR_ENABLE_MAIL))
                             $okforextended = false;
diff --git a/htdocs/admin/modulehelp.php b/htdocs/admin/modulehelp.php
index 94bfa8e05bb242f41e311f69e0af053381518a2f..d318566ff6115b5a18508edfba6648ae21ebe1fb 100644
--- a/htdocs/admin/modulehelp.php
+++ b/htdocs/admin/modulehelp.php
@@ -330,6 +330,24 @@ if ($mode == 'desc')
     else $text.=$langs->trans("Disabled");
     $text.='<br>';
 
+    $tmp = $objMod->getLastActivationInfo();
+    $authorid = $tmp['authorid'];
+    if ($authorid > 0)
+    {
+        $tmpuser = new User($db);
+        $tmpuser->fetch($authorid);
+        $text.='<strong>'.$langs->trans("LastActivationAuthor").':</strong> ';
+        $text.= $tmpuser->getNomUrl(1);
+        $text.='<br>';
+    }
+    $ip = $tmp['ip'];
+    if ($ip)
+    {
+        $text.='<strong>'.$langs->trans("LastActivationIP").':</strong> ';
+        $text.= $ip;
+        $text.='<br>';
+    }    
+    
     $moduledesclong=$objMod->getDescLong();
     if ($moduledesclong) $text.='<br><hr><div class="moduledesclong">'.$moduledesclong.'<div>';
 }
diff --git a/htdocs/admin/modules.php b/htdocs/admin/modules.php
index 4eb82e6183c451b6545df017a89a9a218e5e7555..433508be9083e7e79147e52af2f92880276fa39d 100644
--- a/htdocs/admin/modules.php
+++ b/htdocs/admin/modules.php
@@ -402,9 +402,9 @@ if ($nbofactivatedmodules <= 1) $moreinfo .= ' '.img_warning($langs->trans("YouM
 print load_fiche_titre($langs->trans("ModulesSetup"),$moreinfo,'title_setup');
 
 // Start to show page
-if ($mode=='common')      print $langs->trans("ModulesDesc")."<br>\n";
-if ($mode=='marketplace') print $langs->trans("ModulesMarketPlaceDesc")."<br>\n";
-if ($mode=='deploy')      print $langs->trans("ModulesDeployDesc", $langs->transnoentitiesnoconv("AvailableModules"))."<br>\n";
+if ($mode=='common')      print '<span class="opacitymedium">'.$langs->trans("ModulesDesc")."</span><br>\n";
+if ($mode=='marketplace') print '<span class="opacitymedium">'.$langs->trans("ModulesMarketPlaceDesc")."</span><br>\n";
+if ($mode=='deploy')      print '<span class="opacitymedium">'.$langs->trans("ModulesDeployDesc", $langs->transnoentitiesnoconv("AvailableModules"))."</span><br>\n";
 
 
 $h = 0;
@@ -428,8 +428,6 @@ $h++;
 print "<br>\n";
 
 
-$var=true;
-
 if ($mode == 'common')
 {
     
@@ -642,7 +640,8 @@ if ($mode == 'common')
         {
         	$disableSetup = 0;
 
-        	print '<td class="center valignmiddle" width="80px">';
+        	// Link enable/disabme
+        	print '<td class="center valignmiddle" width="60px">';
         	if (! empty($arrayofwarnings[$modName]))
 	        {
                 print '<!-- This module has a warning to show when we activate it (note: your country is '.$mysoc->country_code.') -->'."\n";
@@ -664,12 +663,12 @@ if ($mode == 'common')
         	}
         	print '</td>'."\n";
 
-        	// Config link
+        	// Link config
         	if (! empty($objMod->config_page_url) && !$disableSetup)
         	{
         		if (is_array($objMod->config_page_url))
         		{
-        			print '<td class="tdsetuppicto right" width="40px"">';
+        			print '<td class="tdsetuppicto right" width="60px">';
         			$i=0;
         			foreach ($objMod->config_page_url as $page)
         			{
@@ -695,22 +694,23 @@ if ($mode == 'common')
         		}
         		else if (preg_match('/^([^@]+)@([^@]+)$/i',$objMod->config_page_url,$regs))
         		{
-        			print '<td class="tdsetuppicto right valignmiddle" width="80px"><a href="'.dol_buildpath('/'.$regs[2].'/admin/'.$regs[1],1).'" title="'.$langs->trans("Setup").'">'.img_picto($langs->trans("Setup"),"setup",'style="padding-right: 6px"').'</a></td>';
+        			print '<td class="tdsetuppicto right valignmiddle" width="60px"><a href="'.dol_buildpath('/'.$regs[2].'/admin/'.$regs[1],1).'" title="'.$langs->trans("Setup").'">'.img_picto($langs->trans("Setup"),"setup",'style="padding-right: 6px"').'</a></td>';
         		}
         		else
         		{
-        			print '<td class="tdsetuppicto right valignmiddle" width="80px"><a href="'.$objMod->config_page_url.'" title="'.$langs->trans("Setup").'">'.img_picto($langs->trans("Setup"),"setup",'style="padding-right: 6px"').'</a></td>';
+        			print '<td class="tdsetuppicto right valignmiddle" width="60px"><a href="'.$objMod->config_page_url.'" title="'.$langs->trans("Setup").'">'.img_picto($langs->trans("Setup"),"setup",'style="padding-right: 6px"').'</a></td>';
         		}
         	}
         	else
         	{
-        		print '<td class="tdsetuppicto right valignmiddle" width="80px">'.img_picto($langs->trans("NothingToSetup"),"setup",'class="opacitytransp" style="padding-right: 6px"').'</td>';
+        		print '<td class="tdsetuppicto right valignmiddle" width="60px">'.img_picto($langs->trans("NothingToSetup"),"setup",'class="opacitytransp" style="padding-right: 6px"').'</td>';
         	}
 
         }
         else	// Module not yet activated
 		{
-        	print '<td class="center valignmiddle" width="80px">';
+		    // Link enable/disable
+        	print '<td class="center valignmiddle" width="60px">';
 		    if (! empty($objMod->always_enabled))
         	{
         		// Should never happened
@@ -756,7 +756,9 @@ if ($mode == 'common')
 	        	print "</a>\n";
         	}
         	print "</td>\n";
-        	print '<td class="tdsetuppicto right valignmiddle" width="80px">'.img_picto($langs->trans("NothingToSetup"),"setup",'class="opacitytransp" style="padding-right: 6px"').'</td>';
+        	
+        	// Link config
+        	print '<td class="tdsetuppicto right valignmiddle" width="60px">'.img_picto($langs->trans("NothingToSetup"),"setup",'class="opacitytransp" style="padding-right: 6px"').'</td>';
         }
 
         print "</tr>\n";
@@ -782,7 +784,7 @@ if ($mode == 'marketplace')
     print '</tr>';
 
     
-    print "<tr ".$bc[$var].">\n";
+    print "<tr class=\"oddeven\">\n";
     $url='https://www.dolistore.com';
     print '<td align="left"><a href="'.$url.'" target="_blank" rel="external"><img border="0" class="imgautosize imgmaxwidth180" src="'.DOL_URL_ROOT.'/theme/dolistore_logo.png"></a></td>';
     print '<td>'.$langs->trans("DoliStoreDesc").'</td>';
@@ -790,7 +792,7 @@ if ($mode == 'marketplace')
     print '</tr>';
 
     
-    print "<tr ".$bc[$var].">\n";
+    print "<tr class=\"oddeven\">\n";
     $url='https://partners.dolibarr.org';
     print '<td align="left"><a href="'.$url.'" target="_blank" rel="external"><img border="0" class="imgautosize imgmaxwidth180" src="'.DOL_URL_ROOT.'/theme/dolibarr_preferred_partner_int.png"></a></td>';
     print '<td>'.$langs->trans("DoliPartnersDesc").'</td>';
diff --git a/htdocs/admin/oauth.php b/htdocs/admin/oauth.php
index 34aa49ea2370841054c6368259f95aab488156d3..c1bb5909e15b26c45759155713f1ece9836c773f 100644
--- a/htdocs/admin/oauth.php
+++ b/htdocs/admin/oauth.php
@@ -93,7 +93,6 @@ print $langs->trans("ListOfSupportedOauthProviders").'<br><br>';
 
 print '<table class="noborder" width="100%">';
 
-$var = true;
 $i=0;
 
 foreach ($list as $key)
@@ -116,31 +115,27 @@ foreach ($list as $key)
     if ($supported)
     {
         $redirect_uri=$urlwithroot.'/core/modules/oauth/'.$supportedoauth2array[$key[0]].'_oauthcallback.php';
-        $var = !$var;
-        print '<tr '.$bc[$var].' class="value">';
+        print '<tr class="oddeven value">';
         print '<td>'.$langs->trans("UseTheFollowingUrlAsRedirectURI").'</td>';
         print '<td><input style="width: 80%" type"text" name="uri'.$key[0].'" value="'.$redirect_uri.'">';
         print '</td></tr>';
     }
     else
     {
-        $var = !$var;
-        print '<tr '.$bc[$var].' class="value">';
+        print '<tr class="oddeven value">';
         print '<td>'.$langs->trans("UseTheFollowingUrlAsRedirectURI").'</td>';
         print '<td>'.$langs->trans("FeatureNotYetSupported").'</td>';
         print '</td></tr>';
     }
         
     // Api Id
-    $var = !$var;
-    print '<tr '.$bc[$var].' class="value">';
+    print '<tr class="oddeven value">';
     print '<td><label for="'.$key[1].'">'.$langs->trans($key[1]).'</label></td>';
     print '<td><input type="text" size="100" id="'.$key[1].'" name="'.$key[1].'" value="'.$conf->global->{$key[1]}.'">';
     print '</td></tr>';
 
     // Api Secret
-    $var = !$var;
-    print '<tr '.$bc[$var].' class="value">';
+    print '<tr class="oddeven value">';
     print '<td><label for="'.$key[2].'">'.$langs->trans($key[2]).'</label></td>';
     print '<td><input type="password" size="100" id="'.$key[2].'" name="'.$key[2].'" value="'.$conf->global->{$key[2]}.'">';
     print '</td></tr>';
diff --git a/htdocs/admin/pdf.php b/htdocs/admin/pdf.php
index b0c32a344ff224f1f418c01706bb9f1d9b5c3ab3..6698be8b01f099334e72fbd923d8dbe5166944cd 100644
--- a/htdocs/admin/pdf.php
+++ b/htdocs/admin/pdf.php
@@ -42,15 +42,25 @@ $langs->load("members");
 if (! $user->admin) accessforbidden();
 
 $action = GETPOST('action','alpha');
+$cancel = GETPOST('cancel','alpha');
+
 
 /*
  * Actions
  */
 
+if ($cancel) {
+    $action='';
+}
+
 if ($action == 'update')
 {
 	dolibarr_set_const($db, "MAIN_PDF_FORMAT",    $_POST["MAIN_PDF_FORMAT"],'chaine',0,'',$conf->entity);
-
+	
+	dolibarr_set_const($db, "MAIN_PDF_MARGIN_LEFT",    $_POST["MAIN_PDF_MARGIN_LEFT"],'chaine',0,'',$conf->entity);
+	dolibarr_set_const($db, "MAIN_PDF_MARGIN_RIGHT",   $_POST["MAIN_PDF_MARGIN_RIGHT"],'chaine',0,'',$conf->entity);
+	dolibarr_set_const($db, "MAIN_PDF_MARGIN_TOP",     $_POST["MAIN_PDF_MARGIN_TOP"],'chaine',0,'',$conf->entity);
+	dolibarr_set_const($db, "MAIN_PDF_MARGIN_BOTTOM",  $_POST["MAIN_PDF_MARGIN_BOTTOM"],'chaine',0,'',$conf->entity);
 
     dolibarr_set_const($db, "MAIN_PROFID1_IN_ADDRESS",    $_POST["MAIN_PROFID1_IN_ADDRESS"],'chaine',0,'',$conf->entity);
 	dolibarr_set_const($db, "MAIN_PROFID2_IN_ADDRESS",    $_POST["MAIN_PROFID2_IN_ADDRESS"],'chaine',0,'',$conf->entity);
@@ -133,7 +143,20 @@ if ($action == 'edit')	// Edit
     print $formadmin->select_paper_format($selected,'MAIN_PDF_FORMAT');
     print '</td></tr>';
 
-	print '</table>';
+    print '<tr class="oddeven"><td>'.$langs->trans("MAIN_PDF_MARGIN_LEFT").'</td><td>';
+    print '<input type="text" class="maxwidth50" name="MAIN_PDF_MARGIN_LEFT" value="'.(empty($conf->global->MAIN_PDF_MARGIN_LEFT)?10:$conf->global->MAIN_PDF_MARGIN_LEFT).'">';
+    print '</td></tr>';
+    print '<tr class="oddeven"><td>'.$langs->trans("MAIN_PDF_MARGIN_RIGHT").'</td><td>';
+    print '<input type="text" class="maxwidth50" name="MAIN_PDF_MARGIN_RIGHT" value="'.(empty($conf->global->MAIN_PDF_MARGIN_RIGHT)?10:$conf->global->MAIN_PDF_MARGIN_RIGHT).'">';
+    print '</td></tr>';
+    print '<tr class="oddeven"><td>'.$langs->trans("MAIN_PDF_MARGIN_TOP").'</td><td>';
+    print '<input type="text" class="maxwidth50" name="MAIN_PDF_MARGIN_TOP" value="'.(empty($conf->global->MAIN_PDF_MARGIN_TOP)?10:$conf->global->MAIN_PDF_MARGIN_TOP).'">';
+    print '</td></tr>';
+    print '<tr class="oddeven"><td>'.$langs->trans("MAIN_PDF_MARGIN_BOTTOM").'</td><td>';
+    print '<input type="text" class="maxwidth50" name="MAIN_PDF_MARGIN_BOTTOM" value="'.(empty($conf->global->MAIN_PDF_MARGIN_BOTTOM)?10:$conf->global->MAIN_PDF_MARGIN_BOTTOM).'">';
+    print '</td></tr>';
+    
+    print '</table>';
 
 	print '<br>';
 
@@ -270,7 +293,9 @@ if ($action == 'edit')	// Edit
 	print '</table>';
 
     print '<br><div class="center">';
-    print '<input class="button" type="submit" value="'.$langs->trans("Save").'">';
+    print '<input class="button" type="submit" name="save" value="'.$langs->trans("Save").'">';
+    print ' &nbsp; ';
+    print '<input class="button" type="submit" name="cancel" value="'.$langs->trans("Cancel").'">';
     print '</div>';
 
     print '</form>';
@@ -281,8 +306,9 @@ else	// Show
     $var=true;
 
     // Misc options
-    print load_fiche_titre($langs->trans("DictionaryPaperFormat"),'','').'<br>';
-	$var=true;
+    print load_fiche_titre($langs->trans("DictionaryPaperFormat"),'','');
+	
+    
     print '<table summary="more" class="noborder" width="100%">';
     print '<tr class="liste_titre"><td>'.$langs->trans("Parameter").'</td><td width="200px">'.$langs->trans("Value").'</td></tr>';
 
@@ -314,11 +340,25 @@ else	// Show
     print $pdfformatlabel;
     print '</td></tr>';
 
+    print '<tr class="oddeven"><td>'.$langs->trans("MAIN_PDF_MARGIN_LEFT").'</td><td>';
+    print empty($conf->global->MAIN_PDF_MARGIN_LEFT)?10:$conf->global->MAIN_PDF_MARGIN_LEFT;
+    print '</td></tr>';
+    print '<tr class="oddeven"><td>'.$langs->trans("MAIN_PDF_MARGIN_RIGHT").'</td><td>';
+    print empty($conf->global->MAIN_PDF_MARGIN_RIGHT)?10:$conf->global->MAIN_PDF_MARGIN_RIGHT;
+    print '</td></tr>';
+    print '<tr class="oddeven"><td>'.$langs->trans("MAIN_PDF_MARGIN_TOP").'</td><td>';
+    print empty($conf->global->MAIN_PDF_MARGIN_TOP)?10:$conf->global->MAIN_PDF_MARGIN_TOP;
+    print '</td></tr>';
+    print '<tr class="oddeven"><td>'.$langs->trans("MAIN_PDF_MARGIN_BOTTOM").'</td><td>';
+    print empty($conf->global->MAIN_PDF_MARGIN_BOTTOM)?10:$conf->global->MAIN_PDF_MARGIN_BOTTOM;
+    print '</td></tr>';
+    
+    
 	print '</table>';
 
 	print '<br>';
 
-	print load_fiche_titre($langs->trans("PDFAddressForging"),'','').'<br>';
+	print load_fiche_titre($langs->trans("PDFAddressForging"),'','');
     print '<table class="noborder" width="100%">';
     print '<tr class="liste_titre"><td>'.$langs->trans("Parameter").'</td><td width="200px">'.$langs->trans("Value").'</td></tr>';
 
@@ -405,7 +445,7 @@ else	// Show
     print '<br>';
 
     // Other
-    print load_fiche_titre($langs->trans("Other"),'','').'<br>';
+    print load_fiche_titre($langs->trans("Other"),'','');
 	$var=true;
     print '<table summary="more" class="noborder" width="100%">';
     print '<tr class="liste_titre"><td>'.$langs->trans("Parameter").'</td><td width="200px" colspan="2">'.$langs->trans("Value").'</td></tr>';
diff --git a/htdocs/admin/perms.php b/htdocs/admin/perms.php
index daafab71053ed0b8919b90043c8d4dabd70a30ed..5acbeb2e627389f14dbd6b8259c422a939f8a4e8 100644
--- a/htdocs/admin/perms.php
+++ b/htdocs/admin/perms.php
@@ -140,7 +140,6 @@ if ($result)
 {
     $num	= $db->num_rows($result);
     $i		= 0;
-    $var	= True;
     $oldmod	= "";
 
     while ($i < $num)
@@ -187,8 +186,7 @@ if ($result)
         }
 
         
-        print '<tr '. $bc[$var].'>';
-
+        print '<tr class="oddeven">';
         print '<td>'.img_object('',$picto).' '.$objMod->getName();
         print '<a name="'.$objMod->getName().'">&nbsp;</a>';
 
diff --git a/htdocs/admin/salaries.php b/htdocs/admin/salaries.php
index a04b23ce4fe74afe5969c83fca471029c6fff24b..52470be41068cb0fce940716b443a7fc0553a76b 100644
--- a/htdocs/admin/salaries.php
+++ b/htdocs/admin/salaries.php
@@ -99,7 +99,7 @@ foreach ($list as $key)
 {
 	
 
-	print '<tr '.$bc[$var].' class="value">';
+	print '<tr class="oddeven value">';
 
 	// Param
 	$label = $langs->trans($key);
diff --git a/htdocs/admin/stock.php b/htdocs/admin/stock.php
index 1c5a92fb0e8240ba84f5cb4c4e7cacc79f775d98..050e00e6278a4c59105e481232e9391776634ed4 100644
--- a/htdocs/admin/stock.php
+++ b/htdocs/admin/stock.php
@@ -149,6 +149,7 @@ if (! empty($conf->productbatch->enabled))
 //if (! empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) || ! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT))
 //{
 print info_admin($langs->trans("IfYouUsePointOfSaleCheckModule"));
+print '<br>';
 //}
 
 // Title rule for stock decrease
@@ -432,6 +433,61 @@ if ($virtualdiffersfromphysical)
 }
 
 
+print '<br />';
+if ($conf->global->MAIN_FEATURES_LEVEL >= 2)
+{
+	$var=false;
+	print '<table class="noborder" width="100%">';
+	print '<tr class="liste_titre">';
+	print '<td>'.$langs->trans("Inventory").'</td>'."\n";
+	print '<td align="center" width="20">&nbsp;</td>';
+	print '<td align="center" width="100">&nbsp;</td>'."\n";
+	
+	// Example with a yes / no select
+	$var=!$var;
+	print '<tr '.$bc[$var].'>';
+	print '<td>'.$langs->trans("INVENTORY_DISABLE_VIRTUAL").'</td>';
+	print '<td align="center" width="20">&nbsp;</td>';
+	print '<td align="right" width="300">';
+	print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'">';
+	print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
+	print '<input type="hidden" name="action" value="set_INVENTORY_DISABLE_VIRTUAL">';
+	print $form->selectyesno("INVENTORY_DISABLE_VIRTUAL",$conf->global->INVENTORY_DISABLE_VIRTUAL,1);
+	print '<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
+	print '</form>';
+	print '</td></tr>';
+	
+	// Example with a yes / no select
+	$var=!$var;
+	print '<tr '.$bc[$var].'>';
+	print '<td>'.$langs->trans("INVENTORY_USE_MIN_PA_IF_NO_LAST_PA").'</td>';
+	print '<td align="center" width="20">&nbsp;</td>';
+	print '<td align="right" width="300">';
+	print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'">';
+	print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
+	print '<input type="hidden" name="action" value="set_INVENTORY_USE_MIN_PA_IF_NO_LAST_PA">';
+	print $form->selectyesno("INVENTORY_USE_MIN_PA_IF_NO_LAST_PA",$conf->global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA,1);
+	print '<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
+	print '</form>';
+	print '</td></tr>';
+	
+	// Example with a yes / no select
+	$var=!$var;
+	print '<tr '.$bc[$var].'>';
+	print '<td>'.$langs->trans("INVENTORY_USE_INVENTORY_DATE_FROM_DATEMVT").'</td>';
+	print '<td align="center" width="20">&nbsp;</td>';
+	print '<td align="right" width="300">';
+	print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'">';
+	print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
+	print '<input type="hidden" name="action" value="set_INVENTORY_USE_INVENTORY_DATE_FROM_DATEMVT">';
+	print $form->selectyesno("INVENTORY_USE_INVENTORY_DATE_FROM_DATEMVT",$conf->global->INVENTORY_USE_INVENTORY_DATE_FROM_DATEMVT,1);
+	print '<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
+	print '</form>';
+	print '</td></tr>';
+	
+	print '</table>';
+}
+
 $var=true;
 print '<table class="noborder" width="100%">';
 
@@ -508,6 +564,7 @@ if ($conf->global->PRODUIT_SOUSPRODUITS)
 
 print '</table>';
 
+
 llxFooter();
 
 $db->close();
diff --git a/htdocs/admin/supplier_invoice.php b/htdocs/admin/supplier_invoice.php
index 19f0e6fc8e2a4e934e545d10b1a36260c8f69506..de128184d18d3644ec721ae31fed778e79949f94 100644
--- a/htdocs/admin/supplier_invoice.php
+++ b/htdocs/admin/supplier_invoice.php
@@ -5,7 +5,7 @@
  * Copyright (C) 2004      Sebastien Di Cintio     <sdicintio@ressource-toi.org>
  * Copyright (C) 2004      Benoit Mortier          <benoit.mortier@opensides.be>
  * Copyright (C) 2010-2013 Juanjo Menent           <jmenent@2byte.es>
- * Copyright (C) 2011-2015 Philippe Grand          <philippe.grand@atoo-net.com>
+ * Copyright (C) 2011-2017 Philippe Grand          <philippe.grand@atoo-net.com>
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -205,7 +205,7 @@ print "<br>";
 
 $head = supplierorder_admin_prepare_head();
 
-dol_fiche_head($head, 'invoice', $langs->trans("Suppliers"), 0, 'company');
+dol_fiche_head($head, 'invoice', $langs->trans("Suppliers"), -1, 'company');
 
 
 // Supplier invoice numbering module
@@ -361,7 +361,6 @@ foreach ($dirmodels as $reldir)
 
     if (is_dir($dir))
     {
-        $var=true;
 
         $handle=opendir($dir);
 
@@ -379,7 +378,7 @@ foreach ($dirmodels as $reldir)
 	                $module = new $classname($db, new FactureFournisseur($db));
 
                     
-                    print "<tr ".$bc[$var].">\n";
+                    print "<tr class=\"oddeven\">\n";
                     print "<td>";
 	                print (empty($module->name)?$name:$module->name);
 	                print "</td>\n";
diff --git a/htdocs/admin/supplier_order.php b/htdocs/admin/supplier_order.php
index a30e7de2654af4a7a70fe57af10d77c71853d984..030a507ce20894855e01fffcd390d828505157e9 100644
--- a/htdocs/admin/supplier_order.php
+++ b/htdocs/admin/supplier_order.php
@@ -5,7 +5,7 @@
  * Copyright (C) 2004      Sebastien Di Cintio     <sdicintio@ressource-toi.org>
  * Copyright (C) 2004      Benoit Mortier          <benoit.mortier@opensides.be>
  * Copyright (C) 2010-2013 Juanjo Menent           <jmenent@2byte.es>
- * Copyright (C) 2011-2015 Philippe Grand          <philippe.grand@atoo-net.com>
+ * Copyright (C) 2011-2017 Philippe Grand          <philippe.grand@atoo-net.com>
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -234,7 +234,7 @@ print "<br>";
 
 $head = supplierorder_admin_prepare_head();
 
-dol_fiche_head($head, 'order', $langs->trans("Suppliers"), 0, 'company');
+dol_fiche_head($head, 'order', $langs->trans("Suppliers"), -1, 'company');
 
 
 // Supplier order numbering module
@@ -382,7 +382,6 @@ print '</tr>'."\n";
 
 clearstatcache();
 
-$var=true;
 foreach ($dirmodels as $reldir)
 {
 	$dir = dol_buildpath($reldir."core/modules/supplier_order/pdf/");
@@ -403,7 +402,7 @@ foreach ($dirmodels as $reldir)
 	                $module = new $classname($db, new CommandeFournisseur($db));
 
                     
-                    print "<tr ".$bc[$var].">\n";
+                    print "<tr class=\"oddeven\">\n";
                     print "<td>";
 	                print (empty($module->name)?$name:$module->name);
 	                print "</td>\n";
diff --git a/htdocs/admin/supplier_payment.php b/htdocs/admin/supplier_payment.php
index 40caa94c8a828c2d4adba0097505bf6095e8c33c..adaa114b1ca2d77830ba50cc174d2d70ae38145a 100644
--- a/htdocs/admin/supplier_payment.php
+++ b/htdocs/admin/supplier_payment.php
@@ -65,7 +65,7 @@ if ($action == 'updateMask')
     }
 }else  if ($action == 'setmod')
 {
-    dolibarr_set_const($db, "SUPPLIER_PAYMENT_ADDON",$value,'chaine',0,'',$conf->entity);
+    dolibarr_set_const($db, "SUPPLIER_PAYMENT_ADDON", $value, 'chaine', 0, '', $conf->entity);
 }
 
 // define constants for models generator that need parameters
@@ -138,7 +138,7 @@ else if ($action == 'specimen')
 	$dirmodels=array_merge(array('/'),(array) $conf->modules_parts['models']);
 	foreach($dirmodels as $reldir)
 	{
-	    $file=dol_buildpath($reldir."core/modules/supplier_payment/pdf/pdf_".$modele.".modules.php",0);
+	    $file=dol_buildpath($reldir."core/modules/supplier_payment/doc/pdf_".$modele.".modules.php",0);
     	if (file_exists($file))
     	{
     		$filefound=1;
@@ -188,7 +188,7 @@ print load_fiche_titre($langs->trans("SupplierPaymentSetup"),$linkback,'title_se
 print "<br>";
 
 $head = supplierorder_admin_prepare_head();
-dol_fiche_head($head, 'supplierpayment', $langs->trans("Suppliers"), 0, 'company');
+dol_fiche_head($head, 'supplierpayment', $langs->trans("Suppliers"), -1, 'company');
 
 /*
  *  Numbering module
@@ -198,12 +198,6 @@ if (empty($conf->global->SUPPLIER_PAYMENT_ADDON)) $conf->global->SUPPLIER_PAYMEN
     
 print load_fiche_titre($langs->trans("PaymentsNumberingModule"), '', '');
 
-/*
- *  Document templates generators
- */
-print '<br>';
-print load_fiche_titre($langs->trans("BillsPDFModules"),'','');
-
 // Load array def with activated templates
 $def = array();
 $sql = "SELECT nom";
@@ -349,6 +343,12 @@ foreach ($dirmodels as $reldir)
 print '</table>';
 
 
+/*
+ *  Document templates generators
+ */
+print '<br>';
+print load_fiche_titre($langs->trans("PaymentsPDFModules"),'','');
+
 print '<table class="noborder" width="100%">'."\n";
 print '<tr class="liste_titre">'."\n";
 print '<td width="100">'.$langs->trans("Name").'</td>'."\n";
@@ -363,11 +363,10 @@ clearstatcache();
 
 foreach ($dirmodels as $reldir)
 {
-	$dir = dol_buildpath($reldir."core/modules/supplier_payment/pdf/");
+	$dir = dol_buildpath($reldir."core/modules/supplier_payment/doc/");
 
     if (is_dir($dir))
     {
-        $var=true;
 
         $handle=opendir($dir);
 
@@ -385,7 +384,7 @@ foreach ($dirmodels as $reldir)
 	                $module = new $classname($db, new PaiementFourn($db));
 
                     
-                    print "<tr ".$bc[$var].">\n";
+                    print "<tr class=\"oddeven\">\n";
                     print "<td>";
 	                print (empty($module->name)?$name:$module->name);
 	                print "</td>\n";
@@ -441,8 +440,6 @@ foreach ($dirmodels as $reldir)
                     $htmltooltip.='<br>'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur;
                     $htmltooltip.='<br><br><u>'.$langs->trans("FeaturesSupported").':</u>';
                     $htmltooltip.='<br>'.$langs->trans("Logo").': '.yn($module->option_logo,1,1);
-                    $htmltooltip.='<br>'.$langs->trans("PaymentMode").': '.yn($module->option_modereg,1,1);
-                    $htmltooltip.='<br>'.$langs->trans("PaymentConditions").': '.yn($module->option_condreg,1,1);
                     print '<td align="center">';
                     print $form->textwithpicto('',$htmltooltip,1,0);
                     print '</td>';
@@ -459,7 +456,7 @@ foreach ($dirmodels as $reldir)
     }
 }
 
-print '</table><br>';
+print '</table>';
 
 dol_fiche_end();
 
diff --git a/htdocs/admin/supplierinvoice_extrafields.php b/htdocs/admin/supplierinvoice_extrafields.php
index 701362e38f4a8ef8b208b5c7e8f9ec10f91604b3..4e0bd1d0dd2a861fa63d891cac2f6e6925dcd840 100644
--- a/htdocs/admin/supplierinvoice_extrafields.php
+++ b/htdocs/admin/supplierinvoice_extrafields.php
@@ -79,7 +79,7 @@ print "<br>\n";
 
 $head = supplierorder_admin_prepare_head();
 
-dol_fiche_head($head, 'supplierinvoice', $langs->trans("Suppliers"), 0, 'company');
+dol_fiche_head($head, 'supplierinvoice', $langs->trans("Suppliers"), -1, 'company');
 
 require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_view.tpl.php';
 
diff --git a/htdocs/admin/supplierinvoicedet_extrafields.php b/htdocs/admin/supplierinvoicedet_extrafields.php
index e741eb6cd75abe3dc88fb120cd137a98bf1e3327..26b3b42e9704cd3d511bf5e6e446ceea6d220f0f 100644
--- a/htdocs/admin/supplierinvoicedet_extrafields.php
+++ b/htdocs/admin/supplierinvoicedet_extrafields.php
@@ -79,7 +79,7 @@ print "<br>\n";
 
 $head = supplierorder_admin_prepare_head();
 
-dol_fiche_head($head, 'supplierinvoicedet', $langs->trans("Suppliers"), 0, 'company');
+dol_fiche_head($head, 'supplierinvoicedet', $langs->trans("Suppliers"), -1, 'company');
 
 require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_view.tpl.php';
 
diff --git a/htdocs/admin/supplierorder_extrafields.php b/htdocs/admin/supplierorder_extrafields.php
index 00550995d19ac96ddae75ecabc859f2b9d7a0462..bcad8121afcf5815fff0ecd247c269976f4ddbd8 100644
--- a/htdocs/admin/supplierorder_extrafields.php
+++ b/htdocs/admin/supplierorder_extrafields.php
@@ -75,7 +75,7 @@ print "<br>\n";
 
 $head = supplierorder_admin_prepare_head();
 
-dol_fiche_head($head, 'supplierorder', $langs->trans("Suppliers"), 0, 'company');
+dol_fiche_head($head, 'supplierorder', $langs->trans("Suppliers"), -1, 'company');
 
 require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_view.tpl.php';
 
diff --git a/htdocs/admin/supplierorderdet_extrafields.php b/htdocs/admin/supplierorderdet_extrafields.php
index f83ad1348fcd87819b881fff720013c438dca764..97d505144bb3a4317096f7b4d40659e8725ed171 100644
--- a/htdocs/admin/supplierorderdet_extrafields.php
+++ b/htdocs/admin/supplierorderdet_extrafields.php
@@ -76,7 +76,7 @@ print "<br>\n";
 
 $head = supplierorder_admin_prepare_head();
 
-dol_fiche_head($head, 'supplierorderdet', $langs->trans("Suppliers"), 0, 'company');
+dol_fiche_head($head, 'supplierorderdet', $langs->trans("Suppliers"), -1, 'company');
 
 require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_view.tpl.php';
 
diff --git a/htdocs/admin/syslog.php b/htdocs/admin/syslog.php
index 71d06ae8e6487f47c78f2a0ef256e8fc5ee94d76..03a1872c90c8c8ed86a5425ed10f5028099bcd2c 100644
--- a/htdocs/admin/syslog.php
+++ b/htdocs/admin/syslog.php
@@ -40,7 +40,7 @@ $action = GETPOST("action");
 $syslogModules = array();
 $activeModules = array();
 
-if (defined('SYSLOG_HANDLERS')) $activeModules = json_decode(constant('SYSLOG_HANDLERS'));
+if (! empty($conf->global->SYSLOG_HANDLERS)) $activeModules = json_decode($conf->global->SYSLOG_HANDLERS);
 
 $dirsyslogs = array_merge(array('/core/modules/syslog/'), $conf->modules_parts['syslog']);
 foreach ($dirsyslogs as $reldir) {
@@ -88,7 +88,8 @@ if ($action == 'set')
 
 	$newActiveModules = array();
 	$selectedModules = (isset($_POST['SYSLOG_HANDLERS']) ? $_POST['SYSLOG_HANDLERS'] : array());
-	//var_dump($selectedModules);
+	
+	// Save options of handler
 	foreach ($syslogModules as $syslogHandler)
 	{
 		if (in_array($syslogHandler, $syslogModules))
@@ -101,7 +102,7 @@ if ($action == 'set')
 				if (isset($_POST[$option['constant']]))
 				{
 					$_POST[$option['constant']] = trim($_POST[$option['constant']]);
-					dolibarr_del_const($db, $option['constant'], 0);
+					dolibarr_del_const($db, $option['constant'], -1);
 					dolibarr_set_const($db, $option['constant'], $_POST[$option['constant']], 'chaine',0, '', 0);
 				}
 			}
@@ -109,7 +110,9 @@ if ($action == 'set')
 	}
 
 	$activeModules = $newActiveModules;
-	dolibarr_set_const($db, 'SYSLOG_HANDLERS', json_encode($activeModules), 'chaine',0,'',0);
+
+    dolibarr_del_const($db, 'SYSLOG_HANDLERS', -1);  // To be sure ther is not a setup into another entity	
+    dolibarr_set_const($db, 'SYSLOG_HANDLERS', json_encode($activeModules), 'chaine',0,'',0);
 
 	// Check configuration
 	foreach ($activeModules as $modulename) {
@@ -194,7 +197,6 @@ print '<tr class="liste_titre">';
 print '<td>'.$langs->trans("Type").'</td><td>'.$langs->trans("Value").'</td>';
 print '<td align="right" colspan="2"><input type="submit" class="button" '.$option.' value="'.$langs->trans("Modify").'"></td>';
 print "</tr>\n";
-$var=true;
 
 foreach ($syslogModules as $moduleName)
 {
@@ -207,7 +209,7 @@ foreach ($syslogModules as $moduleName)
 	
 	print '<tr class="oddeven">';
 	print '<td width="140">';
-	print '<input '.$bc[$var].' type="checkbox" name="SYSLOG_HANDLERS[]" value="'.$moduleName.'" '.(in_array($moduleName, $activeModules) ? 'checked' : '').($moduleactive <= 0 ? 'disabled' : '').'> ';
+	print '<input class="oddeven" type="checkbox" name="SYSLOG_HANDLERS[]" value="'.$moduleName.'" '.(in_array($moduleName, $activeModules) ? 'checked' : '').($moduleactive <= 0 ? 'disabled' : '').'> ';
 	print $module->getName();
 	print '</td>';
 
@@ -217,8 +219,12 @@ foreach ($syslogModules as $moduleName)
 	{
 		foreach ($setuparray as $option)
 		{
-			if (isset($_POST[$option['constant']])) $value=$_POST[$option['constant']];
-			else if (defined($option['constant'])) $value = constant($option['constant']);
+		    $tmpoption=$option['constant'];
+		    if (! empty($tmpoption))
+		    {
+    			if (isset($_POST[$tmpoption])) $value=$_POST[$tmpoption];
+    			else if (! empty($conf->global->$tmpoption)) $value = $conf->global->$tmpoption;
+		    }
 			else $value = (isset($option['default']) ? $option['default'] : '');
 
 			print $option['name'].': <input type="text" class="flat" name="'.$option['constant'].'" value="'.$value.'"'.(isset($option['attr']) ? ' '.$option['attr'] : '').'>';
diff --git a/htdocs/admin/taxes.php b/htdocs/admin/taxes.php
index 788d8604584119dec22cc9c5e637ab6a353383f6..dbdce59c3c57999b98ea3091176fa4f90ac4c46f 100644
--- a/htdocs/admin/taxes.php
+++ b/htdocs/admin/taxes.php
@@ -136,10 +136,10 @@ else
     print '<tr class="liste_titre">';
     print '<td colspan="2">'.$langs->trans('OptionVatMode').'</td><td>'.$langs->trans('Description').'</td>';
     print "</tr>\n";
-    print '<tr '.$bc[false].'><td width="200"><input type="radio" name="tax_mode" value="0"'.($tax_mode != 1 ? ' checked' : '').'> '.$langs->trans('OptionVATDefault').'</td>';
+    print '<tr class="oddeven"><td width="200"><input type="radio" name="tax_mode" value="0"'.($tax_mode != 1 ? ' checked' : '').'> '.$langs->trans('OptionVATDefault').'</td>';
     print '<td colspan="2">'.nl2br($langs->trans('OptionVatDefaultDesc'));
     print "</td></tr>\n";
-    print '<tr '.$bc[true].'><td width="200"><input type="radio" name="tax_mode" value="1"'.($tax_mode == 1 ? ' checked' : '').'> '.$langs->trans('OptionVATDebitOption').'</td>';
+    print '<tr class="oddeven"><td width="200"><input type="radio" name="tax_mode" value="1"'.($tax_mode == 1 ? ' checked' : '').'> '.$langs->trans('OptionVATDebitOption').'</td>';
     print '<td colspan="2">'.nl2br($langs->trans('OptionVatDebitOptionDesc'))."</td></tr>\n";
 
     print "</table>\n";
@@ -152,7 +152,7 @@ else
     print '<tr class="liste_titre"><td>&nbsp;</td><td>'.$langs->trans("Buy").'</td><td>'.$langs->trans("Sell").'</td></tr>';
 
     // Products
-    print '<tr '.$bc[false].'><td>'.$langs->trans("Product").'</td>';
+    print '<tr class="oddeven"><td>'.$langs->trans("Product").'</td>';
     print '<td>';
     print $langs->trans("OnDelivery");
     print ' ('.$langs->trans("SupposedToBeInvoiceDate").')';
@@ -163,7 +163,7 @@ else
     print '</td></tr>';
 
     // Services
-    print '<tr '.$bc[true].'><td>'.$langs->trans("Services").'</td>';
+    print '<tr class="oddeven"><td>'.$langs->trans("Services").'</td>';
     print '<td>';
     if ($tax_mode == 0)
     {
@@ -206,7 +206,7 @@ foreach ($list as $key)
 {
 	
 
-	print '<tr '.$bc[$var].' class="value">';
+	print '<tr class="oddeven value">';
 
 	// Param
 	$label = $langs->trans($key); 
diff --git a/htdocs/admin/user.php b/htdocs/admin/user.php
index 42feea8f8ecf4661b326bfd640cb3158d3e993d9..0c7574b7ec4da40ede76b99aed6e3736987a8a91 100644
--- a/htdocs/admin/user.php
+++ b/htdocs/admin/user.php
@@ -167,7 +167,7 @@ print load_fiche_titre($langs->trans("UsersSetup"),$linkback,'title_setup');
 
 $head=user_admin_prepare_head();
 
-dol_fiche_head($head,'card', $langs->trans("MenuUsersAndGroups"), 0, 'user');
+dol_fiche_head($head,'card', $langs->trans("MenuUsersAndGroups"), -1, 'user');
 
 print '<table class="noborder" width="100%">';
 print '<tr class="liste_titre">';
@@ -205,7 +205,7 @@ print '</td></tr>';
 
 print '</table>';
 
-
+print '<br>';
 
 $dirmodels=array_merge(array('/'),(array) $conf->modules_parts['models']);
 
diff --git a/htdocs/admin/usergroup.php b/htdocs/admin/usergroup.php
index db5ef3cbf59c53a9e3d4ee14aeb2b0fec8364ea6..4642e6d3183e3069620f87ef58fb6212c79e27ae 100644
--- a/htdocs/admin/usergroup.php
+++ b/htdocs/admin/usergroup.php
@@ -151,7 +151,7 @@ print load_fiche_titre($langs->trans("UsersSetup"),$linkback,'title_setup');
 
 $head=user_admin_prepare_head();
 
-dol_fiche_head($head,'usergroupcard', $langs->trans("MenuUsersAndGroups"), 0, 'user');
+dol_fiche_head($head,'usergroupcard', $langs->trans("MenuUsersAndGroups"), -1, 'user');
 
 
 $dirmodels=array_merge(array('/'),(array) $conf->modules_parts['models']);
diff --git a/htdocs/admin/websites.php b/htdocs/admin/websites.php
index 06e9a7b93a43f6f50ea17bf9a33a7a528ef8cd88..9aecc4dfb0ad74edde3b55e8a6185802c369b070 100644
--- a/htdocs/admin/websites.php
+++ b/htdocs/admin/websites.php
@@ -441,7 +441,6 @@ if ($id)
     {
         $num = $db->num_rows($resql);
         $i = 0;
-        $var=true;
         if ($num)
         {
             print '<br>';
@@ -499,7 +498,6 @@ if ($id)
             // Lines with values
             while ($i < $num)
             {
-                $var = ! $var;
 
                 $obj = $db->fetch_object($resql);
                 //print_r($obj);
diff --git a/htdocs/admin/workflow.php b/htdocs/admin/workflow.php
index d9595cd7fb08f5e2fa8b3524d90127c5cb16187a..af104fd4bfe2e34b09806d0248b9e457aebfc172 100644
--- a/htdocs/admin/workflow.php
+++ b/htdocs/admin/workflow.php
@@ -120,8 +120,7 @@ foreach($workflowcodes as $key => $params)
 		$oldfamily = $family;
    	}
 
-   	$var = !$var;
-   	print "<tr ".$bc[$var].">\n";
+   	print "<tr class=\"oddeven\">\n";
    	print "<td>".img_object('', $picto).$langs->trans('desc'.$key);
    	if (! empty($params['warning']))
    	{
diff --git a/htdocs/api/class/api.class.php b/htdocs/api/class/api.class.php
index 7aef2671c8db58795d70410346d4a36c136b0ea1..9228c71ccbf54883b3b8696b3003b1c7e0781b16 100644
--- a/htdocs/api/class/api.class.php
+++ b/htdocs/api/class/api.class.php
@@ -90,6 +90,8 @@ class DolibarrApi
         // Remove linkedObjects. We should already have linkedObjectIds that avoid huge responses
         unset($object->linkedObjects);
         
+        unset($object->fields);
+        
         unset($object->oldline);
         
         unset($object->error);
diff --git a/htdocs/api/class/api_login.class.php b/htdocs/api/class/api_login.class.php
index 704ec1b68746c1a34bdfc22f1940d12cdab6fad4..76a9befebc997a9e00003f1dc56db824e479638b 100644
--- a/htdocs/api/class/api_login.class.php
+++ b/htdocs/api/class/api_login.class.php
@@ -102,7 +102,7 @@ class Login
 			'success' => array(
 				'code' => 200,
 				'token' => $token,
-				'message' => 'Welcome ' . $login.($reset?' - Token is new':' - This is your token (generated by a previous call)')
+				'message' => 'Welcome ' . $login.($reset?' - Token is new':' - This is your token (generated by a previous call). You can use it to make any REST API call, or enter it into the DOLAPIKEY field to use the Dolibarr API explorer.')
 			)
 		);
 	}
diff --git a/htdocs/bookmarks/bookmarks.lib.php b/htdocs/bookmarks/bookmarks.lib.php
index d84713d1e628d2e7de70ffce3707b6a472dcef18..c1882ce4bf9ce6f6c31e9bbaee19ff09ed93e92a 100644
--- a/htdocs/bookmarks/bookmarks.lib.php
+++ b/htdocs/bookmarks/bookmarks.lib.php
@@ -62,14 +62,15 @@ function printBookmarksList($aDb, $aLangs)
     */
 	$ret.= '<div class="menu_top"></div>'."\n";
 
-	$ret.= '<form id="actionbookmark" name="actionbookmark" method="POST" action="">';
+	$ret.= '<!-- form with POST method by default --><form id="actionbookmark" name="actionbookmark" method="POST" action="">';
 	$ret.= '<select name="bookmark" id="boxbookmark" class="flat boxcombo vmenusearchselectcombo">';
 	$ret.= '<option hidden value="listbookmarks" class="optiongrey" selected rel="'.DOL_URL_ROOT.'/bookmarks/list.php">'.$langs->trans('Bookmarks').'</option>';
-    $ret.= '<option value="listbookmark" class="optionblue" rel="'.dol_escape_js(DOL_URL_ROOT.'/bookmarks/list.php').'">'.dol_escape_htmltag($user->rights->bookmark->creer ? $langs->trans('EditBookmarks') : $langs->trans('ListOfBookmarks')).'...</option>';
+    $ret.= '<option value="listbookmark" class="optionblue" rel="'.dol_escape_htmltag(DOL_URL_ROOT.'/bookmarks/list.php').'">'.dol_escape_htmltag($user->rights->bookmark->creer ? $langs->trans('EditBookmarks') : $langs->trans('ListOfBookmarks')).'...</option>';
+	// Url to go on create new bookmark page
 	if ($user->rights->bookmark->creer)
 	{
     	$urltoadd=DOL_URL_ROOT.'/bookmarks/card.php?action=create&amp;urlsource='.urlencode($url).'&amp;url='.urlencode($url);
-    	$ret.= '<option value="newbookmark" class="optionblue" rel="'.dol_escape_js($urltoadd).'">'.dol_escape_htmltag($langs->trans('AddThisPageToBookmarks')).'...</option>';
+    	$ret.= '<option value="newbookmark" class="optionblue" rel="'.dol_escape_htmltag($urltoadd).'">'.dol_escape_htmltag($langs->trans('AddThisPageToBookmarks')).'...</option>';
 	}
 	// Menu with all bookmarks
 	if (! empty($conf->global->BOOKMARKS_SHOW_IN_MENU))
@@ -84,7 +85,7 @@ function printBookmarksList($aDb, $aLangs)
 			while ($i < $conf->global->BOOKMARKS_SHOW_IN_MENU && $obj = $db->fetch_object($resql))
 			{
 				//$ret.='<div class="menu_contenu">';
-			    $ret.='<option name="bookmark'.$obj->rowid.'" value="'.$obj->rowid.'" '.($obj->target == 1?' target="_blank"':'').' rel="'.dol_escape_js($obj->url).'">'.img_picto('','object_bookmark').' '.$obj->title.'</option>';
+			    $ret.='<option name="bookmark'.$obj->rowid.'" value="'.$obj->rowid.'" '.($obj->target == 1?' target="_blank"':'').' rel="'.dol_escape_htmltag($obj->url).'">'.img_picto('','object_bookmark').' '.$obj->title.'</option>';
 				/*$ret.='<a class="vsmenu" title="'.$obj->title.'" href="'.$obj->url.'"'.($obj->target == 1?' target="_blank"':'').'>';
 				if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) $ret.=' '.img_object('','bookmark').' ';
 				$ret.= dol_trunc($obj->title, 20).'</a><br>';*/
@@ -109,9 +110,19 @@ function printBookmarksList($aDb, $aLangs)
 	            var urlselected = jQuery("#boxbookmark option:selected").attr("rel");
 	            var urltarget = jQuery("#boxbookmark option:selected").attr("target");
 	            if (! urltarget) { urltarget=""; }
-	            console.log("We change select bookmark. We choose "+urlselected+" with target "+urltarget);
                 jQuery("form#actionbookmark").attr("target",urltarget);
 	            jQuery("form#actionbookmark").attr("action",urlselected);
+	    
+	            console.log("We change select bookmark. We choose urlselected="+urlselected+" with target="+urltarget);
+	            
+	            // Method is POST for internal link, GET for external
+	            if (urlselected.startsWith(\'http\'))
+	            {
+	                var newmethod=\'GET\';
+	                jQuery("form#actionbookmark").attr("method",newmethod);
+	                console.log("We change method to newmethod="+newmethod);
+	            }
+	    
 	            jQuery("#actionbookmark").submit();
 	       });';
 	$ret.='})</script>';
diff --git a/htdocs/categories/index.php b/htdocs/categories/index.php
index d44407324c0c880c163d796eadaf25fc0aa58f39..ca2b7b5c76ff42eb7c8c17fc271d07b922d26726 100644
--- a/htdocs/categories/index.php
+++ b/htdocs/categories/index.php
@@ -125,7 +125,7 @@ if ($catname || $id > 0)
 		print '</span>';
 		print "</td>\n";
 		print "\t\t<td>";
-		print $cat->description;
+		print dolGetFirstLineOfText($cat->description);
 		print "</td>\n";
 		print "\t</tr>\n";
 	}
@@ -162,7 +162,7 @@ foreach($fulltree as $key => $val)
 	'rowid'=>$val['rowid'],
 	'fk_menu'=>$val['fk_parent'],
 	'entry'=>'<table class="nobordernopadding centpercent"><tr><td><span class="noborderoncategories" '.($categstatic->color?' style="background: #'.$categstatic->color.';"':' style="background: #aaa"').'>'.$li.'</span></td>'.
-	'<td width="50%">'.dolGetFirstLineOfText($desc).'</td>'.
+	//'<td width="50%">'.dolGetFirstLineOfText($desc).'</td>'.
 	'<td align="right" width="20px;"><a href="'.DOL_URL_ROOT.'/categories/viewcat.php?id='.$val['id'].'&type='.$type.'">'.img_view().'</a></td>'.
 	'</tr></table>'
 	);
@@ -181,13 +181,13 @@ $nbofentries=(count($data) - 1);
 
 if ($nbofentries > 0)
 {
-	print '<tr '.$bc[0].'><td colspan="3">';
+	print '<tr class="pair"><td colspan="3">';
 	tree_recur($data,$data[0],0);
 	print '</td></tr>';
 }
 else
 {
-	print '<tr '.$bc[0].'>';
+	print '<tr class="pair">';
 	print '<td colspan="3"><table class="nobordernopadding"><tr class="nobordernopadding"><td>'.img_picto_common('','treemenu/branchbottom.gif').'</td>';
 	print '<td valign="middle">';
 	print $langs->trans("NoCategoryYet");
diff --git a/htdocs/comm/action/card.php b/htdocs/comm/action/card.php
index fc4fc21897129ea6f486b39449be42d359d7fac1..30b13bc30070aca77fa335bd282b43954cca0332 100644
--- a/htdocs/comm/action/card.php
+++ b/htdocs/comm/action/card.php
@@ -337,7 +337,7 @@ if ($action == 'add')
 				unset($_SESSION['assignedtouser']);
 
 				$moreparam='';
-				if ($user->id != $object->userownerid) $moreparam="usertodo=-1";	// We force to remove filter so created record is visible when going back to per user view.
+				if ($user->id != $object->userownerid) $moreparam="filtert=-1";	// We force to remove filter so created record is visible when going back to per user view.
 
 				$db->commit();
 				if (! empty($backtopage))
@@ -706,7 +706,7 @@ if ($action == 'create')
 		if (GETPOST('complete') == '0' || GETPOST("afaire") == 1) $percent='0';
 		else if (GETPOST('complete') == 100 || GETPOST("afaire") == 2) $percent=100;
 	}
-	$formactions->form_select_status_action('formaction',$percent,1,'complete');
+	$formactions->form_select_status_action('formaction', $percent, 1, 'complete', 0, 0, 'maxwidth200');
 	print '</td></tr>';
 
     // Location
@@ -1428,7 +1428,7 @@ if ($id > 0)
 				} else {
 					$value = $object->array_options["options_" . $key];
 				}
-				print '<tr><td width="30%">'.$label.'</td><td>';
+				print '<tr><td class="titlefield">'.$label.'</td><td>';
 				print $extrafields->showOutputField($key,$value);
 				print "</td></tr>\n";
 			}
@@ -1491,7 +1491,7 @@ if ($id > 0)
 	{
 		if (empty($conf->global->AGENDA_DISABLE_BUILDDOC))
 		{
-			print '<div style="clear:both;">&nbsp;<br><br></div><div class="fichecenter"><div class="fichehalfleft">';
+			print '<div style="clear:both;"></div><div class="fichecenter"><div class="fichehalfleft">';
             print '<a name="builddoc"></a>'; // ancre
 
             /*
@@ -1512,8 +1512,6 @@ if ($id > 0)
 
 
 			print '</div></div></div>';
-
-            print '<div style="clear:both;">&nbsp;</div>';
 	    }
 	}
 }
diff --git a/htdocs/comm/action/index.php b/htdocs/comm/action/index.php
index d365acef38b18b593100134d46bae2fb1623f2e5..47ef8093c1a399b0ffaa5a1f1ae4935025982b66 100644
--- a/htdocs/comm/action/index.php
+++ b/htdocs/comm/action/index.php
@@ -43,8 +43,8 @@ if (! isset($conf->global->AGENDA_MAX_EVENTS_DAY_VIEW)) $conf->global->AGENDA_MA
 if (empty($conf->global->AGENDA_EXT_NB)) $conf->global->AGENDA_EXT_NB=5;
 $MAXAGENDA=$conf->global->AGENDA_EXT_NB;
 
-$filter=GETPOST("filter",'',3);
-$filtert = GETPOST("usertodo","int",3)?GETPOST("usertodo","int",3):GETPOST("filtert","int",3);
+$filter = GETPOST("filter",'',3);
+$filtert = GETPOST("filtert","int",3);
 $usergroup = GETPOST("usergroup","int",3);
 $showbirthday = empty($conf->use_javascript_ajax)?GETPOST("showbirthday","int"):1;
 
@@ -1155,21 +1155,6 @@ else    // View by day
     echo '</table>';
 }
 
-
-/* TODO Export
- print '
-<a href="" id="actionagenda_ical_link"><img src="'.DOL_URL_ROOT.'/theme/common/ical.gif" border="0"/></a>
-<a href="" id="actionagenda_vcal_link"><img src="'.DOL_URL_ROOT.'/theme/common/vcal.gif" border="0"/></a>
-<a href="" id="actionagenda_rss_link"><img src="'.DOL_URL_ROOT.'/theme/common/rss.gif"  border="0"/></a>
-
-<script>
-$("#actionagenda_rss_link").attr("href","/public/agenda/agendaexport.php?format=rss&type=ActionAgenda&exportkey=dolibarr&token="+getToken()+"&status="+getStatus()+"&userasked="+getUserasked()+"&usertodo="+getUsertodo()+"&userdone="+getUserdone()+"&year="+getYear()+"&month="+getMonth()+"&day="+getDay()+"&showbirthday="+getShowbirthday()+"&action="+getAction()+"&projectid="+getProjectid()+"");
-$("#actionagenda_ical_link").attr("href","/public/agenda/agendaexport.php?format=ical&type=ActionAgenda&exportkey=dolibarr&token="+getToken()+"&status="+getStatus()+"&userasked="+getUserasked()+"&usertodo="+getUsertodo()+"&userdone="+getUserdone()+"&year="+getYear()+"&month="+getMonth()+"&day="+getDay()+"&showbirthday="+getShowbirthday()+"&action="+getAction()+"&projectid="+getProjectid()+"");
-$("#actionagenda_vcal_link").attr("href","/public/agenda/agendaexport.php?format=vcal&type=ActionAgenda&exportkey=dolibarr&token="+getToken()+"&status="+getStatus()+"&userasked="+getUserasked()+"&usertodo="+getUsertodo()+"&userdone="+getUserdone()+"&year="+getYear()+"&month="+getMonth()+"&day="+getDay()+"&showbirthday="+getShowbirthday()+"&action="+getAction()+"&projectid="+getProjectid()+"");
-</script>
-';
-*/
-
 llxFooter();
 
 $db->close();
diff --git a/htdocs/comm/action/listactions.php b/htdocs/comm/action/listactions.php
index 8b1dc424239dd727103d9a2a6d50153930acac99..3e6224e0c41063cc12868c5cc65aac460250e056 100644
--- a/htdocs/comm/action/listactions.php
+++ b/htdocs/comm/action/listactions.php
@@ -64,8 +64,8 @@ $dateend=dol_mktime(0, 0, 0, GETPOST('dateendmonth'), GETPOST('dateendday'), GET
 if ($status == ''   && ! isset($_GET['status']) && ! isset($_POST['status'])) $status=(empty($conf->global->AGENDA_DEFAULT_FILTER_STATUS)?'':$conf->global->AGENDA_DEFAULT_FILTER_STATUS);
 if (empty($action) && ! isset($_GET['action']) && ! isset($_POST['action'])) $action=(empty($conf->global->AGENDA_DEFAULT_VIEW)?'show_month':$conf->global->AGENDA_DEFAULT_VIEW);
 
-$filter=GETPOST("filter",'',3);
-$filtert = GETPOST("usertodo","int",3)?GETPOST("usertodo","int",3):GETPOST("filtert","int",3);
+$filter = GETPOST("filter",'',3);
+$filtert = GETPOST("filtert","int",3);
 $usergroup = GETPOST("usergroup","int",3);
 $showbirthday = empty($conf->use_javascript_ajax)?GETPOST("showbirthday","int"):1;
 
diff --git a/htdocs/comm/action/pertype.php b/htdocs/comm/action/pertype.php
index 4f4ef6a580c7a96b2a7500a988d1379a911d032c..544da904cdcf8cadb75e40d43c6aa62b7b35f2df 100644
--- a/htdocs/comm/action/pertype.php
+++ b/htdocs/comm/action/pertype.php
@@ -38,8 +38,8 @@ if (! empty($conf->projet->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/class
 
 if (! isset($conf->global->AGENDA_MAX_EVENTS_DAY_VIEW)) $conf->global->AGENDA_MAX_EVENTS_DAY_VIEW=3;
 
-$filter=GETPOST("filter",'',3);
-$filtert = GETPOST("usertodo","int",3)?GETPOST("usertodo","int",3):GETPOST("filtert","int",3);
+$filter = GETPOST("filter",'',3);
+$filtert = GETPOST("filtert","int",3);
 $usergroup = GETPOST("usergroup","int",3);
 //if (! ($usergroup > 0) && ! ($filtert > 0)) $filtert = $user->id;
 //$showbirthday = empty($conf->use_javascript_ajax)?GETPOST("showbirthday","int"):1;
@@ -250,7 +250,7 @@ $picto='calendarweek';
 $nav.=' &nbsp; <form name="dateselect" action="'.$_SERVER["PHP_SELF"].'?action=show_peruser'.$param.'">';
 $nav.='<input type="hidden" name="token" value="' . $_SESSION ['newtoken'] . '">';
 $nav.='<input type="hidden" name="action" value="' . $action . '">';
-$nav.='<input type="hidden" name="usertodo" value="' . $filtert . '">';
+$nav.='<input type="hidden" name="filtert" value="' . $filtert . '">';
 $nav.='<input type="hidden" name="usergroup" value="' . $usergroup . '">';
 $nav.='<input type="hidden" name="actioncode" value="' . $actioncode . '">';
 $nav.='<input type="hidden" name="resourceid" value="' . $resourceid . '">';
@@ -714,7 +714,7 @@ jQuery(document).ready(function() {
 		else if (ids.indexOf(",") > -1)	/* There is several events */
 		{
 			/* alert(\'several events\'); */
-			url = "'.DOL_URL_ROOT.'/comm/action/listactions.php?usertodo="+userid+"&dateselectyear="+year+"&dateselectmonth="+month+"&dateselectday="+day;
+			url = "'.DOL_URL_ROOT.'/comm/action/listactions.php?filtert="+userid+"&dateselectyear="+year+"&dateselectmonth="+month+"&dateselectday="+day;
 			window.location.href = url;
 		}
 		else	/* One event */
diff --git a/htdocs/comm/action/peruser.php b/htdocs/comm/action/peruser.php
index 61bf98634c43979888f1596fc6b88a9128dd72a9..2a707cd2d8ffe24df0792a2b6cb5b4dadb139acb 100644
--- a/htdocs/comm/action/peruser.php
+++ b/htdocs/comm/action/peruser.php
@@ -38,8 +38,8 @@ if (! empty($conf->projet->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/class
 
 if (! isset($conf->global->AGENDA_MAX_EVENTS_DAY_VIEW)) $conf->global->AGENDA_MAX_EVENTS_DAY_VIEW=3;
 
-$filter=GETPOST("filter",'',3);
-$filtert = GETPOST("usertodo","int",3)?GETPOST("usertodo","int",3):GETPOST("filtert","int",3);
+$filter = GETPOST("filter",'',3);
+$filtert = GETPOST("filtert","int",3);
 $usergroup = GETPOST("usergroup","int",3);
 //if (! ($usergroup > 0) && ! ($filtert > 0)) $filtert = $user->id;
 //$showbirthday = empty($conf->use_javascript_ajax)?GETPOST("showbirthday","int"):1;
@@ -252,7 +252,7 @@ $picto='calendarweek';
 $nav.=' &nbsp; <form name="dateselect" action="'.$_SERVER["PHP_SELF"].'?action=show_peruser'.$param.'">';
 $nav.='<input type="hidden" name="token" value="' . $_SESSION ['newtoken'] . '">';
 $nav.='<input type="hidden" name="action" value="' . $action . '">';
-$nav.='<input type="hidden" name="usertodo" value="' . $filtert . '">';
+$nav.='<input type="hidden" name="filtert" value="' . $filtert . '">';
 $nav.='<input type="hidden" name="usergroup" value="' . $usergroup . '">';
 $nav.='<input type="hidden" name="actioncode" value="' . $actioncode . '">';
 $nav.='<input type="hidden" name="resourceid" value="' . $resourceid . '">';
@@ -663,7 +663,6 @@ else
 	if ($usergroup > 0)	$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ug ON u.rowid = ug.fk_user";
 	$sql.= " WHERE u.statut = 1 AND u.entity IN (".getEntity('user',1).")";
 	if ($usergroup > 0)	$sql.= " AND ug.fk_usergroup = ".$usergroup;
-	//if (GETPOST("usertodo","int",3) > 0) $sql.=" AND u.rowid = ".GETPOST("usertodo","int",3);
 	//print $sql;
 	$resql=$db->query($sql);
 	if ($resql)
@@ -816,7 +815,7 @@ jQuery(document).ready(function() {
 		else if (ids.indexOf(",") > -1)	/* There is several events */
 		{
 			/* alert(\'several events\'); */
-			url = "'.DOL_URL_ROOT.'/comm/action/listactions.php?usertodo="+userid+"&dateselectyear="+year+"&dateselectmonth="+month+"&dateselectday="+day;
+			url = "'.DOL_URL_ROOT.'/comm/action/listactions.php?filtert="+userid+"&dateselectyear="+year+"&dateselectmonth="+month+"&dateselectday="+day;
 			window.location.href = url;
 		}
 		else	/* One event */
diff --git a/htdocs/comm/mailing/card.php b/htdocs/comm/mailing/card.php
index fe582d566560b81eb10bb361f577827149e24b6a..0b4c3c239f956763342d6507f035187646443eb3 100644
--- a/htdocs/comm/mailing/card.php
+++ b/htdocs/comm/mailing/card.php
@@ -1057,7 +1057,7 @@ else
 			// Print mail content
 			print load_fiche_titre($langs->trans("EMail"), $form->textwithpicto($langs->trans("AvailableVariables"), $htmltext, 1, 'help', '', 0, 2, 'emailsubstitionhelp'), 'title_generic');
 			
-			dol_fiche_head('');
+			dol_fiche_head('', '', '', -1);
 			
 			print '<table class="border" width="100%">';
 
diff --git a/htdocs/comm/mailing/cibles.php b/htdocs/comm/mailing/cibles.php
index d3642c503939cffdb610c65d2ac4a83e98214fe4..118cc336fb7abce6e0b524ec10e072678f6ff135 100644
--- a/htdocs/comm/mailing/cibles.php
+++ b/htdocs/comm/mailing/cibles.php
@@ -161,6 +161,7 @@ if ($_POST["button_removefilter"])
 	$search_lastname='';
 	$search_firstname='';
 	$search_email='';
+	$search_dest_status='';
 }
 
 
@@ -399,7 +400,7 @@ if ($object->fetch($id) >= 0)
 	if ($search_lastname)    $sql.= " AND mc.lastname    LIKE '%".$db->escape($search_lastname)."%'";
 	if ($search_firstname) $sql.= " AND mc.firstname LIKE '%".$db->escape($search_firstname)."%'";
 	if ($search_email)  $sql.= " AND mc.email  LIKE '%".$db->escape($search_email)."%'";
-	if (!empty($search_dest_status)) $sql.= " AND mc.statut=".$db->escape($search_dest_status)." ";
+	if ($search_dest_status != '' && $search_dest_status >= -1) $sql.= " AND mc.statut=".$db->escape($search_dest_status)." ";
 	$sql .= $db->order($sortfield,$sortorder);
 
 	// Count total nb of records
@@ -411,7 +412,7 @@ if ($object->fetch($id) >= 0)
 	}
 	//$nbtotalofrecords=$object->nbemail;     // nbemail is a denormalized field storing nb of targets
 	$sql .= $db->plimit($limit+1, $offset);
-
+	
 	$resql=$db->query($sql);
 	if ($resql)
 	{
@@ -446,29 +447,12 @@ if ($object->fetch($id) >= 0)
 		print '<input type="hidden" name="limit" value="'.$limit.'">';
 		
 
-		if ($page)			$param.= "&amp;page=".$page;
+		if ($page)	$param.= "&amp;page=".$page;
+		
 		print '<table class="noborder" width="100%">';
-		print '<tr class="liste_titre">';
-		print_liste_field_titre($langs->trans("EMail"),$_SERVER["PHP_SELF"],"mc.email",$param,"","",$sortfield,$sortorder);
-		print_liste_field_titre($langs->trans("Lastname"),$_SERVER["PHP_SELF"],"mc.lastname",$param,"","",$sortfield,$sortorder);
-		print_liste_field_titre($langs->trans("Firstname"),$_SERVER["PHP_SELF"],"mc.firstname",$param,"","",$sortfield,$sortorder);
-		print_liste_field_titre($langs->trans("OtherInformations"),$_SERVER["PHP_SELF"],"",$param,"","",$sortfield,$sortorder);
-		print_liste_field_titre($langs->trans("Source"),$_SERVER["PHP_SELF"],"",$param,"",'align="center"',$sortfield,$sortorder);
-		// Date sending
-		if ($object->statut < 2)
-		{
-			print_liste_field_titre('');
-		}
-		else
-		{
-			print_liste_field_titre($langs->trans("DateSending"),$_SERVER["PHP_SELF"],"mc.date_envoi",$param,'','align="center"',$sortfield,$sortorder);
-		}
-		print_liste_field_titre($langs->trans("Status"),$_SERVER["PHP_SELF"],"mc.statut",$param,'','align="right"',$sortfield,$sortorder);
-		print_liste_field_titre('',$_SERVER["PHP_SELF"],"",'','','',$sortfield,$sortorder,'maxwidthsearch ');
-		print '</tr>';
-
+		
 		// Ligne des champs de filtres
-		print '<tr class="liste_titre">';
+		print '<tr class="liste_titre_filter">';
 		// EMail
 		print '<td class="liste_titre">';
 		print '<input class="flat maxwidth100" type="text" name="search_email" value="'.dol_escape_htmltag($search_email).'">';
@@ -489,7 +473,7 @@ if ($object->fetch($id) >= 0)
 		print '<td class="liste_titre">';
 		print '&nbsp';
 		print '</td>';
-
+		
 		// Date sending
 		print '<td class="liste_titre">';
 		print '&nbsp';
@@ -504,6 +488,25 @@ if ($object->fetch($id) >= 0)
 		print $searchpitco;
 		print '</td>';
 		print '</tr>';
+		
+		print '<tr class="liste_titre">';
+		print_liste_field_titre($langs->trans("EMail"),$_SERVER["PHP_SELF"],"mc.email",$param,"","",$sortfield,$sortorder);
+		print_liste_field_titre($langs->trans("Lastname"),$_SERVER["PHP_SELF"],"mc.lastname",$param,"","",$sortfield,$sortorder);
+		print_liste_field_titre($langs->trans("Firstname"),$_SERVER["PHP_SELF"],"mc.firstname",$param,"","",$sortfield,$sortorder);
+		print_liste_field_titre($langs->trans("OtherInformations"),$_SERVER["PHP_SELF"],"",$param,"","",$sortfield,$sortorder);
+		print_liste_field_titre($langs->trans("Source"),$_SERVER["PHP_SELF"],"",$param,"",'align="center"',$sortfield,$sortorder);
+		// Date sending
+		if ($object->statut < 2)
+		{
+			print_liste_field_titre('');
+		}
+		else
+		{
+			print_liste_field_titre($langs->trans("DateSending"),$_SERVER["PHP_SELF"],"mc.date_envoi",$param,'','align="center"',$sortfield,$sortorder);
+		}
+		print_liste_field_titre($langs->trans("Status"),$_SERVER["PHP_SELF"],"mc.statut",$param,'','align="right"',$sortfield,$sortorder);
+		print_liste_field_titre('',$_SERVER["PHP_SELF"],"",'','','',$sortfield,$sortorder,'maxwidthsearch ');
+		print '</tr>';
 
 		$i = 0;
 
diff --git a/htdocs/comm/mailing/class/mailing.class.php b/htdocs/comm/mailing/class/mailing.class.php
index b0dff81332c5f53aade01443ddd5e8d0a7812b4a..43a3cdcb78d685e039cfb1e526ef8347c4bd5d63 100644
--- a/htdocs/comm/mailing/class/mailing.class.php
+++ b/htdocs/comm/mailing/class/mailing.class.php
@@ -80,8 +80,8 @@ class Mailing extends CommonObject
 		$this->statuts[2] = 'MailingStatusSentPartialy';
 		$this->statuts[3] = 'MailingStatusSentCompletely';
 
-		$this->statut_dest[0] = 'MailingStatusNotSent';
 		$this->statut_dest[-1] = 'MailingStatusError';
+		$this->statut_dest[0] = 'MailingStatusNotSent';
 		$this->statut_dest[1] = 'MailingStatusSent';
 		$this->statut_dest[2] = 'MailingStatusRead';
 		$this->statut_dest[3] = 'MailingStatusReadAndUnsubscribe';    // Read but ask to not be contacted anymore
diff --git a/htdocs/comm/propal/card.php b/htdocs/comm/propal/card.php
index 444669a6f495410cc8d58abd8f7496c16b1e6338..00fa9df2b91cea3820945dd7e3c619ea857dc414 100644
--- a/htdocs/comm/propal/card.php
+++ b/htdocs/comm/propal/card.php
@@ -497,7 +497,10 @@ if (empty($reshook))
 											$array_options = $lines[$i]->array_options;
 										}
 
-										$result = $object->addline($desc, $lines[$i]->subprice, $lines[$i]->qty, $lines[$i]->tva_tx, $lines[$i]->localtax1_tx, $lines[$i]->localtax2_tx, $lines[$i]->fk_product, $lines[$i]->remise_percent, 'HT', 0, $lines[$i]->info_bits, $product_type, $lines[$i]->rang, $lines[$i]->special_code, $fk_parent_line, $lines[$i]->fk_fournprice, $lines[$i]->pa_ht, $label, $date_start, $date_end, $array_options, $lines[$i]->fk_unit);
+										$tva_tx = $lines[$i]->tva_tx;
+										if (! empty($lines[$i]->vat_src_code) && ! preg_match('/\(/', $tva_tx)) $tva_tx .= ' ('.$lines[$i]->vat_src_code.')';
+										
+										$result = $object->addline($desc, $lines[$i]->subprice, $lines[$i]->qty, $tva_tx, $lines[$i]->localtax1_tx, $lines[$i]->localtax2_tx, $lines[$i]->fk_product, $lines[$i]->remise_percent, 'HT', 0, $lines[$i]->info_bits, $product_type, $lines[$i]->rang, $lines[$i]->special_code, $fk_parent_line, $lines[$i]->fk_fournprice, $lines[$i]->pa_ht, $label, $date_start, $date_end, $array_options, $lines[$i]->fk_unit);
 
 										if ($result > 0) {
 											$lineid = $result;
diff --git a/htdocs/comm/propal/class/api_proposals.class.php b/htdocs/comm/propal/class/api_proposals.class.php
index 0440793ceac3084043385144596dc7eda9645ed2..fd508b03256d17bfca762582b56cf8b7600f127b 100644
--- a/htdocs/comm/propal/class/api_proposals.class.php
+++ b/htdocs/comm/propal/class/api_proposals.class.php
@@ -16,9 +16,10 @@
  * along with this program. If not, see <http://www.gnu.org/licenses/>.
  */
 
- use Luracast\Restler\RestException;
+use Luracast\Restler\RestException;
+
+require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
 
- require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
 
 /**
  * API class for orders
@@ -260,12 +261,9 @@ class Proposals extends DolibarrApi
                         $request_data->localtax2_tx,
                         $request_data->fk_product,
                         $request_data->remise_percent,
-                        $request_data->info_bits,
-                        $request_data->fk_remise_except,
                         'HT',
                         0,
-                        $request_data->date_start,
-                        $request_data->date_end,
+                        $request_data->info_bits,
                         $request_data->product_type,
                         $request_data->rang,
                         $request_data->special_code,
@@ -273,10 +271,14 @@ class Proposals extends DolibarrApi
                         $request_data->fk_fournprice,
                         $request_data->pa_ht,
                         $request_data->label,
+                        $request_data->date_start,
+                        $request_data->date_end,
                         $request_data->array_options,
                         $request_data->fk_unit,
                         $this->element,
-                        $request_data->id
+                        $request_data->id,
+                        $request_data->pu_ht_devise,
+                        $request_data->fk_remise_except
       );
 
       if ($updateRes > 0) {
diff --git a/htdocs/comm/propal/class/propal.class.php b/htdocs/comm/propal/class/propal.class.php
index 46c6a55cf2f59fe7c206384cc8994b48572d21b0..7c60e3290f3f224615678d7e6f5f8c18b58e4f99 100644
--- a/htdocs/comm/propal/class/propal.class.php
+++ b/htdocs/comm/propal/class/propal.class.php
@@ -187,7 +187,7 @@ class Propal extends CommonObject
 	/**
 	 * Billed or processed quote
 	 */
-	const STATUS_BILLED = 4;
+	const STATUS_BILLED = 4;   // Todo rename into STATUS_CLOSE ?
 
     /**
      *	Constructor
@@ -253,6 +253,8 @@ class Propal extends CommonObject
             $tva_tx = get_default_tva($mysoc,$this->thirdparty,$prod->id);
             $tva_npr = get_default_npr($mysoc,$this->thirdparty,$prod->id);
             if (empty($tva_tx)) $tva_npr=0;
+            $vat_src_code = '';     // May be defined into tva_tx
+            
             $localtax1_tx = get_localtax($tva_tx,1,$mysoc,$this->thirdparty,$tva_npr);
             $localtax2_tx = get_localtax($tva_tx,2,$mysoc,$this->thirdparty,$tva_npr);
 
@@ -273,6 +275,7 @@ class Propal extends CommonObject
             $line->qty=$qty;
             $line->subprice=$price;
             $line->remise_percent=$remise_percent;
+            $line->vat_src_code=$vat_src_code;
             $line->tva_tx=$tva_tx;
 	        $line->fk_unit=$prod->fk_unit;
 			if ($tva_npr) $line->info_bits = 1;
@@ -315,6 +318,7 @@ class Propal extends CommonObject
             $line->fk_propal=$this->id;
             $line->fk_remise_except=$remise->id;
             $line->desc=$remise->description;   	// Description ligne
+            $line->vat_src_code=$remise->vat_src_code;
             $line->tva_tx=$remise->tva_tx;
             $line->subprice=-$remise->amount_ht;
             $line->fk_product=0;					// Id produit predefined
@@ -391,15 +395,16 @@ class Propal extends CommonObject
      * 		@param 		string		$fk_unit 			Code of the unit to use. Null to use the default one
      *      @param		string		$origin				'order', ...
      *      @param		int			$origin_id			Id of origin object
-     *    	@return    	int         	    			>0 if OK, <0 if KO
      * 		@param		double		$pu_ht_devise		Unit price in currency
+     * 		@param		int    		$fk_remise_except	Id discount if line is from a discount
+     *    	@return    	int         	    			>0 if OK, <0 if KO
      *    	@see       	add_product
      */
-	function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0.0, $txlocaltax2=0.0, $fk_product=0, $remise_percent=0.0, $price_base_type='HT', $pu_ttc=0.0, $info_bits=0, $type=0, $rang=-1, $special_code=0, $fk_parent_line=0, $fk_fournprice=0, $pa_ht=0, $label='',$date_start='', $date_end='',$array_options=0, $fk_unit=null, $origin='', $origin_id=0, $pu_ht_devise = 0)
+	function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0.0, $txlocaltax2=0.0, $fk_product=0, $remise_percent=0.0, $price_base_type='HT', $pu_ttc=0.0, $info_bits=0, $type=0, $rang=-1, $special_code=0, $fk_parent_line=0, $fk_fournprice=0, $pa_ht=0, $label='',$date_start='', $date_end='',$array_options=0, $fk_unit=null, $origin='', $origin_id=0, $pu_ht_devise=0, $fk_remise_except=0)
     {
     	global $mysoc, $conf, $langs;
 
-        dol_syslog(get_class($this)."::addline propalid=$this->id, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, fk_product=$fk_product, remise_except=$remise_percent, price_base_type=$price_base_type, pu_ttc=$pu_ttc, info_bits=$info_bits, type=$type");
+        dol_syslog(get_class($this)."::addline propalid=$this->id, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, fk_product=$fk_product, remise_except=$remise_percent, price_base_type=$price_base_type, pu_ttc=$pu_ttc, info_bits=$info_bits, type=$type, fk_remise_except=".$fk_remise_except);
         include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
 
         // Clean parameters
@@ -515,6 +520,8 @@ class Propal extends CommonObject
 			$this->line->localtax1_type = $localtaxes_type[0];
 			$this->line->localtax2_type = $localtaxes_type[2];
             $this->line->fk_product=$fk_product;
+            $this->line->product_type=$type;
+            $this->line->fk_remise_except=$fk_remise_except;
             $this->line->remise_percent=$remise_percent;
             $this->line->subprice=$pu_ht;
             $this->line->rang=$rangtouse;
@@ -524,7 +531,6 @@ class Propal extends CommonObject
             $this->line->total_localtax1=$total_localtax1;
             $this->line->total_localtax2=$total_localtax2;
             $this->line->total_ttc=$total_ttc;
-            $this->line->product_type=$type;
             $this->line->special_code=$special_code;
             $this->line->fk_parent_line=$fk_parent_line;
             $this->line->fk_unit=$fk_unit;
@@ -698,7 +704,8 @@ class Propal extends CommonObject
             $this->line->label				= $label;
             $this->line->desc				= $desc;
             $this->line->qty				= $qty;
-            $this->line->product_type			= $type;
+            $this->line->product_type		= $type;
+            $this->line->vat_src_code		= $vat_src_code;
             $this->line->tva_tx				= $txtva;
             $this->line->localtax1_tx		= $txlocaltax1;
             $this->line->localtax2_tx		= $txlocaltax2;
@@ -708,7 +715,6 @@ class Propal extends CommonObject
             $this->line->subprice			= $pu_ht;
             $this->line->info_bits			= $info_bits;
 
-            $this->line->vat_src_code		= $vat_src_code;
             $this->line->total_ht			= $total_ht;
             $this->line->total_tva			= $total_tva;
             $this->line->total_localtax1	= $total_localtax1;
@@ -1301,7 +1307,7 @@ class Propal extends CommonObject
                 $this->note                 = $obj->note_private; // TODO deprecated
                 $this->note_private         = $obj->note_private;
                 $this->note_public          = $obj->note_public;
-                $this->statut               = $obj->fk_statut;
+                $this->statut               = (int) $obj->fk_statut;
                 $this->statut_libelle       = $obj->statut_label;
 
                 $this->datec                = $this->db->jdate($obj->datec); // TODO deprecated
@@ -1366,103 +1372,14 @@ class Propal extends CommonObject
                 $this->lines = array();
 
                 /*
-                 * Lignes propales liees a un produit ou non
+                 * Lines
                  */
-                $sql = "SELECT d.rowid, d.fk_propal, d.fk_parent_line, d.label as custom_label, d.description, d.price, d.tva_tx, d.localtax1_tx, d.localtax2_tx, d.qty, d.fk_remise_except, d.remise_percent, d.subprice, d.fk_product,";
-				$sql.= " d.info_bits, d.total_ht, d.total_tva, d.total_localtax1, d.total_localtax2, d.total_ttc, d.fk_product_fournisseur_price as fk_fournprice, d.buy_price_ht as pa_ht, d.special_code, d.rang, d.product_type,";
-	            $sql.= " d.fk_unit,";
-                $sql.= ' p.ref as product_ref, p.description as product_desc, p.fk_product_type, p.label as product_label,';
-                $sql.= ' d.date_start, d.date_end';
-				$sql.= ' ,d.fk_multicurrency, d.multicurrency_code, d.multicurrency_subprice, d.multicurrency_total_ht, d.multicurrency_total_tva, d.multicurrency_total_ttc';
-                $sql.= " FROM ".MAIN_DB_PREFIX."propaldet as d";
-                $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON d.fk_product = p.rowid";
-                $sql.= " WHERE d.fk_propal = ".$this->id;
-                $sql.= " ORDER by d.rang";
-
-                $result = $this->db->query($sql);
-                if ($result)
-                {
-                	require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
-                	$extrafieldsline=new ExtraFields($this->db);
-                	$line = new PropaleLigne($this->db);
-                	$extralabelsline=$extrafieldsline->fetch_name_optionals_label($line->table_element,true);
-
-                    $num = $this->db->num_rows($result);
-                    $i = 0;
-
-                    while ($i < $num)
-                    {
-                        $objp                   = $this->db->fetch_object($result);
-
-                        $line                   = new PropaleLigne($this->db);
-
-                        $line->rowid			= $objp->rowid; //Deprecated
-                        $line->id				= $objp->rowid;
-                        $line->fk_propal		= $objp->fk_propal;
-                        $line->fk_parent_line	= $objp->fk_parent_line;
-                        $line->product_type     = $objp->product_type;
-                        $line->label            = $objp->custom_label;
-                        $line->desc             = $objp->description;  // Description ligne
-                        $line->qty              = $objp->qty;
-                        $line->tva_tx           = $objp->tva_tx;
-                        $line->localtax1_tx		= $objp->localtax1_tx;
-                        $line->localtax2_tx		= $objp->localtax2_tx;
-                        $line->subprice         = $objp->subprice;
-                        $line->fk_remise_except = $objp->fk_remise_except;
-                        $line->remise_percent   = $objp->remise_percent;
-                        $line->price            = $objp->price;		// TODO deprecated
-
-                        $line->info_bits        = $objp->info_bits;
-                        $line->total_ht         = $objp->total_ht;
-                        $line->total_tva        = $objp->total_tva;
-                        $line->total_localtax1	= $objp->total_localtax1;
-                        $line->total_localtax2	= $objp->total_localtax2;
-                        $line->total_ttc        = $objp->total_ttc;
-      					$line->fk_fournprice 	= $objp->fk_fournprice;
-						$marginInfos			= getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
-						$line->pa_ht 			= $marginInfos[0];
-						$line->marge_tx			= $marginInfos[1];
-						$line->marque_tx		= $marginInfos[2];
-                        $line->special_code     = $objp->special_code;
-                        $line->rang             = $objp->rang;
-
-                        $line->fk_product       = $objp->fk_product;
-
-                        $line->ref				= $objp->product_ref;		// TODO deprecated
-                        $line->product_ref		= $objp->product_ref;
-                        $line->libelle			= $objp->product_label;		// TODO deprecated
-                        $line->product_label	= $objp->product_label;
-                        $line->product_desc     = $objp->product_desc; 		// Description produit
-                        $line->fk_product_type  = $objp->fk_product_type;
-	                    $line->fk_unit          = $objp->fk_unit;
-
-                        $line->date_start  		= $this->db->jdate($objp->date_start);
-                        $line->date_end  		= $this->db->jdate($objp->date_end);
-
-						// Multicurrency
-						$line->fk_multicurrency 		= $objp->fk_multicurrency;
-						$line->multicurrency_code 		= $objp->multicurrency_code;
-						$line->multicurrency_subprice 	= $objp->multicurrency_subprice;
-						$line->multicurrency_total_ht 	= $objp->multicurrency_total_ht;
-						$line->multicurrency_total_tva 	= $objp->multicurrency_total_tva;
-						$line->multicurrency_total_ttc 	= $objp->multicurrency_total_ttc;
-
-                        $line->fetch_optionals($line->id,$extralabelsline);
-
-                        $this->lines[$i]        = $line;
-                        //dol_syslog("1 ".$line->fk_product);
-                        //print "xx $i ".$this->lines[$i]->fk_product;
-                        $i++;
-                    }
-                    $this->db->free($result);
-                }
-                else
+                $result=$this->fetch_lines();
+                if ($result < 0)
                 {
-                    $this->error=$this->db->lasterror();
-                    return -1;
+                    return -3;
                 }
 
-
                 return 1;
             }
 
@@ -1475,6 +1392,114 @@ class Propal extends CommonObject
             return -1;
         }
     }
+	
+	/**
+	 * Load array lines
+	 * 
+	 * @param		int		$only_product	Return only physical products
+	 * @return		int						<0 if KO, >0 if OK
+	 */
+	function fetch_lines($only_product=0)
+	{
+		$this->lines=array();
+		
+		$sql = 'SELECT d.rowid, d.fk_propal, d.fk_parent_line, d.label as custom_label, d.description, d.price, d.vat_src_code, d.tva_tx, d.localtax1_tx, d.localtax2_tx, d.qty, d.fk_remise_except, d.remise_percent, d.subprice, d.fk_product,';
+		$sql.= ' d.info_bits, d.total_ht, d.total_tva, d.total_localtax1, d.total_localtax2, d.total_ttc, d.fk_product_fournisseur_price as fk_fournprice, d.buy_price_ht as pa_ht, d.special_code, d.rang, d.product_type,';
+		$sql.= ' d.fk_unit,';
+		$sql.= ' p.ref as product_ref, p.description as product_desc, p.fk_product_type, p.label as product_label,';
+		$sql.= ' d.date_start, d.date_end';
+		$sql.= ' ,d.fk_multicurrency, d.multicurrency_code, d.multicurrency_subprice, d.multicurrency_total_ht, d.multicurrency_total_tva, d.multicurrency_total_ttc';
+		$sql.= ' FROM '.MAIN_DB_PREFIX.'propaldet as d';
+		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON (d.fk_product = p.rowid)';
+		$sql.= ' WHERE d.fk_propal = '.$this->id;
+		if ($only_product) $sql .= ' AND p.fk_product_type = 0';
+		$sql.= ' ORDER by d.rang';
+
+		dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
+		$result = $this->db->query($sql);
+		if ($result)
+		{
+			require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
+
+			$num = $this->db->num_rows($result);
+			
+			$i = 0;
+			while ($i < $num)
+			{
+				$objp                   = $this->db->fetch_object($result);
+
+				$line                   = new PropaleLigne($this->db);
+
+				$line->rowid			= $objp->rowid; //Deprecated
+				$line->id				= $objp->rowid;
+				$line->fk_propal		= $objp->fk_propal;
+				$line->fk_parent_line	= $objp->fk_parent_line;
+				$line->product_type     = $objp->product_type;
+				$line->label            = $objp->custom_label;
+				$line->desc             = $objp->description;  // Description ligne
+				$line->qty              = $objp->qty;
+				$line->vat_src_code     = $objp->vat_src_code;
+				$line->tva_tx           = $objp->tva_tx;
+				$line->localtax1_tx		= $objp->localtax1_tx;
+				$line->localtax2_tx		= $objp->localtax2_tx;
+				$line->subprice         = $objp->subprice;
+				$line->fk_remise_except = $objp->fk_remise_except;
+				$line->remise_percent   = $objp->remise_percent;
+				$line->price            = $objp->price;		// TODO deprecated
+
+				$line->info_bits        = $objp->info_bits;
+				$line->total_ht         = $objp->total_ht;
+				$line->total_tva        = $objp->total_tva;
+				$line->total_localtax1	= $objp->total_localtax1;
+				$line->total_localtax2	= $objp->total_localtax2;
+				$line->total_ttc        = $objp->total_ttc;
+				$line->fk_fournprice 	= $objp->fk_fournprice;
+				$marginInfos			= getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
+				$line->pa_ht 			= $marginInfos[0];
+				$line->marge_tx			= $marginInfos[1];
+				$line->marque_tx		= $marginInfos[2];
+				$line->special_code     = $objp->special_code;
+				$line->rang             = $objp->rang;
+
+				$line->fk_product       = $objp->fk_product;
+
+				$line->ref				= $objp->product_ref;		// TODO deprecated
+				$line->product_ref		= $objp->product_ref;
+				$line->libelle			= $objp->product_label;		// TODO deprecated
+				$line->product_label	= $objp->product_label;
+				$line->product_desc     = $objp->product_desc; 		// Description produit
+				$line->fk_product_type  = $objp->fk_product_type;
+				$line->fk_unit          = $objp->fk_unit;
+
+				$line->date_start  		= $this->db->jdate($objp->date_start);
+				$line->date_end  		= $this->db->jdate($objp->date_end);
+
+				// Multicurrency
+				$line->fk_multicurrency 		= $objp->fk_multicurrency;
+				$line->multicurrency_code 		= $objp->multicurrency_code;
+				$line->multicurrency_subprice 	= $objp->multicurrency_subprice;
+				$line->multicurrency_total_ht 	= $objp->multicurrency_total_ht;
+				$line->multicurrency_total_tva 	= $objp->multicurrency_total_tva;
+				$line->multicurrency_total_ttc 	= $objp->multicurrency_total_ttc;
+
+				$line->fetch_optionals();
+
+				$this->lines[$i]        = $line;
+				//dol_syslog("1 ".$line->fk_product);
+				//print "xx $i ".$this->lines[$i]->fk_product;
+				$i++;
+			}
+			
+			$this->db->free($result);
+			
+			return 1;
+		}
+		else
+		{
+			$this->error=$this->db->lasterror();
+			return -3;
+		}
+	}
 
     /**
      *	Update value of extrafields on the proposal
@@ -3326,8 +3351,10 @@ class Propal extends CommonObject
      */
     function getLinesArray()
     {
-        // For other object, here we call fetch_lines. But fetch_lines does not exists on proposal
-
+        // TODO Duplicate with fetch_lines ? Wich one to keep ?
+        
+        $this->lines = array();
+        
         $sql = 'SELECT pt.rowid, pt.label as custom_label, pt.description, pt.fk_product, pt.fk_remise_except,';
         $sql.= ' pt.qty, pt.vat_src_code, pt.tva_tx, pt.remise_percent, pt.subprice, pt.info_bits,';
         $sql.= ' pt.total_ht, pt.total_tva, pt.total_ttc, pt.fk_product_fournisseur_price as fk_fournprice, pt.buy_price_ht as pa_ht, pt.special_code, pt.localtax1_tx, pt.localtax2_tx,';
@@ -3591,7 +3618,7 @@ class PropaleLigne  extends CommonObjectLine
      */
 	function fetch($rowid)
 	{
-		$sql = 'SELECT pd.rowid, pd.fk_propal, pd.fk_parent_line, pd.fk_product, pd.label as custom_label, pd.description, pd.price, pd.qty, pd.tva_tx,';
+		$sql = 'SELECT pd.rowid, pd.fk_propal, pd.fk_parent_line, pd.fk_product, pd.label as custom_label, pd.description, pd.price, pd.qty, pd.vat_src_code, pd.tva_tx,';
 		$sql.= ' pd.remise, pd.remise_percent, pd.fk_remise_except, pd.subprice,';
 		$sql.= ' pd.info_bits, pd.total_ht, pd.total_tva, pd.total_ttc, pd.fk_product_fournisseur_price as fk_fournprice, pd.buy_price_ht as pa_ht, pd.special_code, pd.rang,';
 		$sql.= ' pd.fk_unit,';
@@ -3617,6 +3644,7 @@ class PropaleLigne  extends CommonObjectLine
 			$this->qty				= $objp->qty;
 			$this->price			= $objp->price;		// deprecated
 			$this->subprice			= $objp->subprice;
+			$this->vat_src_code		= $objp->vat_src_code;
 			$this->tva_tx			= $objp->tva_tx;
 			$this->remise			= $objp->remise;    // deprecated
 			$this->remise_percent	= $objp->remise_percent;
diff --git a/htdocs/comm/propal/contact.php b/htdocs/comm/propal/contact.php
index 3c3aa6aef88b626c1a6eec99d1034333a26f9f6d..3e9e5a1205d589d8e9c2d328ccdc6e94899ffec4 100644
--- a/htdocs/comm/propal/contact.php
+++ b/htdocs/comm/propal/contact.php
@@ -130,12 +130,12 @@ else if ($action == 'deletecontact' && $user->rights->propale->creer)
 		dol_print_error($db);
 	}
 }
-
+/*
 else if ($action == 'setaddress' && $user->rights->propale->creer)
 {
 	$result=$object->setDeliveryAddress($_POST['fk_address']);
 	if ($result < 0) dol_print_error($db,$object->error);
-}
+}*/
 
 
 /*
diff --git a/htdocs/commande/card.php b/htdocs/commande/card.php
index e369a1a7217d49f7cf503e45d2defd9f29cae96e..8459a4a5e9e40624f8346c3af0956c425470bfd1 100644
--- a/htdocs/commande/card.php
+++ b/htdocs/commande/card.php
@@ -377,7 +377,10 @@ if (empty($reshook))
 									$array_options = $lines[$i]->array_options;
 								}
 
-								$result = $object->addline($desc, $lines[$i]->subprice, $lines[$i]->qty, $lines[$i]->tva_tx, $lines[$i]->localtax1_tx, $lines[$i]->localtax2_tx, $lines[$i]->fk_product, $lines[$i]->remise_percent, $lines[$i]->info_bits, $lines[$i]->fk_remise_except, 'HT', 0, $date_start, $date_end, $product_type, $lines[$i]->rang, $lines[$i]->special_code, $fk_parent_line, $lines[$i]->fk_fournprice, $lines[$i]->pa_ht, $label, $array_options, $lines[$i]->fk_unit, $object->origin, $lines[$i]->rowid);
+								$tva_tx = $lines[$i]->tva_tx;
+								if (! empty($lines[$i]->vat_src_code) && ! preg_match('/\(/', $tva_tx)) $tva_tx .= ' ('.$lines[$i]->vat_src_code.')';
+								
+								$result = $object->addline($desc, $lines[$i]->subprice, $lines[$i]->qty, $tva_tx, $lines[$i]->localtax1_tx, $lines[$i]->localtax2_tx, $lines[$i]->fk_product, $lines[$i]->remise_percent, $lines[$i]->info_bits, $lines[$i]->fk_remise_except, 'HT', 0, $date_start, $date_end, $product_type, $lines[$i]->rang, $lines[$i]->special_code, $fk_parent_line, $lines[$i]->fk_fournprice, $lines[$i]->pa_ht, $label, $array_options, $lines[$i]->fk_unit, $object->origin, $lines[$i]->rowid);
 
 								if ($result < 0) {
 									$error++;
diff --git a/htdocs/commande/class/commande.class.php b/htdocs/commande/class/commande.class.php
index 82050b7b5860d7fd0e58f977fc196a67b346b968..70168b5e1a9eb302ab6d8f9f45ae2262e74349f2 100644
--- a/htdocs/commande/class/commande.class.php
+++ b/htdocs/commande/class/commande.class.php
@@ -1103,6 +1103,7 @@ class Commande extends CommonOrder
             $line->desc              = $object->lines[$i]->desc;
             $line->price             = $object->lines[$i]->price;
             $line->subprice          = $object->lines[$i]->subprice;
+            $line->vat_src_code      = $object->lines[$i]->vat_src_code;
             $line->tva_tx            = $object->lines[$i]->tva_tx;
             $line->localtax1_tx      = $object->lines[$i]->localtax1_tx;
             $line->localtax2_tx      = $object->lines[$i]->localtax2_tx;
@@ -1466,7 +1467,8 @@ class Commande extends CommonOrder
             $tva_tx = get_default_tva($mysoc,$this->thirdparty,$prod->id);
             $tva_npr = get_default_npr($mysoc,$this->thirdparty,$prod->id);
             if (empty($tva_tx)) $tva_npr=0;
-
+            $vat_src_code = '';     // May be defined into tva_tx
+            
             $localtax1_tx=get_localtax($tva_tx,1,$this->thirdparty,$mysoc,$tva_npr);
             $localtax2_tx=get_localtax($tva_tx,2,$this->thirdparty,$mysoc,$tva_npr);
 
@@ -1485,6 +1487,7 @@ class Commande extends CommonOrder
             $line->qty=$qty;
             $line->subprice=$price;
             $line->remise_percent=$remise_percent;
+            $line->vat_src_code=$vat_src_code;
             $line->tva_tx=$tva_tx;
             $line->localtax1_tx=$localtax1_tx;
             $line->localtax2_tx=$localtax2_tx;
@@ -1703,6 +1706,7 @@ class Commande extends CommonOrder
             $line->fk_commande=$this->id;
             $line->fk_remise_except=$remise->id;
             $line->desc=$remise->description;   	// Description ligne
+            $line->vat_src_code=$remise->vat_src_code;
             $line->tva_tx=$remise->tva_tx;
             $line->subprice=-$remise->amount_ht;
             $line->price=-$remise->amount_ht;
@@ -1758,7 +1762,7 @@ class Commande extends CommonOrder
         $this->lines=array();
 
         $sql = 'SELECT l.rowid, l.fk_product, l.fk_parent_line, l.product_type, l.fk_commande, l.label as custom_label, l.description, l.price, l.qty, l.vat_src_code, l.tva_tx,';
-        $sql.= ' l.localtax1_tx, l.localtax2_tx, l.fk_remise_except, l.remise_percent, l.subprice, l.fk_product_fournisseur_price as fk_fournprice, l.buy_price_ht as pa_ht, l.rang, l.info_bits, l.special_code,';
+        $sql.= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.fk_remise_except, l.remise_percent, l.subprice, l.fk_product_fournisseur_price as fk_fournprice, l.buy_price_ht as pa_ht, l.rang, l.info_bits, l.special_code,';
         $sql.= ' l.total_ht, l.total_ttc, l.total_tva, l.total_localtax1, l.total_localtax2, l.date_start, l.date_end,';
 	    $sql.= ' l.fk_unit,';
 		$sql.= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
@@ -1795,9 +1799,11 @@ class Commande extends CommonOrder
 
                 $line->vat_src_code     = $objp->vat_src_code; 
                 $line->tva_tx           = $objp->tva_tx;
-                $line->localtax1_tx     = $objp->localtax1_tx;
+	            $line->localtax1_tx     = $objp->localtax1_tx;
                 $line->localtax2_tx     = $objp->localtax2_tx;
-                $line->total_ht         = $objp->total_ht;
+	            $line->localtax1_type	= $objp->localtax1_type;
+	            $line->localtax2_type	= $objp->localtax2_type;
+	            $line->total_ht         = $objp->total_ht;
                 $line->total_ttc        = $objp->total_ttc;
                 $line->total_tva        = $objp->total_tva;
                 $line->total_localtax1  = $objp->total_localtax1;
@@ -3806,6 +3812,7 @@ class OrderLine extends CommonOrderLine
             $this->qty              = $objp->qty;
             $this->price            = $objp->price;
             $this->subprice         = $objp->subprice;
+            $this->vat_src_code     = $objp->vat_src_code;
             $this->tva_tx           = $objp->tva_tx;
             $this->localtax1_tx		= $objp->localtax1_tx;
             $this->localtax2_tx		= $objp->localtax2_tx;
@@ -4117,6 +4124,7 @@ class OrderLine extends CommonOrderLine
 		$sql = "UPDATE ".MAIN_DB_PREFIX."commandedet SET";
 		$sql.= " description='".$this->db->escape($this->desc)."'";
 		$sql.= " , label=".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null");
+		$sql.= " , vat_src_code=".(! empty($this->vat_src_code)?"'".$this->db->escape($this->vat_src_code)."'":"''");
 		$sql.= " , tva_tx=".price2num($this->tva_tx);
 		$sql.= " , localtax1_tx=".price2num($this->localtax1_tx);
 		$sql.= " , localtax2_tx=".price2num($this->localtax2_tx);
diff --git a/htdocs/commande/contact.php b/htdocs/commande/contact.php
index bc257f3ac0558391f7c7ef4604491b7ee1756c44..fe37a630c5dbd3be130d3f35b0d06bc108d30812 100644
--- a/htdocs/commande/contact.php
+++ b/htdocs/commande/contact.php
@@ -107,13 +107,14 @@ else if ($action == 'deletecontact' && $user->rights->commande->creer)
 		dol_print_error($db);
 	}
 }
-
+/*
 else if ($action == 'setaddress' && $user->rights->commande->creer)
 {
 	$object->fetch($id);
 	$result=$object->setDeliveryAddress($_POST['fk_address']);
 	if ($result < 0) dol_print_error($db,$object->error);
-}
+}*/
+
 
 /*
  * View
diff --git a/htdocs/compta/bank/card.php b/htdocs/compta/bank/card.php
index df6e6b1c8c83e3e4ae897d33130c9b1c39a073fa..5b3bb3a58fe35e679e40323d21d307ad104fe899 100644
--- a/htdocs/compta/bank/card.php
+++ b/htdocs/compta/bank/card.php
@@ -1,11 +1,11 @@
 <?php
 /* Copyright (C) 2002-2003	Rodolphe Quiedeville	<rodolphe@quiedeville.org>
- * Copyright (C) 2003		Jean-Louis Bergamo	<jlb@j1b.org>
- * Copyright (C) 2004-2016	Laurent Destailleur	<eldy@users.sourceforge.net>
- * Copyright (C) 2005-2009	Regis Houssin		<regis.houssin@capnetworks.com>
- * Copyright (C) 2014-2016	Alexandre Spangaro	<aspangaro.dolibarr@gmail.com>
- * Copyright (C) 2015       Jean-François Ferry	<jfefe@aternatik.fr>
- * Copyright (C) 2016       Marcos García       <marcosgdf@gmail.com>
+ * Copyright (C) 2003		Jean-Louis Bergamo		<jlb@j1b.org>
+ * Copyright (C) 2004-2016	Laurent Destailleur		<eldy@users.sourceforge.net>
+ * Copyright (C) 2005-2009	Regis Houssin			<regis.houssin@capnetworks.com>
+ * Copyright (C) 2014-2017	Alexandre Spangaro		<aspangaro@zendsi.com>
+ * Copyright (C) 2015		Jean-François Ferry		<jfefe@aternatik.fr>
+ * Copyright (C) 2016		Marcos García			<marcosgdf@gmail.com>
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -35,8 +35,8 @@ require_once DOL_DOCUMENT_ROOT . '/core/class/html.formbank.class.php';
 require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php';
 require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
 if (! empty($conf->categorie->enabled)) require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
-if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php';
 if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT . '/accountancy/class/html.formventilation.class.php';
+if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingaccount.class.php';
 
 $langs->load("banks");
 $langs->load("bills");
@@ -664,7 +664,10 @@ else
 		print '<tr class="liste_titre_add"><td class="titlefield">'.$langs->trans("AccountancyCode").'</td>';
 		print '<td>';
 		if (! empty($conf->accounting->enabled)) {
-		    print length_accountg($object->account_number).'</td></tr>';
+			$accountingaccount = new AccountingAccount($db);
+			$accountingaccount->fetch('',$object->account_number);
+
+			print $accountingaccount->getNomUrl(0,1,1,'',1);
 		} else {
 		    print $object->account_number;
 		}
@@ -683,13 +686,11 @@ else
 		
 		print '</table>';
 
-		
 		print '</div>';
 		print '<div class="fichehalfright">';
 		print '<div class="ficheaddleft">';
 		print '<div class="underbanner clearboth"></div>';
 
-
 		print '<table class="border centpercent">';
 		
         // Categories
@@ -703,8 +704,7 @@ else
 		print '<td>'.dol_htmlentitiesbr($object->comment).'</td></tr>';
 
 		print '</table>';
-		
-		
+
 		if ($object->type == Account::TYPE_SAVINGS || $object->type == Account::TYPE_CURRENT)
 		{
 		    print '<br>';
diff --git a/htdocs/compta/bank/index.php b/htdocs/compta/bank/index.php
index a92b23fc617db98b8866a80b283e1aca6dd98406..b808fa8f596a099244cba18198f15e80a04ed1f8 100644
--- a/htdocs/compta/bank/index.php
+++ b/htdocs/compta/bank/index.php
@@ -33,6 +33,7 @@ require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
 $langs->load("banks");
 $langs->load("categories");
 $langs->load("accountancy");
+$langs->load("compta");
 
 $action=GETPOST('action','alpha');
 $massaction=GETPOST('massaction','alpha');
@@ -87,6 +88,7 @@ $arrayfields=array(
     'b.label'=>array('label'=>$langs->trans("Label"), 'checked'=>1),
     'b.number'=>array('label'=>$langs->trans("AccountIdShort"), 'checked'=>1),
     'b.account_number'=>array('label'=>$langs->trans("AccountAccounting"), 'checked'=>$conf->accountancy->enabled),
+    'b.accountancy_journal'=>array('label'=>$langs->trans("AccountancyJournal"), 'checked'=>$conf->accountancy->enabled),
     'toreconcile'=>array('label'=>$langs->trans("TransactionsToConciliate"), 'checked'=>1),
     'b.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500),
     'b.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500),
@@ -139,7 +141,7 @@ $title=$langs->trans('BankAccounts');
 // Load array of financial accounts (opened by default)
 $accounts = array();
 
-$sql  = "SELECT rowid, label, courant, rappro, account_number, datec as date_creation, tms as date_update";
+$sql  = "SELECT rowid, label, courant, rappro, account_number, accountancy_journal, datec as date_creation, tms as date_update";
 // Add fields from extrafields
 foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key.' as options_'.$key : '');
 // Add fields from hooks
@@ -286,6 +288,7 @@ print '<div class="div-table-responsive">';
 print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n";
 
 print '<tr class="liste_titre_filter">';
+
 // Ref
 if (! empty($arrayfields['b.ref']['checked']))
 {
@@ -306,19 +309,25 @@ if (! empty($arrayfields['accountype']['checked']))
     print '<td class="liste_titre">';
     print '</td>';
 }
-// Number
+// Bank number
 if (! empty($arrayfields['b.number']['checked']))
 {
     print '<td class="liste_titre">';
     print '<input class="flat" size="6" type="text" name="search_number" value="'.$search_number.'">';
     print '</td>';
 }
-// Number
+// Account number
 if (! empty($arrayfields['b.account_number']['checked']))
 {
     print '<td class="liste_titre">';
     print '</td>';
 }
+// Accountancy journal
+if (! empty($arrayfields['b.accountancy_journal']['checked']))
+{
+    print '<td class="liste_titre">';
+    print '</td>';
+}
 // Transactions to reconcile
 if (! empty($arrayfields['toreconcile']['checked']))
 {
@@ -394,6 +403,7 @@ if (! empty($arrayfields['b.label']['checked']))          print_liste_field_titr
 if (! empty($arrayfields['accountype']['checked']))       print_liste_field_titre($arrayfields['accountype']['label'],$_SERVER["PHP_SELF"],'','',$param,'',$sortfield,$sortorder);
 if (! empty($arrayfields['b.number']['checked']))         print_liste_field_titre($arrayfields['b.number']['label'],$_SERVER["PHP_SELF"],'b.number','',$param,'',$sortfield,$sortorder);
 if (! empty($arrayfields['b.account_number']['checked'])) print_liste_field_titre($arrayfields['b.account_number']['label'],$_SERVER["PHP_SELF"],'b.account_number','',$param,'',$sortfield,$sortorder);
+if (! empty($arrayfields['b.accountancy_journal']['checked'])) print_liste_field_titre($arrayfields['b.accountancy_journal']['label'],$_SERVER["PHP_SELF"],'b.accountancy_journal','',$param,'',$sortfield,$sortorder);
 if (! empty($arrayfields['toreconcile']['checked']))      print_liste_field_titre($arrayfields['toreconcile']['label'],$_SERVER["PHP_SELF"],'','',$param,'align="center"',$sortfield,$sortorder);
 // Extra fields
 if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label))
@@ -482,6 +492,14 @@ foreach ($accounts as $key=>$type)
 	    if (! $i) $totalarray['nbfield']++;
     }
     
+    // Accountancy journal
+    if (! empty($arrayfields['b.accountancy_journal']['checked']))
+    {
+        include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
+        print '<td>'.length_accountg($acc->accountancy_journal).'</td>';
+	    if (! $i) $totalarray['nbfield']++;
+    }
+    
     // Transactions to reconcile
     if (! empty($arrayfields['toreconcile']['checked']))
     {
diff --git a/htdocs/compta/facture/card.php b/htdocs/compta/facture/card.php
index b516ccd2f23660c18bc07a7b41882690e96f48d2..897b61a0e60612dd9f37ea1beae30277601e4811 100644
--- a/htdocs/compta/facture/card.php
+++ b/htdocs/compta/facture/card.php
@@ -611,7 +611,9 @@ if (empty($reshook))
 		{
 			$db->begin();
 
-			// Boucle sur chaque taux de tva
+			$amount_ht = $amount_tva = $amount_ttc = array();
+			
+			// Loop on each vat rate
 			$i = 0;
 			foreach ($object->lines as $line)
 			{
@@ -630,20 +632,19 @@ if (empty($reshook))
 				$discount->description = '(CREDIT_NOTE)';
 			elseif ($object->type == Facture::TYPE_DEPOSIT)
 				$discount->description = '(DEPOSIT)';
-			elseif ($object->type == Facture::TYPE_STANDARD)
+			elseif ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_SITUATION)
 				$discount->description = '(EXCESS RECEIVED)';
 			else {
 				setEventMessages($langs->trans('CantConvertToReducAnInvoiceOfThisType'), null, 'errors');
 			}
-			$discount->tva_tx = abs($object->total_ttc);
 			$discount->fk_soc = $object->socid;
 			$discount->fk_facture_source = $object->id;
 
 			$error = 0;
 			
-			if ($object->type == Facture::TYPE_STANDARD) {
-				
-				// If we're on a standard invoice, we have to get excess received to create it in TTC wuthout VAT
+			if ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_SITUATION) 
+			{
+				// If we're on a standard invoice, we have to get excess received to create a discount in TTC without VAT
 				
 				$sql = 'SELECT SUM(pf.amount) as total_paiements
 						FROM llx_c_paiement as c, llx_paiement_facture as pf, llx_paiement as p
@@ -663,8 +664,9 @@ if (empty($reshook))
 					$error++;
 				}
 				
-			} else {
-			
+			}
+			if ($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT)
+			{
 				foreach ($amount_ht as $tva_tx => $xxx)
 				{
 					$discount->amount_ht = abs($amount_ht[$tva_tx]);
@@ -871,19 +873,6 @@ if (empty($reshook))
 	                    $object->addline($langs->trans('invoiceAvoirLineWithPaymentRestAmount'),$remain_to_pay,1,0,0,0,0,0,'','','TTC');
 	                }
 	            }
-
-				// Add predefined lines
-				/*
-	             TODO delete
-	             for($i = 1; $i <= $NBLINES; $i ++) {
-					if ($_POST['idprod' . $i]) {
-						$product = new Product($db);
-						$product->fetch($_POST['idprod' . $i]);
-						$startday = dol_mktime(12, 0, 0, $_POST['date_start' . $i . 'month'], $_POST['date_start' . $i . 'day'], $_POST['date_start' . $i . 'year']);
-						$endday = dol_mktime(12, 0, 0, $_POST['date_end' . $i . 'month'], $_POST['date_end' . $i . 'day'], $_POST['date_end' . $i . 'year']);
-						$result = $object->addline($product->description, $product->price, $_POST['qty' . $i], $product->tva_tx, $product->localtax1_tx, $product->localtax2_tx, $_POST['idprod' . $i], $_POST['remise_percent' . $i], $startday, $endday, 0, 0, '', $product->price_base_type, $product->price_ttc, $product->type);
-					}
-				}*/
 			}
 		}
 
@@ -1077,7 +1066,7 @@ if (empty($reshook))
 							{
 								if ($typeamount == 'amount')
 								{
-									$amountdeposit[] = $valuedeposit;
+									$amountdeposit[0] = $valuedeposit;
 								}
 								else
 								{
@@ -1095,9 +1084,11 @@ if (empty($reshook))
 										}
 
 										if ($totalamount != 0) {
-											$amountdeposit[$lines[$i]->tva] = ($totalamount * $valuedeposit) / 100;
+										    $tva_tx = $lines[$i]->tva_tx;
+										    if (! empty($lines[$i]->vat_src_code) && ! preg_match('/\(/', $tva_tx)) $tva_tx .= ' ('.$lines[$i]->vat_src_code.')';
+											$amountdeposit[$tva_tx] = ($totalamount * $valuedeposit) / 100;
 										} else {
-											$amountdeposit[] = 0;
+											$amountdeposit[0] = 0;
 										}
 									} else {
 										setEventMessages($srcobject->error, $srcobject->errors, 'errors');
@@ -1222,11 +1213,15 @@ if (empty($reshook))
 											$array_options = $lines[$i]->array_options;
 										}
 
-										// View third's localtaxes for now
-										$localtax1_tx = get_localtax($lines[$i]->tva_tx, 1, $object->thirdparty);
-										$localtax2_tx = get_localtax($lines[$i]->tva_tx, 2, $object->thirdparty);
+										$tva_tx = $lines[$i]->tva_tx;
+										if (! empty($lines[$i]->vat_src_code) && ! preg_match('/\(/', $tva_tx)) $tva_tx .= ' ('.$lines[$i]->vat_src_code.')';
+										
+										// View third's localtaxes for NOW and do not use value from origin.
+										// TODO Is this really what we want ? Yes if source if template invoice but what if proposal or order ?
+										$localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty);
+										$localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty);
 
-										$result = $object->addline($desc, $lines[$i]->subprice, $lines[$i]->qty, $lines[$i]->tva_tx, $localtax1_tx, $localtax2_tx, $lines[$i]->fk_product, $lines[$i]->remise_percent, $date_start, $date_end, 0, $lines[$i]->info_bits, $lines[$i]->fk_remise_except, 'HT', 0, $product_type, $lines[$i]->rang, $lines[$i]->special_code, $object->origin, $lines[$i]->rowid, $fk_parent_line, $lines[$i]->fk_fournprice, $lines[$i]->pa_ht, $label, $array_options, $lines[$i]->situation_percent, $lines[$i]->fk_prev_id, $lines[$i]->fk_unit);
+										$result = $object->addline($desc, $lines[$i]->subprice, $lines[$i]->qty, $tva_tx, $localtax1_tx, $localtax2_tx, $lines[$i]->fk_product, $lines[$i]->remise_percent, $date_start, $date_end, 0, $lines[$i]->info_bits, $lines[$i]->fk_remise_except, 'HT', 0, $product_type, $lines[$i]->rang, $lines[$i]->special_code, $object->origin, $lines[$i]->rowid, $fk_parent_line, $lines[$i]->fk_fournprice, $lines[$i]->pa_ht, $label, $array_options, $lines[$i]->situation_percent, $lines[$i]->fk_prev_id, $lines[$i]->fk_unit);
 
 										if ($result > 0) {
 											$lineid = $result;
@@ -3634,8 +3629,7 @@ else if ($id > 0 || ! empty($ref))
             print '<tr class="liste_titre">';
             print '<td>' . $langs->trans('ListOfNextSituationInvoices') . '</td>';
             print '<td></td>';
-            if (! empty($conf->banque->enabled))
-                print '<td align="right"></td>';
+            if (! empty($conf->banque->enabled)) print '<td align="right"></td>';
             print '<td align="right">' . $langs->trans('AmountHT') . '</td>';
             print '<td align="right">' . $langs->trans('AmountTTC') . '</td>';
             print '<td width="18">&nbsp;</td>';
@@ -3651,8 +3645,7 @@ else if ($id > 0 || ! empty($ref))
                 print '<tr ' . $bc[$var] . '>';
                 print '<td>' . $next_invoice->getNomUrl(1) . '</td>';
                 print '<td></td>';
-                if (! empty($conf->banque->enabled))
-                    print '<td align="right"></td>';
+                if (! empty($conf->banque->enabled)) print '<td align="right"></td>';
                 print '<td align="right">' . price($next_invoice->total_ht) . '</td>';
                 print '<td align="right">' . price($next_invoice->total_ttc) . '</td>';
                 print '<td align="right">' . $next_invoice->getLibStatut(3, $totalpaye) . '</td>';
@@ -3663,8 +3656,7 @@ else if ($id > 0 || ! empty($ref))
             
             print '<tr ' . $bc[$var] . '>';
             print '<td colspan="2" align="right"></td>';
-	    if (! empty($conf->banque->enabled))
-		print '<td align="right"></td>';
+		    if (! empty($conf->banque->enabled)) print '<td align="right"></td>';
 
             print '<td align="right"><b>' . price($total_next_ht) . '</b></td>';
             print '<td align="right"><b>' . price($total_next_ttc) . '</b></td>';
diff --git a/htdocs/compta/facture/class/facture.class.php b/htdocs/compta/facture/class/facture.class.php
index 4b9ced1c4c0f03d2f3333ad4affdc236a52b87aa..f3f0fd543fa608f86cce7611e64f7e1cc7c9790e 100644
--- a/htdocs/compta/facture/class/facture.class.php
+++ b/htdocs/compta/facture/class/facture.class.php
@@ -951,6 +951,7 @@ class Facture extends CommonInvoice
 			$line->total_ht			= $object->lines[$i]->total_ht;
 			$line->total_tva		= $object->lines[$i]->total_tva;
 			$line->total_ttc		= $object->lines[$i]->total_ttc;
+			$line->vat_src_code  	= $object->lines[$i]->vat_src_code;
 			$line->tva_tx			= $object->lines[$i]->tva_tx;
 			$line->localtax1_tx		= $object->lines[$i]->localtax1_tx;
 			$line->localtax2_tx		= $object->lines[$i]->localtax2_tx;
@@ -1550,6 +1551,7 @@ class Facture extends CommonInvoice
 			$facligne->fk_facture=$this->id;
 			$facligne->fk_remise_except=$remise->id;
 			$facligne->desc=$remise->description;   	// Description ligne
+			$facligne->vat_src_code=$remise->vat_src_code;
 			$facligne->tva_tx=$remise->tva_tx;
 			$facligne->subprice=-$remise->amount_ht;
 			$facligne->fk_product=0;					// Id produit predefini
@@ -2398,7 +2400,7 @@ class Facture extends CommonInvoice
 	 * 		@param    	string		$desc            	Description of line
 	 * 		@param    	double		$pu_ht              Unit price without tax (> 0 even for credit note)
 	 * 		@param    	double		$qty             	Quantity
-	 * 		@param    	double		$txtva           	Force Vat rate, -1 for auto
+	 * 		@param    	double		$txtva           	Force Vat rate, -1 for auto (Can contain the vat_src_code too with syntax '9.9 (CODE)')
 	 * 		@param		double		$txlocaltax1		Local tax 1 rate (deprecated)
 	 *  	@param		double		$txlocaltax2		Local tax 2 rate (deprecated)
 	 *		@param    	int			$fk_product      	Id of predefined product/service
@@ -3511,10 +3513,11 @@ class Facture extends CommonInvoice
 
 
 	/**
-	 *	Create a withdrawal request for a standing order
+	 *	Create a withdrawal request for a standing order.
+	 *  Use the remain to pay excluding all existing open direct debit requests.
 	 *
-	 *	@param      User	$fuser       User asking standing order
-	 *  @param		float	$amount		Amount we request withdraw for
+	 *	@param      User	$fuser      User asking the direct debit transfer
+	 *  @param		float	$amount		Amount we request direct debit for
 	 *	@return     int         		<0 if KO, >0 if OK
 	 */
 	function demande_prelevement($fuser, $amount=0)
@@ -4225,7 +4228,7 @@ class FactureLigne extends CommonInvoiceLine
 	 */
 	function fetch($rowid)
 	{
-		$sql = 'SELECT fd.rowid, fd.fk_facture, fd.fk_parent_line, fd.fk_product, fd.product_type, fd.label as custom_label, fd.description, fd.price, fd.qty, fd.tva_tx,';
+		$sql = 'SELECT fd.rowid, fd.fk_facture, fd.fk_parent_line, fd.fk_product, fd.product_type, fd.label as custom_label, fd.description, fd.price, fd.qty, fd.vat_src_code, fd.tva_tx,';
 		$sql.= ' fd.localtax1_tx, fd. localtax2_tx, fd.remise, fd.remise_percent, fd.fk_remise_except, fd.subprice,';
 		$sql.= ' fd.date_start as date_start, fd.date_end as date_end, fd.fk_product_fournisseur_price as fk_fournprice, fd.buy_price_ht as pa_ht,';
 		$sql.= ' fd.info_bits, fd.special_code, fd.total_ht, fd.total_tva, fd.total_ttc, fd.total_localtax1, fd.total_localtax2, fd.rang,';
@@ -4253,6 +4256,7 @@ class FactureLigne extends CommonInvoiceLine
 			$this->desc					= $objp->description;
 			$this->qty					= $objp->qty;
 			$this->subprice				= $objp->subprice;
+			$this->vat_src_code  		= $objp->vat_src_code;
 			$this->tva_tx				= $objp->tva_tx;
 			$this->localtax1_tx			= $objp->localtax1_tx;
 			$this->localtax2_tx			= $objp->localtax2_tx;
diff --git a/htdocs/compta/facture/fiche-rec.php b/htdocs/compta/facture/fiche-rec.php
index 706807c8f0247e179f1e13a73170b24bbcc8ad9a..cb60b8bcff5d10589e699b0bcc174fc2bca71f27 100644
--- a/htdocs/compta/facture/fiche-rec.php
+++ b/htdocs/compta/facture/fiche-rec.php
@@ -35,8 +35,9 @@ require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
 if (! empty($conf->projet->enabled)) {
     require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
-    require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php';
+    //require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php';
 }
+require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php';
 require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
 require_once DOL_DOCUMENT_ROOT . '/core/lib/invoice.lib.php';
 
@@ -891,7 +892,6 @@ if ($action == 'create')
 
 	$object = new Facture($db);   // Source invoice
 	$product_static = new Product($db);
-	$formproject = new FormProjets($db);
 
 	if ($object->fetch($id, $ref) > 0)
 	{
diff --git a/htdocs/compta/paiement.php b/htdocs/compta/paiement.php
index 96f77e857581cc8d0e0065de82dd7c26af6abf95..8cd924a0df82cc644db7d37942b02c4536beae70 100644
--- a/htdocs/compta/paiement.php
+++ b/htdocs/compta/paiement.php
@@ -1,6 +1,6 @@
 <?php
 /* Copyright (C) 2001-2006 Rodolphe Quiedeville  <rodolphe@quiedeville.org>
- * Copyright (C) 2004-2016 Laurent Destailleur   <eldy@users.sourceforge.net>
+ * Copyright (C) 2004-2017 Laurent Destailleur   <eldy@users.sourceforge.net>
  * Copyright (C) 2005      Marc Barilley / Ocebo <marc@ocebo.com>
  * Copyright (C) 2005-2012 Regis Houssin         <regis.houssin@capnetworks.com>
  * Copyright (C) 2007      Franky Van Liedekerke <franky.van.liedekerke@telenet.be>
@@ -221,7 +221,7 @@ if (empty($reshook))
 	    $db->begin();
 
 	    // Clean parameters amount if payment is for a credit note
-	    if (GETPOST('type') == 2)
+	    if (GETPOST('type') == Facture::TYPE_CREDIT_NOTE)
 	    {
 		    foreach ($amounts as $key => $value)	// How payment is dispatch
 		    {
@@ -249,7 +249,7 @@ if (empty($reshook))
 	    // Creation of payment line
 	    $paiement = new Paiement($db);
 	    $paiement->datepaye     = $datepaye;
-	    $paiement->amounts      = $amounts;   // Array with all payments dispatching
+	    $paiement->amounts      = $amounts;   // Array with all payments dispatching with invoice id
 	    $paiement->multicurrency_amounts = $multicurrency_amounts;   // Array with all payments dispatching
 	    $paiement->paiementid   = dol_getIdFromCode($db,GETPOST('paiementcode'),'c_paiement');
 	    $paiement->num_paiement = GETPOST('num_paiement');
@@ -257,7 +257,7 @@ if (empty($reshook))
 
 	    if (! $error)
 	    {
-	    	$paiement_id = $paiement->create($user, (GETPOST('closepaidinvoices')=='on'?1:0));
+	    	$paiement_id = $paiement->create($user, (GETPOST('closepaidinvoices')=='on'?1:0));    // This include closing invoices
 	    	if ($paiement_id < 0)
 	        {
 	            setEventMessages($paiement->error, $paiement->errors, 'errors');
@@ -268,7 +268,7 @@ if (empty($reshook))
 	    if (! $error)
 	    {
 	    	$label='(CustomerInvoicePayment)';
-	    	if (GETPOST('type') == 2) $label='(CustomerInvoicePaymentBack)';
+	    	if (GETPOST('type') == Facture::TYPE_CREDIT_NOTE) $label='(CustomerInvoicePaymentBack)';  // Refund of a credit note
 	        $result=$paiement->addPaymentToBank($user,'payment',$label,GETPOST('accountid'),GETPOST('chqemetteur'),GETPOST('chqbank'));
 	        if ($result < 0)
 	        {
@@ -281,7 +281,7 @@ if (empty($reshook))
 	    {
 	        $db->commit();
 
-	        // If payment dispatching on more than one invoice, we keep on summary page, otherwise go on invoice card
+	        // If payment dispatching on more than one invoice, we keep on summary page, otherwise jump on invoice card
 	        $invoiceid=0;
 	        foreach ($paiement->amounts as $key => $amount)
 	        {
@@ -309,7 +309,7 @@ if (empty($reshook))
  * View
  */
 
-llxHeader();
+llxHeader('', $langs->trans("Payment"));
 
 $form=new Form($db);
 
@@ -324,8 +324,8 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie
 		$facture->fetch_thirdparty();
 
 		$title='';
-		if ($facture->type != 2) $title.=$langs->trans("EnterPaymentReceivedFromCustomer");
-		if ($facture->type == 2) $title.=$langs->trans("EnterPaymentDueToCustomer");
+		if ($facture->type != Facture::TYPE_CREDIT_NOTE) $title.=$langs->trans("EnterPaymentReceivedFromCustomer");
+		if ($facture->type == Facture::TYPE_CREDIT_NOTE) $title.=$langs->trans("EnterPaymentDueToCustomer");
 		print load_fiche_titre($title);
 
 		// Initialize data for confirmation (this is used because data can be change during confirmation)
@@ -347,7 +347,7 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie
 		}
 
 		// Add realtime total information
-		if ($conf->use_javascript_ajax)
+		if (! empty($conf->use_javascript_ajax))
 		{
 			print "\n".'<script type="text/javascript" language="javascript">';
 			print '$(document).ready(function () {
@@ -369,7 +369,7 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie
 			                    }
             					if ($(\'#fieldchqemetteur\').val() == \'\')
             					{
-            						var emetteur = ('.$facture->type.' == 2) ? \''.dol_escape_js(dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_NOM)).'\' : jQuery(\'#thirdpartylabel\').val();
+            						var emetteur = ('.$facture->type.' == '.Facture::TYPE_CREDIT_NOTE.') ? \''.dol_escape_js(dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_NOM)).'\' : jQuery(\'#thirdpartylabel\').val();
             						$(\'#fieldchqemetteur\').val(emetteur);
             					}
             				}
@@ -437,14 +437,14 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie
 			';
 
 			print '	});'."\n";
-			if (!empty($conf->use_javascript_ajax)){
-				//Add js for AutoFill
-				print ' $(document).ready(function () {';
-				print ' 	$(".AutoFillAmout").on(\'click touchstart\', function(){
-								$("input[name="+$(this).data(\'rowname\')+"]").val($(this).data("value")).trigger("change");
-							});';
-				print '	});'."\n";
-			}
+
+			//Add js for AutoFill
+			print ' $(document).ready(function () {';
+			print ' 	$(".AutoFillAmout").on(\'click touchstart\', function(){
+							$("input[name="+$(this).data(\'rowname\')+"]").val($(this).data("value")).trigger("change");
+						});';
+			print '	});'."\n";
+
 			print '	</script>'."\n";
 		}
 
diff --git a/htdocs/compta/paiement/cheque/card.php b/htdocs/compta/paiement/cheque/card.php
index 625b2be518eafe7a5cf6fafba24c5918cdf4bc57..eed3a79335c3cc4efd5d2cf31125f7c1abb43f83 100644
--- a/htdocs/compta/paiement/cheque/card.php
+++ b/htdocs/compta/paiement/cheque/card.php
@@ -334,7 +334,7 @@ else
 	//  $head[$h][1] = $langs->trans("Info");
 	//  $h++;
 
-	dol_fiche_head($head, $hselected, $langs->trans("Cheques"),0,'payment');
+	dol_fiche_head($head, $hselected, $langs->trans("Cheques"), -1, 'payment');
 
 	/*
 	 * Confirmation de la suppression du bordereau
@@ -476,8 +476,7 @@ if ($action == 'new')
         print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n";
 		
 		print '<tr class="liste_titre">';
-		print '<td style="min-width: 120px">'.$langs->trans("DateChequeReceived").' ';
-		print "</td>\n";
+		print '<td style="min-width: 120px">'.$langs->trans("DateChequeReceived").'</td>'."\n";
 		print '<td style="min-width: 120px">'.$langs->trans("ChequeNumber")."</td>\n";
 		print '<td style="min-width: 200px">'.$langs->trans("CheckTransmitter")."</td>\n";
 		print '<td style="min-width: 200px">'.$langs->trans("Bank")."</td>\n";
@@ -487,59 +486,57 @@ if ($action == 'new')
 		print '<td align="center" width="100px">'.$langs->trans("Select")."<br>";
 		if ($conf->use_javascript_ajax) print '<a href="#" id="checkall_'.$bid.'">'.$langs->trans("All").'</a> / <a href="#" id="checknone_'.$bid.'">'.$langs->trans("None").'</a>';
 		print '</td>';
-
 		print "</tr>\n";
 
-		$var=true;
-
-		foreach ($lines[$bid] as $lid => $value)
+		if (count($lines[$bid]))
 		{
-			
-
-			$account_id = $bid;
-			if (! isset($accounts[$bid]))
-				$accounts[$bid]=0;
-			$accounts[$bid] += 1;
-
-			print '<tr class="oddeven">';
-			print '<td>'.dol_print_date($value["date"],'day').'</td>';
-			print '<td>'.$value["numero"]."</td>\n";
-			print '<td>'.$value["emetteur"]."</td>\n";
-			print '<td>'.$value["banque"]."</td>\n";
-			print '<td align="right">'.price($value["amount"], 0, $langs, 1, -1, -1, $conf->currency).'</td>';
-
-			// Link to payment
-			print '<td align="center">';
-			$paymentstatic->id=$value["paymentid"];
-			$paymentstatic->ref=$value["paymentid"];
-			if ($paymentstatic->id)
-			{
-				print $paymentstatic->getNomUrl(1);
-			}
-			else
-			{
-				print '&nbsp;';
-			}
-			print '</td>';
-			// Link to bank transaction
-			print '<td align="center">';
-			$accountlinestatic->rowid=$value["id"];
-			if ($accountlinestatic->rowid)
-			{
-				print $accountlinestatic->getNomUrl(1);
-			}
-			else
-			{
-				print '&nbsp;';
-			}
-			print '</td>';
-
-			print '<td align="center">';
-			print '<input id="'.$value["id"].'" class="flat checkforremise_'.$bid.'" checked type="checkbox" name="toRemise[]" value="'.$value["id"].'">';
-			print '</td>' ;
-			print '</tr>';
-
-			$i++;
+    		foreach ($lines[$bid] as $lid => $value)
+    		{
+    			$account_id = $bid;
+    			if (! isset($accounts[$bid]))
+    				$accounts[$bid]=0;
+    			$accounts[$bid] += 1;
+
+    			print '<tr class="oddeven">';
+    			print '<td>'.dol_print_date($value["date"],'day').'</td>';
+    			print '<td>'.$value["numero"]."</td>\n";
+    			print '<td>'.$value["emetteur"]."</td>\n";
+    			print '<td>'.$value["banque"]."</td>\n";
+    			print '<td align="right">'.price($value["amount"], 0, $langs, 1, -1, -1, $conf->currency).'</td>';
+
+    			// Link to payment
+    			print '<td align="center">';
+    			$paymentstatic->id=$value["paymentid"];
+    			$paymentstatic->ref=$value["paymentid"];
+    			if ($paymentstatic->id)
+    			{
+    				print $paymentstatic->getNomUrl(1);
+    			}
+    			else
+    			{
+    				print '&nbsp;';
+    			}
+    			print '</td>';
+    			// Link to bank transaction
+    			print '<td align="center">';
+    			$accountlinestatic->rowid=$value["id"];
+    			if ($accountlinestatic->rowid)
+    			{
+    				print $accountlinestatic->getNomUrl(1);
+    			}
+    			else
+    			{
+    				print '&nbsp;';
+    			}
+    			print '</td>';
+    
+    			print '<td align="center">';
+    			print '<input id="'.$value["id"].'" class="flat checkforremise_'.$bid.'" checked type="checkbox" name="toRemise[]" value="'.$value["id"].'">';
+    			print '</td>' ;
+    			print '</tr>';
+    
+    			$i++;
+    		}
 		}
 		print "</table>";
         print '</div>';
@@ -686,65 +683,75 @@ else
 		print_liste_field_titre('');
 		print "</tr>\n";
 		$i=1;
-		$var=false;
-		while ($objp = $db->fetch_object($resql))
-		{
-			$account_id = $objp->bid;
-			if (! isset($accounts[$objp->bid]))
-				$accounts[$objp->bid]=0;
-			$accounts[$objp->bid] += 1;
-
-			print '<tr class="oddeven">';
-			print '<td align="center">'.$i.'</td>';
-			print '<td align="center">'.dol_print_date($db->jdate($objp->date),'day').'</td>';	// Date operation
-			print '<td align="center">'.($objp->num_chq?$objp->num_chq:'&nbsp;').'</td>';
-			print '<td>'.dol_trunc($objp->emetteur,24).'</td>';
-			print '<td>'.dol_trunc($objp->banque,24).'</td>';
-			print '<td align="right">'.price($objp->amount).'</td>';
-			// Link to payment
-			print '<td align="center">';
-			$paymentstatic->id=$objp->pid;
-			$paymentstatic->ref=$objp->pid;
-			if ($paymentstatic->id)
-			{
-				print $paymentstatic->getNomUrl(1);
-			}
-			else
-			{
-				print '&nbsp;';
-			}
-			print '</td>';
-			// Link to bank transaction
-			print '<td align="center">';
-			$accountlinestatic->rowid=$objp->rowid;
-			if ($accountlinestatic->rowid)
-			{
-				print $accountlinestatic->getNomUrl(1);
-			}
-			else
-			{
-				print '&nbsp;';
-			}
-			print '</td>';
-			// Action button
-			print '<td align="right">';
-			if ($object->statut == 0)
-			{
-				print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=remove&amp;lineid='.$objp->rowid.'">'.img_delete().'</a>';
-			}
-   			if ($object->statut == 1 && $objp->statut != 2)
-   			{
-   				print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=reject_check&amp;lineid='.$objp->rowid.'">'.img_picto($langs->trans("RejectCheck"),'disable').'</a>';
-   			}
-			if ($objp->statut == 2) 
-			{
-				print ' &nbsp; '.img_picto($langs->trans('CheckRejected'),'statut8').'</a>';
-			}
-		    print '</td>';
-			print '</tr>';
-			
-			$i++;
-		}
+
+        if ($num > 0)
+        {
+    		while ($objp = $db->fetch_object($resql))
+    		{
+    			$account_id = $objp->bid;
+    			if (! isset($accounts[$objp->bid]))
+    				$accounts[$objp->bid]=0;
+    			$accounts[$objp->bid] += 1;
+    
+    			print '<tr class="oddeven">';
+    			print '<td align="center">'.$i.'</td>';
+    			print '<td align="center">'.dol_print_date($db->jdate($objp->date),'day').'</td>';	// Date operation
+    			print '<td align="center">'.($objp->num_chq?$objp->num_chq:'&nbsp;').'</td>';
+    			print '<td>'.dol_trunc($objp->emetteur,24).'</td>';
+    			print '<td>'.dol_trunc($objp->banque,24).'</td>';
+    			print '<td align="right">'.price($objp->amount).'</td>';
+    			// Link to payment
+    			print '<td align="center">';
+    			$paymentstatic->id=$objp->pid;
+    			$paymentstatic->ref=$objp->pid;
+    			if ($paymentstatic->id)
+    			{
+    				print $paymentstatic->getNomUrl(1);
+    			}
+    			else
+    			{
+    				print '&nbsp;';
+    			}
+    			print '</td>';
+    			// Link to bank transaction
+    			print '<td align="center">';
+    			$accountlinestatic->rowid=$objp->rowid;
+    			if ($accountlinestatic->rowid)
+    			{
+    				print $accountlinestatic->getNomUrl(1);
+    			}
+    			else
+    			{
+    				print '&nbsp;';
+    			}
+    			print '</td>';
+    			// Action button
+    			print '<td align="right">';
+    			if ($object->statut == 0)
+    			{
+    				print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=remove&amp;lineid='.$objp->rowid.'">'.img_delete().'</a>';
+    			}
+       			if ($object->statut == 1 && $objp->statut != 2)
+       			{
+       				print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=reject_check&amp;lineid='.$objp->rowid.'">'.img_picto($langs->trans("RejectCheck"),'disable').'</a>';
+       			}
+    			if ($objp->statut == 2) 
+    			{
+    				print ' &nbsp; '.img_picto($langs->trans('CheckRejected'),'statut8').'</a>';
+    			}
+    		    print '</td>';
+    			print '</tr>';
+    			
+    			$i++;
+    		}
+        }
+        else
+        {
+            print '<td colspan="8" class="opacitymedium">';
+            print $langs->trans("None");
+            print '</td>';
+        }
+                
 		print "</table>";
 		print "</div>";
 	}
diff --git a/htdocs/compta/paiement/cheque/index.php b/htdocs/compta/paiement/cheque/index.php
index 2d77cb710613bec28f22ce10803c2c65cbf0c6b1..97dc3c1674f324eb493faa3d2661061dfb76337f 100644
--- a/htdocs/compta/paiement/cheque/index.php
+++ b/htdocs/compta/paiement/cheque/index.php
@@ -50,8 +50,6 @@ llxHeader('',$langs->trans("ChequesArea"));
 
 print load_fiche_titre($langs->trans("ChequesArea"));
 
-//print '<table border="0" width="100%" class="notopnoleftnoright">';
-//print '<tr><td valign="top" width="30%" class="notopnoleft">';
 print '<div class="fichecenter"><div class="fichethirdleft">';
 
 $sql = "SELECT count(b.rowid)";
@@ -90,7 +88,6 @@ else
 }
 
 
-//print '</td><td valign="top" width="70%" class="notopnoleftnoright">';
 print '</div><div class="fichetwothirdright"><div class="ficheaddleft">';
 
 $max=10;
@@ -98,15 +95,13 @@ $max=10;
 $sql = "SELECT bc.rowid, bc.date_bordereau as db, bc.amount, bc.ref as ref";
 $sql.= ", bc.statut, bc.nbcheque";
 $sql.= ", ba.label, ba.rowid as bid";
-$sql.= " FROM ".MAIN_DB_PREFIX."bordereau_cheque as bc";
-$sql.= ", ".MAIN_DB_PREFIX."bank_account as ba";
+$sql.= " FROM ".MAIN_DB_PREFIX."bordereau_cheque as bc, ".MAIN_DB_PREFIX."bank_account as ba";
 $sql.= " WHERE ba.rowid = bc.fk_bank_account";
 $sql.= " AND bc.entity = ".$conf->entity;
 $sql.= " ORDER BY bc.date_bordereau DESC, rowid DESC";
 $sql.= $db->plimit($max);
 
 $resql = $db->query($sql);
-
 if ($resql)
 {
 	print '<table class="noborder" width="100%">';
@@ -128,9 +123,8 @@ if ($resql)
 
 		$accountstatic->id=$objp->bid;
 		$accountstatic->label=$objp->label;
-
 		
-		print "<tr ".$bc[$var].">\n";
+		print '<tr class="oddeven">'."\n";
 
 		print '<td>'.$checkdepositstatic->getNomUrl(1).'</td>';
 		print '<td>'.dol_print_date($db->jdate($objp->db),'day').'</td>';
@@ -142,15 +136,15 @@ if ($resql)
 		print '</tr>';
 	}
 	print "</table>";
+
 	$db->free($resql);
 }
 else
 {
-  dol_print_error($db);
+    dol_print_error($db);
 }
 
 
-//print "</td></tr></table>\n";
 print '</div></div></div>';
 
 llxFooter();
diff --git a/htdocs/compta/paiement/class/paiement.class.php b/htdocs/compta/paiement/class/paiement.class.php
index 53035dca96f669061fcb578067d786319508c740..03a7759e52c7ad402af13f42c937268134dd610f 100644
--- a/htdocs/compta/paiement/class/paiement.class.php
+++ b/htdocs/compta/paiement/class/paiement.class.php
@@ -255,7 +255,7 @@ class Paiement extends CommonObject
                                 {
                                     if (! empty($conf->prelevement->enabled))
                                     {
-                                        // TODO Check if this payment has a withdraw request
+                                        // FIXME Check if this invoice has a withdraw request
                                         // if not, $mustwait++;      // This will disable automatic close on invoice to allow to process
                                     }
                                 }
@@ -275,11 +275,61 @@ class Paiement extends CommonObject
                             else if ($mustwait) dol_syslog("There is ".$mustwait." differed payment to process, we do nothing more.");
                             else
                             {
-                                $result=$invoice->set_paid($user,'','');
-                                if ($result<0)
+                                // If invoice is a down payment, we also convert down payment to discount
+                                if ($invoice->type == Facture::TYPE_DEPOSIT)
                                 {
-                                    $this->error=$invoice->error;
-                                    $error++;
+			                        $amount_ht = $amount_tva = $amount_ttc = array();
+			                         
+                                    // Loop on each vat rate
+                                    $i = 0;
+                                    foreach ($invoice->lines as $line)
+                                    {
+                                        if ($line->total_ht!=0)
+                                        { 	// no need to create discount if amount is null
+                                            $amount_ht[$line->tva_tx] += $line->total_ht;
+                                            $amount_tva[$line->tva_tx] += $line->total_tva;
+                                            $amount_ttc[$line->tva_tx] += $line->total_ttc;
+                                            $i ++;
+                                        }
+                                    }
+                                    
+                                    // Insert one discount by VAT rate category
+                                    $discount = new DiscountAbsolute($this->db);
+                                    $discount->description = '(DEPOSIT)';
+                                    $discount->fk_soc = $invoice->socid;
+                                    $discount->fk_facture_source = $invoice->id;
+                                
+                                    foreach ($amount_ht as $tva_tx => $xxx)
+                                    {
+                                        $discount->amount_ht = abs($amount_ht[$tva_tx]);
+                                        $discount->amount_tva = abs($amount_tva[$tva_tx]);
+                                        $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
+                                        $discount->tva_tx = abs($tva_tx);
+                            
+                                        $result = $discount->create($user);
+                                        if ($result < 0)
+                                        {
+                                            $error++;
+                                            break;
+                                        }
+                                    }
+                                    
+                                    if ($error)
+                                    {
+                                        setEventMessages($discount->error, $discount->errors, 'errors');
+                                        $error++;
+                                    }                                   
+                                }
+                                
+                                // Set invoice to paid
+                                if (! $error)
+                                {
+                                    $result=$invoice->set_paid($user,'','');
+                                    if ($result<0)
+                                    {
+                                        $this->error=$invoice->error;
+                                        $error++;
+                                    }
                                 }
                             }
 					    }
diff --git a/htdocs/contrat/card.php b/htdocs/contrat/card.php
index 0e5f3fca0938501fb7f911a775942f39c86ccd8e..e88372c483566fc61e658206c6902e38670ef177 100644
--- a/htdocs/contrat/card.php
+++ b/htdocs/contrat/card.php
@@ -332,14 +332,20 @@ if (empty($reshook))
 								else {
 								    $desc = dol_htmlentitiesbr($lines[$i]->desc);
 						        }
+
+								$txtva = $lines[$i]->vat_src_code ? $lines[$i]->tva_tx . ' (' .  $lines[$i]->vat_src_code . ')' : $lines[$i]->tva_tx;
+
+								// View third's localtaxes for now
+								$localtax1_tx = get_localtax($txtva, 1, $object->thirdparty);
+								$localtax2_tx = get_localtax($txtva, 2, $object->thirdparty);
 	
 			                    $result = $object->addline(
 					                $desc,
 					                $lines[$i]->subprice,
 					                $lines[$i]->qty,
-					                $lines[$i]->tva_tx,
-					                $lines[$i]->localtax1_tx,
-					                $lines[$i]->localtax2_tx,
+                                    $txtva,
+                                    $localtax1_tx,
+                                    $localtax2_tx,
 					                $lines[$i]->fk_product,
 					                $lines[$i]->remise_percent,
 					                $lines[$i]->date_start,
diff --git a/htdocs/contrat/class/contrat.class.php b/htdocs/contrat/class/contrat.class.php
index f0a34e982c82e6c5ad5bbe6c83ca2b2fc8fa5c6d..06ee9130ea9d7e7d5951860789b4c5b19a080d68 100644
--- a/htdocs/contrat/class/contrat.class.php
+++ b/htdocs/contrat/class/contrat.class.php
@@ -616,7 +616,7 @@ class Contrat extends CommonObject
 		
 		// Selectionne les lignes contrats liees a un produit
 		$sql = "SELECT p.label as product_label, p.description as product_desc, p.ref as product_ref,";
-		$sql.= " d.rowid, d.fk_contrat, d.statut, d.description, d.price_ht, d.tva_tx, d.localtax1_tx, d.localtax2_tx, d.qty, d.remise_percent, d.subprice, d.fk_product_fournisseur_price as fk_fournprice, d.buy_price_ht as pa_ht,";
+		$sql.= " d.rowid, d.fk_contrat, d.statut, d.description, d.price_ht, d.vat_src_code, d.tva_tx, d.localtax1_tx, d.localtax2_tx, d.localtax1_type, d.localtax2_type, d.qty, d.remise_percent, d.subprice, d.fk_product_fournisseur_price as fk_fournprice, d.buy_price_ht as pa_ht,";
 		$sql.= " d.total_ht,";
 		$sql.= " d.total_tva,";
 		$sql.= " d.total_localtax1,";
@@ -650,9 +650,12 @@ class Contrat extends CommonObject
 				$line->fk_contrat		= $objp->fk_contrat;
 				$line->desc				= $objp->description;  // Description ligne
 				$line->qty				= $objp->qty;
+				$line->vat_src_code 	= $objp->vat_src_code ;
 				$line->tva_tx			= $objp->tva_tx;
 				$line->localtax1_tx		= $objp->localtax1_tx;
 				$line->localtax2_tx		= $objp->localtax2_tx;
+				$line->localtax1_type	= $objp->localtax1_type;
+				$line->localtax2_type	= $objp->localtax2_type;
 				$line->subprice			= $objp->subprice;
 				$line->statut			= $objp->statut;
 				$line->remise_percent	= $objp->remise_percent;
@@ -2722,6 +2725,7 @@ class ContratLigne extends CommonObjectLine
 		$this->statut=(int) $this->statut;
 		$this->label=trim($this->label);
 		$this->description=trim($this->description);
+		$this->vat_src_code=trim($this->vat_src_code);
 		$this->tva_tx=trim($this->tva_tx);
 		$this->localtax1_tx=trim($this->localtax1_tx);
 		$this->localtax2_tx=trim($this->localtax2_tx);
@@ -2793,6 +2797,7 @@ class ContratLigne extends CommonObjectLine
 		$sql.= " date_ouverture=".($this->date_ouverture!=''?"'".$this->db->idate($this->date_ouverture)."'":"null").",";
 		$sql.= " date_fin_validite=".($this->date_fin_validite!=''?"'".$this->db->idate($this->date_fin_validite)."'":"null").",";
 		$sql.= " date_cloture=".($this->date_cloture!=''?"'".$this->db->idate($this->date_cloture)."'":"null").",";
+		$sql.= " vat_src_code='".$this->vat_src_code."',";
 		$sql.= " tva_tx='".$this->tva_tx."',";
 		$sql.= " localtax1_tx='".$this->localtax1_tx."',";
 		$sql.= " localtax2_tx='".$this->localtax2_tx."',";
@@ -2921,6 +2926,7 @@ class ContratLigne extends CommonObjectLine
 		$sql.= ") VALUES ($this->fk_contrat, '', '" . $this->db->escape($this->description) . "',";
 		$sql.= ($this->fk_product>0 ? $this->fk_product : "null").",";
 		$sql.= " '".$this->qty."',";
+		$sql.= " '".$this->vat_src_code."',";
 		$sql.= " '".$this->tva_tx."',";
 		$sql.= " '".$this->localtax1_tx."',";
 		$sql.= " '".$this->localtax2_tx."',";
diff --git a/htdocs/core/actions_massactions.inc.php b/htdocs/core/actions_massactions.inc.php
index 74badc6daae73a0612c72ca641ac1d2b8e8d72dc..58e47a29ec86a81b9d8f169c8712d2c1241325e5 100644
--- a/htdocs/core/actions_massactions.inc.php
+++ b/htdocs/core/actions_massactions.inc.php
@@ -406,60 +406,105 @@ if (! $error && $massaction == "builddoc" && $permtoread && ! GETPOST('button_se
         $outputlangs->setDefaultLang($newlang);
     }
 
-    // Create empty PDF
-    $pdf=pdf_getInstance();
-    if (class_exists('TCPDF'))
-    {
-        $pdf->setPrintHeader(false);
-        $pdf->setPrintFooter(false);
-    }
-    $pdf->SetFont(pdf_getPDFFont($outputlangs));
-
-    if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false);
-
-    // Add all others
-    foreach($files as $file)
-    {
-        // Charge un document PDF depuis un fichier.
-        $pagecount = $pdf->setSourceFile($file);
-        for ($i = 1; $i <= $pagecount; $i++)
-        {
-            $tplidx = $pdf->importPage($i);
-            $s = $pdf->getTemplatesize($tplidx);
-            $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L');
-            $pdf->useTemplate($tplidx);
-        }
+    if(!empty($conf->global->USE_PDFTK_FOR_PDF_CONCAT)) {
+    	// Create output dir if not exists
+	dol_mkdir($diroutputmassaction);
+
+	// Defined name of merged file
+	$filename=strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
+	$filename=preg_replace('/\s/','_',$filename);
+
+	// Save merged file
+	if ($filter=='paye:0')
+	{
+	if ($option=='late') $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
+	else $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
+	}
+	if ($year) $filename.='_'.$year;
+	if ($month) $filename.='_'.$month;
+
+    	if (count($files)>0)
+    	{
+    	
+    		$now=dol_now();
+    		$file=$diroutputmassaction.'/'.$filename.'_'.dol_print_date($now,'dayhourlog').'.pdf';
+    		
+    		$input_files = '';
+    		foreach($files as $f) {
+    			$input_files.=' '.escapeshellarg($f);
+    		}
+    		
+    		$cmd = 'pdftk '.$input_files.' cat output '.escapeshellarg($file);
+    		exec($cmd);
+    		
+    		if (! empty($conf->global->MAIN_UMASK))
+    			@chmod($file, octdec($conf->global->MAIN_UMASK));
+    			
+    			$langs->load("exports");
+    			setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs');
+    	}
+    	else
+    	{
+    		setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
+    	}
+    	
     }
-
-    // Create output dir if not exists
-    dol_mkdir($diroutputmassaction);
-
-    // Defined name of merged file
-    $filename=strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
-    $filename=preg_replace('/\s/','_',$filename);
-    
-    // Save merged file
-    if ($filter=='paye:0')
-    {
-        if ($option=='late') $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
-        else $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
-    }
-    if ($year) $filename.='_'.$year;
-    if ($month) $filename.='_'.$month;
-    if ($pagecount)
-    {
-        $now=dol_now();
-        $file=$diroutputmassaction.'/'.$filename.'_'.dol_print_date($now,'dayhourlog').'.pdf';
-        $pdf->Output($file,'F');
-        if (! empty($conf->global->MAIN_UMASK))
-            @chmod($file, octdec($conf->global->MAIN_UMASK));
-
-            $langs->load("exports");
-            setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs');
-    }
-    else
-    {
-        setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
+    else {
+	    // Create empty PDF
+	    $pdf=pdf_getInstance();
+	    if (class_exists('TCPDF'))
+	    {
+		$pdf->setPrintHeader(false);
+		$pdf->setPrintFooter(false);
+	    }
+	    $pdf->SetFont(pdf_getPDFFont($outputlangs));
+
+	    if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false);
+
+	    // Add all others
+	    foreach($files as $file)
+	    {
+		// Charge un document PDF depuis un fichier.
+		$pagecount = $pdf->setSourceFile($file);
+		for ($i = 1; $i <= $pagecount; $i++)
+		{
+		    $tplidx = $pdf->importPage($i);
+		    $s = $pdf->getTemplatesize($tplidx);
+		    $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L');
+		    $pdf->useTemplate($tplidx);
+		}
+	    }
+
+	    // Create output dir if not exists
+	    dol_mkdir($diroutputmassaction);
+
+	    // Defined name of merged file
+	    $filename=strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
+	    $filename=preg_replace('/\s/','_',$filename);
+	    
+	    // Save merged file
+	    if ($filter=='paye:0')
+	    {
+		if ($option=='late') $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
+		else $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
+	    }
+	    if ($year) $filename.='_'.$year;
+	    if ($month) $filename.='_'.$month;
+	    if ($pagecount)
+	    {
+		$now=dol_now();
+		$file=$diroutputmassaction.'/'.$filename.'_'.dol_print_date($now,'dayhourlog').'.pdf';
+		$pdf->Output($file,'F');
+		if (! empty($conf->global->MAIN_UMASK))
+		    @chmod($file, octdec($conf->global->MAIN_UMASK));
+
+		    $langs->load("exports");
+		    setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs');
+	    }
+	    else
+	    {
+		setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
+	    }
     }
 }
 
diff --git a/htdocs/core/ajax/check_notifications.php b/htdocs/core/ajax/check_notifications.php
index 4db67aef9397198c204a9f857fe13ace3f94d3c1..fa3edd7a4be98c99a5af55ea61c3f41c5357f7a0 100644
--- a/htdocs/core/ajax/check_notifications.php
+++ b/htdocs/core/ajax/check_notifications.php
@@ -21,7 +21,6 @@ if (! defined('NOREQUIREMENU'))  define('NOREQUIREMENU','1');
 if (! defined('NOREQUIREHTML'))  define('NOREQUIREHTML','1');
 if (! defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX','1');
 if (! defined('NOREQUIRESOC'))   define('NOREQUIRESOC','1');
-if (! defined('NOREQUIRETRAN'))  define('NOREQUIRETRAN','1');
 
 require '../../main.inc.php';
 
@@ -88,9 +87,11 @@ if ($time >= $_SESSION['auto_check_events_not_before'])
         while ($obj = $db->fetch_object($resql)) 
         {
             $langs->load("agenda");
+            $langs->load("commercial");
             
             $actionmod->fetch($obj->id);
 
+            // Message must be formated and translated to be used with javascript directly
             $event = array();
             $event['type'] = 'agenda';
             $event['id'] = $actionmod->id;
@@ -101,6 +102,10 @@ if ($time >= $_SESSION['auto_check_events_not_before'])
             $eventfound[] = $event;
         }
     }
+    else
+    {
+        dol_syslog("Error sql = ".$db->lasterror(), LOG_ERR);
+    }
 
 }
 
diff --git a/htdocs/core/boxes/box_external_rss.php b/htdocs/core/boxes/box_external_rss.php
index 71b643665b35eae33bfa1bf1cb487728d2448a36..14e542ff101f6858f246a8d400b797f37e0d10e6 100644
--- a/htdocs/core/boxes/box_external_rss.php
+++ b/htdocs/core/boxes/box_external_rss.php
@@ -80,8 +80,11 @@ class box_external_rss extends ModeleBoxes
 		// documents/externalrss is created by module activation
 		// documents/externalrss/tmp is created by rssparser
 
+		$keyforparamurl="EXTERNAL_RSS_URLRSS_".$site;
+		$keyforparamtitle="EXTERNAL_RSS_TITLE_".$site;
+		
 		// Get RSS feed
-        $url=@constant("EXTERNAL_RSS_URLRSS_".$site);
+		$url=$conf->global->$keyforparamurl;
 
         $rssparser=new RssParser($this->db);
 		$result = $rssparser->parser($url, $this->max, $cachedelay, $conf->externalrss->dir_temp);
@@ -90,7 +93,7 @@ class box_external_rss extends ModeleBoxes
 		$description=$rssparser->getDescription();
 		$link=$rssparser->getLink();
 
-        $title=$langs->trans("BoxTitleLastRssInfos",$max, @constant("EXTERNAL_RSS_TITLE_". $site));
+        $title=$langs->trans("BoxTitleLastRssInfos", $max, $conf->global->$keyforparamtitle);
         if ($result < 0 || ! empty($rssparser->error))
         {
             // Show warning
diff --git a/htdocs/core/class/commondocgenerator.class.php b/htdocs/core/class/commondocgenerator.class.php
index e3a84c80a1c53a0e56ddcd440936d2721b2f53a4..00394b0e03f80fca092d6860b3156f69855d22da 100644
--- a/htdocs/core/class/commondocgenerator.class.php
+++ b/htdocs/core/class/commondocgenerator.class.php
@@ -360,7 +360,7 @@ abstract class CommonDocGenerator
 	{
 		global $conf;
 
-		$sumpayed=''; $alreadypayed='';
+		$sumpayed=$sumdeposit=$sumcreditnote='';
 		if ($object->element == 'facture')
 		{
 			$invoice_source=new Facture($this->db);
@@ -369,7 +369,8 @@ abstract class CommonDocGenerator
 				$invoice_source->fetch($object->fk_facture_source);
 			}
 			$sumpayed = $object->getSommePaiement();
-			$alreadypayed=price($sumpayed,0,$outputlangs);
+			$sumdeposit = $object->getSumDepositsUsed();
+			$sumcreditnote = $object->getSumCreditNotesUsed();
 		}
 
 		$resarray=array(
@@ -412,11 +413,21 @@ abstract class CommonDocGenerator
 		$array_key.'_note_private'=>$object->note,
 		$array_key.'_note_public'=>$object->note_public,
 		$array_key.'_note'=>$object->note_public,			// For backward compatibility
+		
 		// Payments
-		$array_key.'_already_payed_locale'=>price($alreadypayed, 0, $outputlangs),
-		$array_key.'_remain_to_pay_locale'=>price($object->total_ttc - $sumpayed, 0, $outputlangs),
-		$array_key.'_already_payed'=>$alreadypayed,
-		$array_key.'_remain_to_pay'=>price2num($object->total_ttc - $sumpayed)
+		$array_key.'_already_payed_locale'=>price($sumpayed, 0, $outputlangs),
+		$array_key.'_already_payed'=>price2num($sumpayed),
+		$array_key.'_already_deposit_locale'=>price($sumdeposit, 0, $outputlangs),
+		$array_key.'_already_deposit'=>price2num($sumdeposit),
+		$array_key.'_already_creditnote_locale'=>price($sumcreditnote, 0, $outputlangs),
+		$array_key.'_already_creditnote'=>price2num($sumcreditnote),
+		
+		$array_key.'_already_payed_all_locale'=>price(price2num($sumpayed + $sumdeposit + $sumcreditnote, 'MT'), 0, $outputlangs),
+		$array_key.'already_payed_all'=> price2num(($sumpayed + $sumdeposit + $sumcreditnote), 'MT'),
+		    
+		// Remain to pay with all know infrmation (except open direct debit requests)
+		$array_key.'_remain_to_pay_locale'=>price(price2num($object->total_ttc - $sumpayed - $sumdeposit - $sumcreditnote, 'MT'), 0, $outputlangs),
+		$array_key.'_remain_to_pay'=>price2num($object->total_ttc - $sumpayed - $sumdeposit - $sumcreditnote, 'MT')
 		);
 
 		// Add vat by rates
diff --git a/htdocs/core/class/commoninvoice.class.php b/htdocs/core/class/commoninvoice.class.php
index 3e9d56f8f8cce35a30a6f7df8520c324b81ebbef..2e2a26dd9ae8fc0a163739e85f2daa80c8138fcd 100644
--- a/htdocs/core/class/commoninvoice.class.php
+++ b/htdocs/core/class/commoninvoice.class.php
@@ -51,7 +51,8 @@ abstract class CommonInvoice extends CommonObject
     const TYPE_DEPOSIT = 3;
 
     /**
-     * Proforma invoice
+     * Proforma invoice. 
+     * @deprectad Remove this. A "proforma invoice" is an order with a look of invoice, not an invoice !
      */
     const TYPE_PROFORMA = 4;
 
@@ -90,8 +91,8 @@ abstract class CommonInvoice extends CommonObject
 
 	
 	/**
-	 * 	Return remain amount to pay.
-	 *  Property ->id and ->total_ttc must be set.
+	 * 	Return remain amount to pay. Property ->id and ->total_ttc must be set.
+	 *  This does not include open direct debit requests.
 	 *
 	 *  @param 		int 	$multicurrency 	Return multicurrency_amount instead of amount
 	 *	@return		int						Remain of amount to pay
@@ -548,6 +549,12 @@ abstract class CommonInvoiceLine extends CommonObjectLine
 	 */
 	public $fk_product;
 
+	/**
+	 * VAT code
+	 * @var string
+	 */
+	public $vat_src_code;
+
 	/**
 	 * VAT %
 	 * @var float
diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php
index e03db1b4773fb39679fcb0e0d9f524faf28aec50..947d99af545662270a2b0e40aa7dc00ed0984719 100644
--- a/htdocs/core/class/commonobject.class.php
+++ b/htdocs/core/class/commonobject.class.php
@@ -11,6 +11,7 @@
  * Copyright (C) 2012      Cedric Salvador      <csalvador@gpcsolutions.fr>
  * Copyright (C) 2015      Alexandre Spangaro   <aspangaro.dolibarr@gmail.com>
  * Copyright (C) 2016      Bahfir abbes         <dolipar@dolipar.org>
+ * Copyright (C) 2017      ATM Consulting       <support@atm-consulting.fr>
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -238,6 +239,7 @@ abstract class CommonObject
 
 	/**
 	 * @var int Delivery address ID
+	 * @deprecated
 	 * @see setDeliveryAddress()
 	 */
 	public $fk_delivery_address;
@@ -1623,7 +1625,8 @@ abstract class CommonObject
 
     /**
      *	Define delivery address
-     *
+     *  @deprecated
+     *  
      *	@param      int		$id		Address id
      *	@return     int				<0 si ko, >0 si ok
      */
@@ -2787,6 +2790,8 @@ abstract class CommonObject
     {
     	global $user,$langs,$conf;
 
+    	$savElementId=$elementId;  // To be used later to know if we were using the method using the id of this or not.
+    	
         $elementId = (!empty($elementId)?$elementId:$this->id);
         $elementTable = (!empty($elementType)?$elementType:$this->table_element);
 
@@ -2810,11 +2815,13 @@ abstract class CommonObject
             $error = 0;
 
             $trigkey='';
-            if ($this->element == 'supplier_proposal' && $status == 2) $trigkey='SUPPLIER_PROPOSAL_CLOSE';
+            if ($this->element == 'supplier_proposal' && $status == 2) $trigkey='SUPPLIER_PROPOSAL_SIGN';   // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
+            if ($this->element == 'supplier_proposal' && $status == 3) $trigkey='SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
+            if ($this->element == 'supplier_proposal' && $status == 4) $trigkey='SUPPLIER_PROPOSAL_CLOSE';  // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
             if ($this->element == 'fichinter' && $status == 3) $trigkey='FICHINTER_CLASSIFY_DONE';
             if ($this->element == 'fichinter' && $status == 2) $trigkey='FICHINTER_CLASSIFY_BILLED';
             if ($this->element == 'fichinter' && $status == 1) $trigkey='FICHINTER_CLASSIFY_UNBILLED';
-
+            
             if ($trigkey)
             {
                 // Appel des triggers
@@ -2830,12 +2837,14 @@ abstract class CommonObject
 			if (! $error)
 			{
 				$this->db->commit();
-        		if (empty($elementId))    // If the element we update was $this (so $elementId is null)
+				
+        		if (empty($savElementId))    // If the element we update was $this (so $elementId is null)
         		{
         		    $this->statut = $status;
         		    $this->status = $status;
         		}
-				return 1;
+
+                return 1;
 			}
 			else
 			{
@@ -3031,12 +3040,12 @@ abstract class CommonObject
      */
     function getTotalWeightVolume()
     {
-        $weightUnit=0;
-        $volumeUnit=0;
-        $totalWeight = '';
-        $totalVolume = '';
-        $totalOrdered = '';     // defined for shipment only
-        $totalToShip = '';      // defined for shipment only
+        $totalWeight = 0;
+        $totalVolume = 0;
+	    // defined for shipment only
+        $totalOrdered = '';
+	    // defined for shipment only
+        $totalToShip = '';
 
         foreach ($this->lines as $line)
         {
@@ -3051,11 +3060,18 @@ abstract class CommonObject
                 $totalToShip+=$line->qty_shipped;   // defined for shipment only
             }
 
-            // Define qty, weight, volume, weight_units, volume_units
-            if ($this->element == 'shipping') $qty=$line->qty_shipped;     // for shipments
-            else $qty=$line->qty;
-            $weight=$line->weight;
-            $volume=$line->volume;
+	        // Define qty, weight, volume, weight_units, volume_units
+	        if ($this->element == 'shipping') {
+		        // for shipments
+		        $qty = $line->qty_shipped ? $line->qty_shipped : 0;
+	        }
+	        else {
+		        $qty = $line->qty ? $line->qty : 0;
+	        }
+
+            $weight = $line->weight ? $line->weight : 0;
+            $volume = $line->volume ? $line->volume : 0;
+
             $weight_units=$line->weight_units;
             $volume_units=$line->volume_units;
 
@@ -3223,51 +3239,14 @@ abstract class CommonObject
 
     /**
      *  Return if a country is inside the EEC (European Economic Community)
-     *  TODO Add a field into dictionary
+     *  @deprecated
      *
      *  @return     boolean		true = country inside EEC, false = country outside EEC
      */
     function isInEEC()
     {
-        // List of all country codes that are in europe for european vat rules
-        // List found on http://ec.europa.eu/taxation_customs/common/faq/faq_1179_en.htm#9
-        $country_code_in_EEC=array(
-    			'AT',	// Austria
-    			'BE',	// Belgium
-    			'BG',	// Bulgaria
-    			'CY',	// Cyprus
-    			'CZ',	// Czech republic
-    			'DE',	// Germany
-    			'DK',	// Danemark
-    			'EE',	// Estonia
-    			'ES',	// Spain
-    			'FI',	// Finland
-    			'FR',	// France
-    			'GB',	// United Kingdom
-    			'GR',	// Greece
-    			'HR',   // Croatia
-                'NL',	// Holland
-    			'HU',	// Hungary
-    			'IE',	// Ireland
-    			'IM',	// Isle of Man - Included in UK
-    			'IT',	// Italy
-    			'LT',	// Lithuania
-    			'LU',	// Luxembourg
-    			'LV',	// Latvia
-    			'MC',	// Monaco - Included in France
-    			'MT',	// Malta
-                //'NO',	// Norway
-    			'PL',	// Poland
-    			'PT',	// Portugal
-    			'RO',	// Romania
-    			'SE',	// Sweden
-    			'SK',	// Slovakia
-    			'SI',	// Slovenia
-    			'UK',	// United Kingdom
-        //'CH',	// Switzerland - No. Swizerland in not in EEC
-        );
-        //print "dd".$this->country_code;
-        return in_array($this->country_code,$country_code_in_EEC);
+        require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
+        return isInEEC($this);
     }
 
 
@@ -3594,7 +3573,7 @@ abstract class CommonObject
         print '<tr class="liste_titre">';
         print '<td>'.$langs->trans('Ref').'</td>';
         print '<td>'.$langs->trans('Description').'</td>';
-        print '<td align="right">'.$langs->trans('VAT').'</td>';
+        print '<td align="right">'.$langs->trans('VATRate').'</td>';
         print '<td align="right">'.$langs->trans('PriceUHT').'</td>';
 		if (!empty($conf->multicurrency->enabled)) print '<td align="right">'.$langs->trans('PriceUHTCurrency').'</td>';
         print '<td align="right">'.$langs->trans('Qty').'</td>';
@@ -3731,7 +3710,10 @@ abstract class CommonObject
             $this->tpl['description'] = '&nbsp;';
         }
 
+        // VAT Rate
         $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
+        if (! empty($line->vat_src_code) && ! preg_match('/\(/', $this->tpl['vat_rate'])) $this->tpl['vat_rate'].=' ('.$line->vat_src_code.')';
+
         $this->tpl['price'] = price($line->subprice);
 		$this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
         $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
@@ -3754,21 +3736,6 @@ abstract class CommonObject
     }
 
 
-	/**
-	 * Show the array with all margin infos
-	 *
-	 * @param 		bool	$force_price	Force price
-	 * @return		void
-	 * @deprecated	3.8 Load FormMargin class and make a direct call to displayMarginInfos
-	 */
-	function displayMarginInfos($force_price=false)
-	{
-		include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php';
-		$formmargin=new FormMargin($this->db);
-		$formmargin->displayMarginInfos($this, $force_price);
-	}
-
-
 	/**
 	 *	Add resources to the current object : add entry into llx_element_resources
 	 *	Need $this->element & $this->id
@@ -4711,4 +4678,372 @@ abstract class CommonObject
 		}
 		return $buyPrice;
 	}
+	
+	/**
+	 * Function test if type is date
+	 *
+	 * @param   array   $info   content informations of field
+	 * @return                  bool
+	 */
+	protected function isDate($info)
+	{
+		if(isset($info['type']) && $info['type']=='date') return true;
+		else return false;
+	}
+	
+	/**
+	 * Function test if type is array
+	 *
+	 * @param   array   $info   content informations of field
+	 * @return                  bool
+	 */
+	protected function isArray($info)
+	{
+		if(is_array($info))
+		{
+			if(isset($info['type']) && $info['type']=='array') return true;
+			else return false;
+		}
+		else return false;
+	}
+	
+	/**
+	 * Function test if type is null
+	 *
+	 * @param   array   $info   content informations of field
+	 * @return                  bool
+	 */
+	protected function isNull($info)
+	{
+		if(is_array($info))
+		{
+			if(isset($info['type']) && $info['type']=='null') return true;
+			else return false;
+		}
+		else return false;
+	}
+	
+	/**
+	 * Function test if type is integer
+	 *
+	 * @param   array   $info   content informations of field
+	 * @return                  bool
+	 */
+	protected function isInt($info)
+	{
+		if(is_array($info))
+		{
+			if(isset($info['type']) && ($info['type']=='int' || $info['type']=='integer' )) return true;
+			else return false;
+		}
+		else return false;
+	}
+	
+	/**
+	 * Function test if type is float
+	 *
+	 * @param   array   $info   content informations of field
+	 * @return                  bool
+	 */
+	protected function isFloat($info)
+	{
+		if(is_array($info))
+		{
+			if(isset($info['type']) && $info['type']=='float') return true;
+			else return false;
+		}
+		else return false;
+	}
+	
+	/**
+	 * Function test if type is text
+	 *
+	 * @param   array   $info   content informations of field
+	 * @return                  bool
+	 */
+	protected function isText($info)
+	{
+		if(is_array($info))
+		{
+			if(isset($info['type']) && $info['type']=='text') return true;
+			else return false;
+		}
+		else return false;
+	}
+	
+	/**
+	 * Function test if is indexed
+	 *
+	 * @param   array   $info   content informations of field
+	 * @return                  bool
+	 */
+	protected function isIndex($info)
+	{
+		if(is_array($info))
+		{
+			if(isset($info['index']) && $info['index']==true) return true;
+			else return false;
+		}
+		else return false;
+	}
+	
+	/**
+	 * Function to prepare the values to insert
+	 *
+	 * @return array
+	 */
+	private function set_save_query()
+	{
+		$query=array();
+		foreach ($this->fields as $field=>$info)
+		{
+			if($this->isDate($info))
+			{
+				if(empty($this->{$field}))
+				{
+					$query[$field] = NULL;
+				}
+				else
+				{
+					$query[$field] = $this->db->idate($this->{$field});
+				}
+			}
+			else if($this->isArray($info))
+			{
+				$query[$field] = serialize($this->{$field});
+			}
+			else if($this->isInt($info))
+			{
+				$query[$field] = (int) price2num($this->{$field});
+			}
+			else if($this->isFloat($info))
+			{
+				$query[$field] = (double) price2num($this->{$field});
+			}
+			elseif($this->isNull($info))
+			{
+				$query[$field] = (is_null($this->{$field}) || (empty($this->{$field}) && $this->{$field}!==0 && $this->{$field}!=='0') ? null : $this->{$field});
+			}
+			else
+			{
+				$query[$field] = $this->{$field};
+			}
+		}
+		
+		return $query;
+	}
+
+	/**
+	 * Create object into database
+	 *
+	 * @param  User $user      User that creates
+	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
+	 *
+	 * @return int <0 if KO, Id of created object if OK
+	 */
+	public function createCommon(User $user, $notrigger = false)
+	{
+	    
+	    $fields = array_merge(array('datec'=>$this->db->idate(dol_now())), $this->set_save_query());
+	    
+	    foreach ($fields as $k => $v) {
+	    	
+	    	$keys[] = $k;
+	    	$values[] = $this->quote($v);
+	    	
+	    }
+	    $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element.'
+					( '.implode( ",", $keys ).' )
+					VALUES ( '.implode( ",", $values ).' ) ';
+	    $res = $this->db->query( $sql );
+	    if($res===false) {
+	    	
+	    	return false;
+	    }
+	    
+	    // TODO Add triggers
+	    
+	    return true;
+	    
+	}
+	
+	/**
+	 * Function to load data into current object this
+	 *
+	 * @param   stdClass    $obj    Contain data of object from database
+	 */
+	private function set_vars_by_db(&$obj)
+	{
+		foreach ($this->fields as $field => $info)
+		{
+			if($this->isDate($info))
+			{
+				if(empty($obj->{$field}) || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') $this->{$field} = 0;
+				else $this->{$field} = strtotime($obj->{$field});
+			}
+			elseif($this->isArray($info))
+			{
+				$this->{$field} = @unserialize($obj->{$field});
+				// Hack for data not in UTF8
+				if($this->{$field } === FALSE) @unserialize(utf8_decode($obj->{$field}));
+			}
+			elseif($this->isInt($info))
+			{
+				$this->{$field} = (int) $obj->{$field};
+			}
+			elseif($this->isFloat($info))
+			{
+				$this->{$field} = (double) $obj->{$field};
+			}
+			elseif($this->isNull($info))
+			{
+				$val = $obj->{$field};
+				// zero is not null
+				$this->{$field} = (is_null($val) || (empty($val) && $val!==0 && $val!=='0') ? null : $val);
+			}
+			else
+			{
+				$this->{$field} = $obj->{$field};
+			}
+			
+		}
+	}
+	
+	/**
+	 * Function to concat keys of fields
+	 *
+	 * @return string
+	 */
+	private function get_field_list()
+	{
+		$keys = array_keys($this->fields);
+		return implode(',', $keys);
+	}
+	
+	/**
+	 * Load object in memory from the database
+	 *
+	 * @param int    $id  Id object
+	 * @param string $ref Ref
+	 *
+	 * @return int <0 if KO, 0 if not found, >0 if OK
+	 */
+	public function fetchCommon($id, $ref = null)
+	{
+	    
+		if (empty($id) && empty($ref)) return false;
+		
+		$sql = 'SELECT '.$this->get_field_list().', datec, tms';
+		$sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
+		
+		if(!empty($id)) $sql.= ' WHERE rowid = '.$id;
+		else  $sql.= ' WHERE ref = \''.$this->quote($ref).'\'';
+
+		$res = $this->db->query($sql);
+		if ($res)
+		{
+    		if ($obj = $this->db->fetch_object($res))
+    		{
+    			$this->id = $id;
+    			$this->set_vars_by_db($obj);
+    			
+    			$this->datec = $this->db->idate($obj->datec);
+    			$this->tms = $this->db->idate($obj->tms);
+    			
+    			return $this->id;
+    		}
+    		else
+    		{
+    			$this->error = $this->db->lasterror();
+    			$this->errors[] = $this->error;
+    			return -1;
+    		}
+		}
+		else
+		{
+		    $this->error = $this->db->lasterror();
+		    $this->errors[] = $this->error;
+		    return -1;
+		}
+	}
+
+	/**
+	 * Update object into database
+	 *
+	 * @param  User $user      User that modifies
+	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
+	 *
+	 * @return int <0 if KO, >0 if OK
+	 */
+	public function updateCommon(User $user, $notrigger = false)
+	{
+		$fields = $this->set_save_query();
+		
+		foreach ($fields as $k => $v) {
+			
+			if (is_array($key)){
+				$i=array_search($k, $key);
+				if ( $i !== false) {
+					$where[] = $key[$i].'=' . $this->quote( $v ) ;
+					continue;
+				}
+			} else {
+				if ( $k == $key) {
+					$where[] = $k.'=' .$this->quote( $v ) ;
+					continue;
+				}
+			}
+			
+			$tmp[] = $k.'='.$this->quote($v);
+		}
+		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET '.implode( ',', $tmp ).' WHERE rowid='.$this->id ;
+		$res = $this->db->query( $sql );
+		
+		if($res===false) {
+			//error
+			return false;
+		}
+		
+		// TODO Add triggers
+		
+		return true;
+	}
+	
+	/**
+	 * Delete object in database
+	 *
+	 * @param User $user      User that deletes
+	 * @param bool $notrigger false=launch triggers after, true=disable triggers
+	 *
+	 * @return int <0 if KO, >0 if OK
+	 */
+	public function deleteCommon(User $user, $notrigger = false)
+	{
+		$sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.$this->id;
+		
+		$res = $this->db->query( $sql );
+		if($res===false) {
+			return false;
+		}
+		
+		// TODO Add triggers
+		
+		return true;
+	}
+
+	/**
+	 * Add quote to field value if necessary
+	 *
+	 * @param string|int	$value	value to protect
+	 * @return string|int
+	 */
+	protected function quote($value) {
+	
+	    if(is_null($value)) return 'NULL';
+	    else if(is_numeric($value)) return $value;
+	    else return "'".$this->db->escape( $value )."'";
+	
+	}
+	
 }
+
diff --git a/htdocs/core/class/conf.class.php b/htdocs/core/class/conf.class.php
index 9446020e3ff138bacbab7b63a4d77d3ecedb9735..28a287971a829c58f4fe499b948c57a91c91eaf5 100644
--- a/htdocs/core/class/conf.class.php
+++ b/htdocs/core/class/conf.class.php
@@ -210,7 +210,7 @@ class Conf
                 $file=dol_sanitizeFileName($file);
                 include_once DOL_DOCUMENT_ROOT . "/".$file."/".$file."_consts.php";
                 foreach ($file2bddconsts as $key=>$value) {
-                    $this->global->$key=constant($value);
+                    $this->global->$key=$value;
                 }
             }
         }
@@ -358,8 +358,8 @@ class Conf
     			$this->supplier_order->dir_temp=$rootfordata."/fournisseur/commande/temp";
     			$this->supplier_invoice=new stdClass();
     			$this->supplier_invoice->enabled=1;
-    			$this->supplier_order->dir_output=$rootfordata."/fournisseur/facture";
-    			$this->supplier_order->dir_temp=$rootfordata."/fournisseur/facture/temp";
+    			$this->supplier_invoice->dir_output=$rootfordata."/fournisseur/facture";
+    			$this->supplier_invoice->dir_temp=$rootfordata."/fournisseur/facture/temp";
 			}
 		}
 
diff --git a/htdocs/core/class/coreobject.class.php b/htdocs/core/class/coreobject.class.php
new file mode 100644
index 0000000000000000000000000000000000000000..1456fb991c2fa0a414740700cd6ae2940f616342
--- /dev/null
+++ b/htdocs/core/class/coreobject.class.php
@@ -0,0 +1,438 @@
+<?php
+/* EXPERIMENTAL
+ * 
+ * Copyright (C) 2016		ATM Consulting			<support@atm-consulting.fr>
+ *
+ * This program 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.
+ *
+ * This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/**
+ *	\file       htdocs/core/class/coreobject.class.php
+ *	\ingroup    core
+ *	\brief      File of class to manage all object. Might be replace or merge into commonobject
+ */
+ 
+require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
+
+class CoreObject extends CommonObject
+{
+	public $withChild = true;
+
+	/**
+	 *  @var Array $_fields Fields to synchronize with Database
+	 */
+	protected $fields=array();
+
+    /**
+	 *  Constructor
+	 *
+	 *  @param      DoliDB		$db      Database handler
+	 */
+	function __construct(DoliDB &$db)
+    {
+        $this->db = $db;
+	}
+
+    /**
+     * Function to init fields
+     *
+     * @return bool
+     */
+	protected function init()
+    {
+		$this->id = 0;
+		$this->datec = 0;
+		$this->tms = 0;
+		
+		if (!empty($this->fields))
+		{
+			foreach ($this->fields as $field=>$info)
+			{
+		        if ($this->isDate($info)) $this->{$field} = time();
+		        elseif ($this->isArray($info)) $this->{$field} = array();
+		        elseif ($this->isInt($info)) $this->{$field} = (int) 0;
+		        elseif ($this->isFloat($info)) $this->{$field} = (double) 0;
+				else $this->{$field} = '';
+		    }
+
+            $this->to_delete=false;
+            $this->is_clone=false;
+			
+			return true;
+		}
+		else
+        {
+			return false;
+		}
+			
+	}
+
+    /**
+     * Test type of field
+     *
+     * @param   string  $field  name of field
+     * @param   string  $type   type of field to test
+     * @return                  value of field or false
+     */
+    private function checkFieldType($field, $type)
+    {
+		if (isset($this->fields[$field]) && method_exists($this, 'is_'.$type))
+		{
+			return $this->{'is_'.$type}($this->fields[$field]);
+		}
+		else
+        {
+            return false;
+        }
+	}
+
+    /**
+     *	Get object and children from database
+     *
+     *	@param      int			$id       		Id of object to load
+     * 	@param		bool		$loadChild		used to load children from database
+     *	@return     int         				>0 if OK, <0 if KO, 0 if not found
+     */
+	public function fetch($id, $loadChild = true)
+    {
+    	$res = $this->fetchCommon($id);
+    	if($res>0) {
+    		if ($loadChild) $this->fetchChild();
+    	}
+    	
+    	return $res;
+	}
+
+
+    /**
+     * Function to instantiate a new child
+     *
+     * @param   string  $tabName        Table name of child
+     * @param   int     $id             If id is given, we try to return his key if exist or load if we try_to_load
+     * @param   string  $key            Attribute name of the object id
+     * @param   bool    $try_to_load    Force the fetch if an id is given
+     * @return                          int
+     */
+    public function addChild($tabName, $id=0, $key='id', $try_to_load = false)
+    {
+		if(!empty($id))
+		{
+			foreach($this->{$tabName} as $k=>&$object)
+			{
+				if($object->{$key} === $id) return $k;
+			}
+		}
+	
+		$k = count($this->{$tabName});
+	
+		$className = ucfirst($tabName);
+		$this->{$tabName}[$k] = new $className($this->db);
+		if($id>0 && $key==='id' && $try_to_load)
+		{
+			$this->{$tabName}[$k]->fetch($id); 
+		}
+
+		return $k;
+	}
+
+
+    /**
+     * Function to set a child as to delete
+     *
+     * @param   string  $tabName        Table name of child
+     * @param   int     $id             Id of child to set as to delete
+     * @param   string  $key            Attribute name of the object id
+     * @return                          bool
+     */
+    public function removeChild($tabName, $id, $key='id')
+    {
+		foreach ($this->{$tabName} as &$object)
+		{
+			if ($object->{$key} == $id)
+			{
+				$object->to_delete = true;
+				return true;
+			}
+		}
+		return false;
+	}
+
+
+    /**
+     * Function to fetch children objects
+     */
+    public function fetchChild()
+    {
+		if($this->withChild && !empty($this->childtables) && !empty($this->fk_element))
+		{
+			foreach($this->childtables as &$childTable)
+			{
+                $className = ucfirst($childTable);
+
+                $this->{$className}=array();
+
+                $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$childTable.' WHERE '.$this->fk_element.' = '.$this->id;
+                $res = $this->db->query($sql);
+
+                if($res)
+                {
+                    while($obj = $this->db->fetch_object($res))
+                    {
+                        $o=new $className($this->db);
+                        $o->fetch($obj->rowid);
+
+                        $this->{$className}[] = $o;
+                    }
+                }
+                else
+                {
+                    $this->errors[] = $this->db->lasterror();
+                }
+			}
+		}
+	}
+
+    /**
+     * Function to update children data
+     *
+     * @param   User    $user   user object
+     */
+	public function saveChild(User &$user)
+    {
+		if($this->withChild && !empty($this->childtables) && !empty($this->fk_element))
+		{
+			foreach($this->childtables as &$childTable)
+			{
+				$className = ucfirst($childTable);
+				if(!empty($this->{$className}))
+				{
+					foreach($this->{$className} as $i => &$object)
+					{
+						$object->{$this->fk_element} = $this->id;
+						
+						$object->update($user);
+						if($this->unsetChildDeleted && isset($object->to_delete) && $object->to_delete==true) unset($this->{$className}[$i]);
+					}
+				}
+			}
+		}
+	}
+
+
+    /**
+     * Function to update object or create or delete if needed
+     *
+     * @param   User    $user   user object
+     * @return                  < 0 if ko, > 0 if ok
+     */
+    public function update(User &$user)
+    {
+		if (empty($this->id)) return $this->create($user); // To test, with that, no need to test on high level object, the core decide it, update just needed
+        elseif (isset($this->to_delete) && $this->to_delete==true) return $this->delete($user);
+
+        $error = 0;
+        $this->db->begin();
+
+        $res = $this->updateCommon($user);
+        if ($res)
+        {
+            $result = $this->call_trigger(strtoupper($this->element). '_UPDATE', $user);
+            if ($result < 0) $error++;
+            else $this->saveChild($user);
+        }
+        else
+        {
+            $error++;
+            $this->error = $this->db->lasterror();
+            $this->errors[] = $this->error;
+        }
+
+        if (empty($error))
+        {
+            $this->db->commit();
+            return $this->id;
+        }
+        else
+        {
+            $this->db->rollback();
+            return -1;
+        }
+
+	}
+
+    /**
+     * Function to create object in database
+     *
+     * @param   User    $user   user object
+     * @return                  < 0 if ko, > 0 if ok
+     */
+    public function create(User &$user)
+    {
+		if($this->id > 0) return $this->update($user);
+
+        $error = 0;
+        $this->db->begin();
+
+        $res = $this->createCommon($user);
+		if($res)
+		{
+			$this->id = $this->db->last_insert_id($this->table_element);
+
+			$result = $this->call_trigger(strtoupper($this->element). '_CREATE', $user);
+            if ($result < 0) $error++;
+            else $this->saveChild($user);
+		}
+		else
+        {
+            $error++;
+            $this->error = $this->db->lasterror();
+            $this->errors[] = $this->error;
+		}
+
+        if (empty($error))
+        {
+            $this->db->commit();
+            return $this->id;
+        }
+        else
+        {
+            $this->db->rollback();
+            return -1;
+        }
+	}
+
+    /**
+     * Function to delete object in database
+     *
+     * @param   User    $user   user object
+     * @return                  < 0 if ko, > 0 if ok
+     */
+	public function delete(User &$user)
+    {
+		if ($this->id <= 0) return 0;
+
+        $error = 0;
+        $this->db->begin();
+
+        $result = $this->call_trigger(strtoupper($this->element). '_DELETE', $user);
+        if ($result < 0) $error++;
+
+        if (!$error)
+        {
+            $this->deleteCommon($user);
+            if($this->withChild && !empty($this->childtables))
+            {
+                foreach($this->childtables as &$childTable)
+                {
+                    $className = ucfirst($childTable);
+                    if (!empty($this->{$className}))
+                    {
+                        foreach($this->{$className} as &$object)
+                        {
+                            $object->delete($user);
+                        }
+                    }
+                }
+            }
+        }
+
+        if (empty($error))
+        {
+            $this->db->commit();
+            return 1;
+        }
+        else
+        {
+            $this->error = $this->db->lasterror();
+            $this->errors[] = $this->error;
+            $this->db->rollback();
+            return -1;
+        }
+	}
+
+
+    /**
+     * Function to get a formatted date
+     *
+     * @param   string  $field  Attribute to return
+     * @param   string  $format Output date format
+     * @return          string
+     */
+    public function getDate($field, $format='')
+    {
+		if(empty($this->{$field})) return '';
+		else
+        {
+			return dol_print_date($this->{$field}, $format);
+		}
+	}
+
+    /**
+     * Function to set date in field
+     *
+     * @param   string  $field  field to set
+     * @param   string  $date   formatted date to convert
+     * @return                  mixed
+     */
+    public function setDate($field, $date)
+    {
+	  	if (empty($date))
+	  	{
+	  		$this->{$field} = 0;
+	  	}
+		else
+        {
+			require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
+			$this->{$field} = dol_stringtotime($date);
+		}
+
+		return $this->{$field};
+	}
+
+
+    /**
+     * Function to update current object
+     *
+     * @param   array   $Tab    Array of values
+     * @return                  int
+     */
+    public function setValues(&$Tab)
+    {
+		foreach ($Tab as $key => $value)
+		{
+			if($this->checkFieldType($key, 'date'))
+			{
+				$this->setDate($key, $value);
+			}
+			else if( $this->checkFieldType($key, 'array'))
+			{
+				$this->{$key} = $value;
+			}
+			else if( $this->checkFieldType($key, 'float') )
+			{
+				$this->{$key} = (double) price2num($value);
+			}
+			else if( $this->checkFieldType($key, 'int') ) {
+				$this->{$key} = (int) price2num($value);
+			}
+			else
+            {
+				$this->{$key} = $value;
+			}
+		}
+
+		return 1;
+	}
+
+}
diff --git a/htdocs/core/class/ctyperesource.class.php b/htdocs/core/class/ctyperesource.class.php
new file mode 100644
index 0000000000000000000000000000000000000000..1de616210e4469c8d8e3ac370fb47c4bc2589742
--- /dev/null
+++ b/htdocs/core/class/ctyperesource.class.php
@@ -0,0 +1,500 @@
+<?php
+/* Copyright (C) 2007-2012  Laurent Destailleur <eldy@users.sourceforge.net>
+ * Copyright (C) 2014-2016  Juanjo Menent       <jmenent@2byte.es>
+ * Copyright (C) 2016       Florian Henry       <florian.henry@atm-consulting.fr>
+ * Copyright (C) 2015       Raphaël Doursenaud  <rdoursenaud@gpcsolutions.fr>
+ *
+ * This program 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.
+ *
+ * This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/**
+ * \file    resource/ctyperesource.class.php
+ * \ingroup resource
+ */
+
+/**
+ * Class Ctyperesource
+ *
+ * Put here description of your class
+ *
+ * @see CommonObject
+ */
+class Ctyperesource
+{
+	/**
+	 * @var string Id to identify managed objects
+	 */
+	public $element = 'ctyperesource';
+	/**
+	 * @var string Name of table without prefix where object is stored
+	 */
+	public $table_element = 'c_type_resource';
+
+	/**
+	 * @var CtyperesourceLine[] Lines
+	 */
+	public $lines = array();
+
+	/**
+	 */
+	
+	public $code;
+	public $label;
+	public $active;
+
+	/**
+	 */
+	
+
+	/**
+	 * Constructor
+	 *
+	 * @param DoliDb $db Database handler
+	 */
+	public function __construct(DoliDB $db)
+	{
+		$this->db = $db;
+	}
+
+	/**
+	 * Create object into database
+	 *
+	 * @param  User $user      User that creates
+	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
+	 *
+	 * @return int <0 if KO, Id of created object if OK
+	 */
+	public function create(User $user, $notrigger = false)
+	{
+		dol_syslog(__METHOD__, LOG_DEBUG);
+
+		$error = 0;
+
+		// Clean parameters
+		
+		if (isset($this->code)) {
+			 $this->code = trim($this->code);
+		}
+		if (isset($this->label)) {
+			 $this->label = trim($this->label);
+		}
+		if (isset($this->active)) {
+			 $this->active = trim($this->active);
+		}
+
+		
+
+		// Check parameters
+		// Put here code to add control on parameters values
+
+		// Insert request
+		$sql = 'INSERT INTO ' . MAIN_DB_PREFIX . $this->table_element . '(';
+		
+		$sql.= 'code,';
+		$sql.= 'label';
+		$sql.= 'active';
+
+		
+		$sql .= ') VALUES (';
+		
+		$sql .= ' '.(! isset($this->code)?'NULL':"'".$this->db->escape($this->code)."'").',';
+		$sql .= ' '.(! isset($this->label)?'NULL':"'".$this->db->escape($this->label)."'").',';
+		$sql .= ' '.(! isset($this->active)?'NULL':$this->active);
+
+		
+		$sql .= ')';
+
+		$this->db->begin();
+
+		$resql = $this->db->query($sql);
+		if (!$resql) {
+			$error ++;
+			$this->errors[] = 'Error ' . $this->db->lasterror();
+			dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
+		}
+
+		if (!$error) {
+			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element);
+
+			if (!$notrigger) {
+				// Uncomment this and change MYOBJECT to your own tag if you
+				// want this action to call a trigger.
+
+				//// Call triggers
+				//$result=$this->call_trigger('MYOBJECT_CREATE',$user);
+				//if ($result < 0) $error++;
+				//// End call triggers
+			}
+		}
+
+		// Commit or rollback
+		if ($error) {
+			$this->db->rollback();
+
+			return - 1 * $error;
+		} else {
+			$this->db->commit();
+
+			return $this->id;
+		}
+	}
+
+	/**
+	 * Load object in memory from the database
+	 *
+	 * @param int    $id  Id object
+	 * @param string $code code
+	 * @param string $label Label
+	 *
+	 * @return int <0 if KO, 0 if not found, >0 if OK
+	 */
+	public function fetch($id,$code='',$label='')
+	{
+		dol_syslog(__METHOD__, LOG_DEBUG);
+
+		$sql = 'SELECT';
+		$sql .= ' t.rowid,';
+		
+		$sql .= " t.code,";
+		$sql .= " t.label,";
+		$sql .= " t.active";
+
+		
+		$sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t';
+		if ($id)   $sql.= " WHERE t.id = ".$id;
+		elseif ($code) $sql.= " WHERE t.code = '".$this->db->escape($code)."'";
+		elseif ($label) $sql.= " WHERE t.label = '".$this->db->escape($label)."'";
+		
+		
+		$resql = $this->db->query($sql);
+		if ($resql) {
+			$numrows = $this->db->num_rows($resql);
+			if ($numrows) {
+				$obj = $this->db->fetch_object($resql);
+
+				$this->id = $obj->rowid;
+				
+				$this->code = $obj->code;
+				$this->label = $obj->label;
+				$this->active = $obj->active;
+
+				
+			}
+			
+			// Retrieve all extrafields for invoice
+			// fetch optionals attributes and labels
+			/*
+			require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
+			$extrafields=new ExtraFields($this->db);
+			$extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
+			$this->fetch_optionals($this->id,$extralabels);
+            */
+			
+			// $this->fetch_lines();
+			
+			$this->db->free($resql);
+
+			if ($numrows) {
+				return 1;
+			} else {
+				return 0;
+			}
+		} else {
+			$this->errors[] = 'Error ' . $this->db->lasterror();
+			dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
+
+			return - 1;
+		}
+	}
+
+	/**
+	 * Load object in memory from the database
+	 *
+	 * @param string $sortorder Sort Order
+	 * @param string $sortfield Sort field
+	 * @param int    $limit     offset limit
+	 * @param int    $offset    offset limit
+	 * @param array  $filter    filter array
+	 * @param string $filtermode filter mode (AND or OR)
+	 *
+	 * @return int <0 if KO, >0 if OK
+	 */
+	public function fetchAll($sortorder='', $sortfield='', $limit=0, $offset=0, array $filter = array(), $filtermode='AND')
+	{
+		dol_syslog(__METHOD__, LOG_DEBUG);
+
+		$sql = 'SELECT';
+		$sql .= ' t.rowid,';
+		
+		$sql .= " t.code,";
+		$sql .= " t.label,";
+		$sql .= " t.active";
+
+		
+		$sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element. ' as t';
+
+		// Manage filter
+		$sqlwhere = array();
+		if (count($filter) > 0) {
+			foreach ($filter as $key => $value) {
+				$sqlwhere [] = $key . ' LIKE \'%' . $this->db->escape($value) . '%\'';
+			}
+		}
+		
+		if (count($sqlwhere) > 0) {
+			$sql .= ' WHERE ' . implode(' '.$filtermode.' ', $sqlwhere);
+		}
+		if (!empty($sortfield)) {
+			$sql .= $this->db->order($sortfield,$sortorder);
+		}
+		if (!empty($limit)) {
+		 $sql .=  ' ' . $this->db->plimit($limit, $offset);
+		}
+
+		$resql = $this->db->query($sql);
+		if ($resql) {
+			$num = $this->db->num_rows($resql);
+
+			while ($obj = $this->db->fetch_object($resql)) {
+				$line = new self($this->db);
+
+				$line->id = $obj->rowid;
+				
+				$line->code = $obj->code;
+				$line->label = $obj->label;
+				$line->active = $obj->active;
+
+				
+			}
+			$this->db->free($resql);
+
+			return $num;
+		} else {
+			$this->errors[] = 'Error ' . $this->db->lasterror();
+			dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
+
+			return - 1;
+		}
+	}
+
+	/**
+	 * Update object into database
+	 *
+	 * @param  User $user      User that modifies
+	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
+	 *
+	 * @return int <0 if KO, >0 if OK
+	 */
+	public function update(User $user, $notrigger = false)
+	{
+		$error = 0;
+
+		dol_syslog(__METHOD__, LOG_DEBUG);
+
+		// Clean parameters
+		
+		if (isset($this->code)) {
+			 $this->code = trim($this->code);
+		}
+		if (isset($this->label)) {
+			 $this->label = trim($this->label);
+		}
+		if (isset($this->active)) {
+			 $this->active = trim($this->active);
+		}
+
+		// Check parameters
+		// Put here code to add a control on parameters values
+
+		// Update request
+		$sql = 'UPDATE ' . MAIN_DB_PREFIX . $this->table_element . ' SET';
+		
+		$sql .= ' code = '.(isset($this->code)?"'".$this->db->escape($this->code)."'":"null").',';
+		$sql .= ' label = '.(isset($this->label)?"'".$this->db->escape($this->label)."'":"null").',';
+		$sql .= ' active = '.(isset($this->active)?$this->active:"null");
+
+        
+		$sql .= ' WHERE rowid=' . $this->id;
+
+		$this->db->begin();
+
+		$resql = $this->db->query($sql);
+		if (!$resql) {
+			$error ++;
+			$this->errors[] = 'Error ' . $this->db->lasterror();
+			dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
+		}
+
+		if (!$error && !$notrigger) {
+			// Uncomment this and change MYOBJECT to your own tag if you
+			// want this action calls a trigger.
+
+			//// Call triggers
+			//$result=$this->call_trigger('MYOBJECT_MODIFY',$user);
+			//if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
+			//// End call triggers
+		}
+
+		// Commit or rollback
+		if ($error) {
+			$this->db->rollback();
+
+			return - 1 * $error;
+		} else {
+			$this->db->commit();
+
+			return 1;
+		}
+	}
+
+	/**
+	 * Delete object in database
+	 *
+	 * @param User $user      User that deletes
+	 * @param bool $notrigger false=launch triggers after, true=disable triggers
+	 *
+	 * @return int <0 if KO, >0 if OK
+	 */
+	public function delete(User $user, $notrigger = false)
+	{
+		dol_syslog(__METHOD__, LOG_DEBUG);
+
+		$error = 0;
+
+		$this->db->begin();
+
+		if (!$error) {
+			if (!$notrigger) {
+				// Uncomment this and change MYOBJECT to your own tag if you
+				// want this action calls a trigger.
+
+				//// Call triggers
+				//$result=$this->call_trigger('MYOBJECT_DELETE',$user);
+				//if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
+				//// End call triggers
+			}
+		}
+
+		// If you need to delete child tables to, you can insert them here
+		
+		if (!$error) {
+			$sql = 'DELETE FROM ' . MAIN_DB_PREFIX . $this->table_element;
+			$sql .= ' WHERE rowid=' . $this->id;
+
+			$resql = $this->db->query($sql);
+			if (!$resql) {
+				$error ++;
+				$this->errors[] = 'Error ' . $this->db->lasterror();
+				dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
+			}
+		}
+
+		// Commit or rollback
+		if ($error) {
+			$this->db->rollback();
+
+			return - 1 * $error;
+		} else {
+			$this->db->commit();
+
+			return 1;
+		}
+	}
+
+	/**
+	 * Load an object from its id and create a new one in database
+	 *
+	 * @param int $fromid Id of object to clone
+	 *
+	 * @return int New id of clone
+	 */
+	public function createFromClone($fromid)
+	{
+		dol_syslog(__METHOD__, LOG_DEBUG);
+
+		global $user;
+		$error = 0;
+		$object = new Ctyperesource($this->db);
+
+		$this->db->begin();
+
+		// Load source object
+		$object->fetch($fromid);
+		// Reset object
+		$object->id = 0;
+
+		// Clear fields
+		// ...
+
+		// Create clone
+		$result = $object->create($user);
+
+		// Other options
+		if ($result < 0) {
+			$error ++;
+			$this->errors = $object->errors;
+			dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
+		}
+
+		// End
+		if (!$error) {
+			$this->db->commit();
+
+			return $object->id;
+		} else {
+			$this->db->rollback();
+
+			return - 1;
+		}
+	}
+
+	/**
+	 * Initialise object with example values
+	 * Id must be 0 if object instance is a specimen
+	 *
+	 * @return void
+	 */
+	public function initAsSpecimen()
+	{
+		$this->id = 0;
+		
+		$this->code = '';
+		$this->label = '';
+		$this->active = '';
+	}
+
+}
+
+/**
+ * Class CtyperesourceLine
+ */
+class CtyperesourceLine
+{
+	/**
+	 * @var int ID
+	 */
+	public $id;
+	/**
+	 * @var mixed Sample line property 1
+	 */
+	
+	public $code;
+	public $label;
+	public $active;
+
+	/**
+	 * @var mixed Sample line property 2
+	 */
+	
+}
diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php
index 3275ee0f303ff32313e44359a786d709413af0c7..6a503b40975cdd4b9dfba7bbfd74dd12a10ac89a 100644
--- a/htdocs/core/class/html.form.class.php
+++ b/htdocs/core/class/html.form.class.php
@@ -492,10 +492,11 @@ class Form
      */
     function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 2, $tooltiptrigger='')
     {
-        global $conf;
+        global $conf, $langs;
 
         $alt = '';
-
+        if ($tooltiptrigger) $alt=$langs->trans("ClickToShowHelp");
+        
         //For backwards compatibility
         if ($type == '0') $type = 'info';
         elseif ($type == '1') $type = 'help';
@@ -985,18 +986,23 @@ class Form
     		}
     		// mode 1
     		$urloption='htmlname='.$htmlname.'&outjson=1&filter='.$filter;
-    		print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
+    		$out.=  ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
+			$out.='<style type="text/css">
+					.ui-autocomplete {
+						z-index: 150;
+					}
+				</style>';
     		if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : ';
     		else if ($hidelabel > 1) {
     			if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"';
     			else $placeholder=' title="'.$langs->trans("RefOrLabel").'"';
     			if ($hidelabel == 2) {
-    				print img_picto($langs->trans("Search"), 'search');
+    				$out.=  img_picto($langs->trans("Search"), 'search');
     			}
     		}
-            print '<input type="text" class="'.$morecss.'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->THIRDPARTY_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
+            $out.=  '<input type="text" class="'.$morecss.'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->THIRDPARTY_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
     		if ($hidelabel == 3) {
-    			print img_picto($langs->trans("Search"), 'search');
+    			$out.=  img_picto($langs->trans("Search"), 'search');
     		}
     	}
     	else
diff --git a/htdocs/core/class/html.formactions.class.php b/htdocs/core/class/html.formactions.class.php
index b799e0e23593e4e5f27bdee0ecce355c09256f3e..452ff89d9146c2f4f40a81257dd6f68924b40d69 100644
--- a/htdocs/core/class/html.formactions.class.php
+++ b/htdocs/core/class/html.formactions.class.php
@@ -54,9 +54,10 @@ class FormActions
      *  @param  string	$htmlname   	Name of html prefix for html fields (selectX and valX)
      *  @param	integer	$showempty		Show an empty line if select is used
      *  @param	integer	$onlyselect		0=Standard, 1=Hide percent of completion and force usage of a select list, 2=Same than 1 and add "Incomplete (Todo+Running)
+     *  @param  string  $morecss        More css on select field
      * 	@return	void
      */
-    function form_select_status_action($formname,$selected,$canedit=1,$htmlname='complete',$showempty=0,$onlyselect=0)
+    function form_select_status_action($formname, $selected, $canedit=1, $htmlname='complete', $showempty=0, $onlyselect=0, $morecss='maxwidth100')
     {
         global $langs,$conf;
 
@@ -120,7 +121,7 @@ class FormActions
         {
         	//var_dump($selected);
         	if ($selected == 'done') $selected='100';
-            print '<select '.($canedit?'':'disabled ').'name="'.$htmlname.'" id="select'.$htmlname.'" class="flat maxwidth100">';
+            print '<select '.($canedit?'':'disabled ').'name="'.$htmlname.'" id="select'.$htmlname.'" class="flat'.($morecss?' '.$morecss:'').'">';
             if ($showempty) print '<option value=""'.($selected == ''?' selected':'').'></option>';
             foreach($listofstatus as $key => $val)
             {
diff --git a/htdocs/core/class/html.formmail.class.php b/htdocs/core/class/html.formmail.class.php
index d7ab17e60c4583436c70f52d25a4615347cde9dd..1d5e8714aad8edb2fce26b36187e64c0eedb7cf0 100644
--- a/htdocs/core/class/html.formmail.class.php
+++ b/htdocs/core/class/html.formmail.class.php
@@ -327,7 +327,7 @@ class FormMail extends Form
         	{
 	        	$out.= '<div class="center" style="padding: 0px 0 12px 0">'."\n";
         	    $out.= $langs->trans('SelectMailModel').': '.$this->selectarray('modelmailselected', $modelmail_array, 0, 1);
-	        	if ($user->admin) $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
+	        	if ($user->admin) $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFrom", $langs->transnoentitiesnoconv('Setup').' - '.$langs->transnoentitiesnoconv('EMails')),1);
 	        	$out.= ' &nbsp; ';
 	        	$out.= '<input class="button" type="submit" value="'.$langs->trans('Apply').'" name="modelselected" id="modelselected">';
 	        	$out.= ' &nbsp; ';
@@ -341,7 +341,7 @@ class FormMail extends Form
         	{
 	        	$out.= '<div class="center" style="padding: 0px 0 12px 0">'."\n";
         	    $out.= $langs->trans('SelectMailModel').': <select name="modelmailselected" disabled="disabled"><option value="none">'.$langs->trans("NoTemplateDefined").'</option></select>';    // Do not put disabled on option, it is already on select and it makes chrome crazy.
-        	    if ($user->admin) $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
+        	    if ($user->admin) $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFrom", $langs->transnoentitiesnoconv('Setup').' - '.$langs->transnoentitiesnoconv('EMails')),1);
         	    $out.= ' &nbsp; ';
         	    $out.= '<input class="button" type="submit" value="'.$langs->trans('Apply').'" name="modelselected" disabled="disabled" id="modelselected">';
         	    $out.= ' &nbsp; ';
@@ -1059,18 +1059,18 @@ class FormMail extends Form
 	}
 	
 	/**
-	 * Set substit array from object
+	 * Get list of substition keys available.
 	 * 
-	 * @param	string	$mode		'form', 'formwithlines', 'formforlines' or 'emailing'
+	 * @param	string	$mode		'formemail', 'formemailwithlines', 'formemailforlines', 'emailing', ...
 	 * @return	void
 	 */
-	function getAvailableSubstitKey($mode='form')
+	static function getAvailableSubstitKey($mode='formemail')
 	{
-		global $conf;
+		global $conf, $langs;
 		
 		$vars=array();
 		
-		if ($mode == 'form' || $mode == 'formwithlines' || $mode == 'formforlines')
+		if ($mode == 'formemail' || $mode == 'formemailwithlines' || $mode == 'formemailforlines')
 		{
 			$vars=array(
 				'__REF__', 
@@ -1133,6 +1133,15 @@ class FormMail extends Form
 				$vars['__SECUREKEYPAYPAL_MEMBER__']='';
 			}
 		}
+		
+		$tmparray=array();
+		$parameters=array('mode'=>$mode);
+		complete_substitutions_array($tmparray, $langs, null, $parameters);
+		foreach($tmparray as $key => $val)
+		{
+		    $vars[$key]=$key;
+		}
+		
 		return $vars;
 	}
 
diff --git a/htdocs/core/class/html.formmailing.class.php b/htdocs/core/class/html.formmailing.class.php
index 0c63049f9d88cf7cd63a4fea81d5b308a87939eb..9fb4e4eea86566132632d7e5d3badc1af881a3e1 100644
--- a/htdocs/core/class/html.formmailing.class.php
+++ b/htdocs/core/class/html.formmailing.class.php
@@ -32,9 +32,9 @@ class FormMailing  extends Form
 	/**
 	 * Output a select with destinaries status
 	 * 
-	 * @param string $selectedid the selected id
-	 * @param string $htmlname name of controm
-	 * @param integer $show_empty show empty option
+	 * @param string   $selectedid     The selected id
+	 * @param string   $htmlname       Name of controm
+	 * @param integer  $show_empty     Show empty option
 	 * @return string HTML select
 	 */
 	public function selectDestinariesStatus($selectedid='',$htmlname='dest_status', $show_empty=0) {
@@ -46,13 +46,13 @@ class FormMailing  extends Form
 		$mailing = new Mailing($this->db);
 
 		$options = array();
-
+        
 		if ($show_empty) {
-			$options[''] = '';
+			$options[-2] = '';   // Note -1 is used for error
 		}
 
-		$options = array_merge($options, $mailing->statut_dest);
+        $options = $options + $mailing->statut_dest;
 
-		return Form::selectarray($htmlname, $options, $selectedid, 0, 0, 0, '', 1);
+        return Form::selectarray($htmlname, $options, $selectedid, 0, 0, 0, '', 1);
 	}
 }
diff --git a/htdocs/core/class/translate.class.php b/htdocs/core/class/translate.class.php
index 30cedf57d51efec7f8bd86223331f99a86168320..0f2e6a837efb317adcd637f0fa02205d3a3612c8 100644
--- a/htdocs/core/class/translate.class.php
+++ b/htdocs/core/class/translate.class.php
@@ -170,6 +170,7 @@ class Translate
 	 * 	@param	int		$forcelangdir		To force a different lang directory
 	 *  @param  int     $loadfromfileonly   1=Do not load overwritten translation from file or old conf.
 	 *	@return	int							<0 if KO, 0 if already loaded or loading not required, >0 if OK
+	 *  @see loadLangs
 	 */
 	function load($domain,$alt=0,$stopafterdirection=0,$forcelangdir='',$loadfromfileonly=0)
 	{
diff --git a/htdocs/core/js/lib_notification.js.php b/htdocs/core/js/lib_notification.js.php
index af4452dfb3936cca165233d388bd9611fe921616..a3b90a35db6b46022673685dbc49dedab50af994 100644
--- a/htdocs/core/js/lib_notification.js.php
+++ b/htdocs/core/js/lib_notification.js.php
@@ -65,7 +65,7 @@ if (! ($_SERVER['HTTP_REFERER'] === $dolibarr_main_url_root . '/' || $_SERVER['H
    	// We set a delay before launching first test so next check will arrive after the time_auto_update compared to previous one.
     var time_first_execution = (time_auto_update - (nowtime - time_js_next_test)) * 1000;	//need milliseconds
     if (login != '') { 
-    	console.log("Launch browser notif check: setTimeout to wait time_first_execution="+time_first_execution+" before first check - nowtime = "+nowtime+" auto_check_events_not_before = "+auto_check_events_not_before+" time_js_next_test = "+time_js_next_test+" time_auto_update="+time_auto_update);
+    	console.log("Launch browser notif check: setTimeout is set to launch 'first_execution' function after a wait of time_first_execution="+time_first_execution+". nowtime (time php page generation) = "+nowtime+" auto_check_events_not_before (val in session)= "+auto_check_events_not_before+" time_js_next_test (max now,auto_check_events_not_before) = "+time_js_next_test+" time_auto_update="+time_auto_update);
     	setTimeout(first_execution, time_first_execution); 
     } //first run auto check
 
@@ -79,17 +79,18 @@ if (! ($_SERVER['HTTP_REFERER'] === $dolibarr_main_url_root . '/' || $_SERVER['H
     function check_events() {
     	if (Notification.permission === "granted")
     	{
-    		console.log("Call check_events time_js_next_test="+time_js_next_test);
-            $.ajax("<?php print dol_buildpath('/core/ajax/check_notifications.php', 1); ?>", {
-                type: "post",   // Usually post o get
+    		console.log("Call check_events time_js_next_test = date we are looking for event after ="+time_js_next_test);
+            $.ajax("<?php print DOL_URL_ROOT.'/core/ajax/check_notifications.php'; ?>", {
+                type: "post",   // Usually post or get
                 async: true,
                 data: {time: time_js_next_test},
                 success: function (result) {
                     var arr = JSON.parse(result);
                     if (arr.length > 0) {
+                    	var audio = null; 
                         <?php
                         if (! empty($conf->global->AGENDA_NOTIFICATION_SOUND)) {
-                            print 'var audio = new Audio(\''.DOL_URL_ROOT.'/theme/common/sound/notification_agenda.wav'.'\');';
+                            print 'audio = new Audio(\''.DOL_URL_ROOT.'/theme/common/sound/notification_agenda.wav'.'\');';
                         }
                         ?>
     
@@ -136,6 +137,7 @@ if (! ($_SERVER['HTTP_REFERER'] === $dolibarr_main_url_root . '/' || $_SERVER['H
         }
 
         time_js_next_test += time_auto_update;
+		console.log('Updated time_js_next_test. New value is '+time_js_next_test);
     }
 <?php 
 }
diff --git a/htdocs/core/js/listview.js b/htdocs/core/js/listview.js
new file mode 100644
index 0000000000000000000000000000000000000000..de3113d0faef0d5e5cf037347238fe4e3ad262a6
--- /dev/null
+++ b/htdocs/core/js/listview.js
@@ -0,0 +1,166 @@
+// Copyright (C) 2017 Laurent Destailleur  <eldy@users.sourceforge.net>
+//
+// This program 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.
+//
+// This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
+// or see http://www.gnu.org/
+
+//
+// \file       htdocs/core/js/listview.js
+// \brief      File that include javascript functions for lists
+//
+var Listview_include = true;
+
+function Listview_OrderDown(idListe, column) {
+	var base_url = document.location.href;
+	
+	base_url = Listview_recup_form_param(idListe,base_url);
+	base_url = Listview_removeParam(base_url,'Listview['+encodeURIComponent(idListe)+'][orderBy]');
+	
+	base_url = Listview_removeParam(base_url,'get-all-for-export');
+	
+	document.location.href=Listview_modifyUrl(base_url,"Listview["+encodeURIComponent(idListe)+"][orderBy]["+encodeURIComponent(column)+"]","DESC");
+}
+function Listview_OrderUp(idListe, column) {
+	
+	var base_url = document.location.href;
+	
+	base_url = Listview_recup_form_param(idListe,base_url);
+	base_url = Listview_removeParam(base_url,'Listview['+encodeURIComponent(idListe)+'][orderBy]');
+	
+	base_url = Listview_removeParam(base_url,'get-all-for-export');
+	
+	document.location.href=Listview_modifyUrl(base_url,"Listview["+encodeURIComponent(idListe)+"][orderBy]["+encodeURIComponent(column)+"]","ASC");
+}
+function Listview_modifyUrl(strURL,paramName,paramNewValue){
+	    if (strURL.indexOf(paramName+'=')!=-1){
+        	
+                var strFirstPart=strURL.substring(0,strURL.indexOf(paramName+'=',0))+paramName+'=';
+                var strLastPart="";
+                if (strURL.indexOf('&',strFirstPart.length-1)>0)
+                      strLastPart=strURL.substring(strURL.indexOf('&',strFirstPart.length-1),strURL.length);
+              		  strURL=strFirstPart+paramNewValue+strLastPart;
+                }
+        else{
+                if (strURL.search('=')!=-1) // permet de verifier s'il y a dej� des param�tres dans l'URL
+                        strURL+='&'+paramName+'='+paramNewValue;
+                else
+                        strURL+='?'+paramName+'='+paramNewValue;
+        }
+        
+        return strURL;
+}
+function Listview_removeParam(strURL, paramMask) {
+	var cpt=0;
+	var url = '';
+	
+	 while(strURL.indexOf(paramMask)!=-1 && cpt++ <50){
+	 	var strFirstPart= strURL.substring(0,strURL.indexOf(paramMask)-1);
+	 	
+	 	var strLastPart='';
+	 	if (strURL.indexOf('&',strFirstPart.length+1)>0) {
+	 		strLastPart = strURL.substring(strURL.indexOf('&',strFirstPart.length+1),strURL.length);	
+	 	}
+	 		
+		url = strFirstPart+strLastPart;
+	 	
+	 }
+	 
+	 if(url=='')url = strURL;
+	 
+	 return url;
+}
+
+function Listview_recup_form_param(idListe,base_url) {
+	
+	$('#'+idListe+' tr.barre-recherche [listviewtbs],#'+idListe+' tr.barre-recherche-head input,#'+idListe+' tr.barre-recherche-head select,#'+idListe+' div.tabsAction input[listviewtbs]').each(function(i,item) {
+		if($(item).attr("name")) {
+			base_url = Listview_modifyUrl(base_url, $(item).attr("name") , $(item).val());
+		}
+		
+	});
+	
+	return base_url;
+}
+
+function Listview_GoToPage(idListe,pageNumber){
+	
+	var base_url = document.location.href;
+	
+	base_url = Listview_recup_form_param(idListe,base_url);
+	base_url =Listview_modifyUrl(base_url,"Listview["+encodeURIComponent(idListe)+"][page]",pageNumber);
+	
+	base_url = Listview_removeParam(base_url,'get-all-for-export');
+	
+	document.location.href=base_url;
+}
+function Listview_submitSearch(obj) {
+	
+	$form = $(obj).closest('form');
+	console.log($form);
+	if($form.length>0){
+		$form.submit();
+	}
+}
+function Listview_launch_downloadAs(mode,url,token,session_name) {
+	 $('#listviewdAS_export_form').remove();
+	
+	$form = $('<form action="'+url+'" method="post" name="listviewdAS_export_form" id="listTBSdAS_export_form"></form>');
+	$form.append('<input type="hidden" name="mode" value="'+mode+'" />');
+	$form.append('<input type="hidden" name="token" value="'+token+'" />');
+	$form.append('<input type="hidden" name="session_name" value="'+session_name+'" />');
+	
+	$('body').append($form);
+	
+    $('#listviewdAS_export_form').submit();
+	
+}
+
+function Listview_downloadAs(obj, mode,url,token,session_name) {
+	
+	$form = $(obj).closest('form');
+	$div = $form.find('div.tabsAction');
+	$div.append('<input type="hidden" listviewtbs="hidden" name="token" value="'+token+'" />');
+	$div.append('<input type="hidden" listviewtbs="hidden" name="mode" value="'+mode+'" />');
+	$div.append('<input type="hidden" listviewtbs="hidden" name="url" value="'+url+'" />');
+	$div.append('<input type="hidden" listviewtbs="hidden" name="session_name" value="'+session_name+'" />');
+	$div.append('<input type="hidden" listviewtbs="hidden" name="get-all-for-export" value="1" />');
+	
+	Listview_submitSearch(obj);
+}
+
+$(document).ready(function() {
+	$('tr.barre-recherche input').keypress(function(e) {
+	    if(e.which == 13) {
+	       
+	       var id_list = $(this).closest('table').attr('id');
+	       
+	       $('#'+id_list+' .list-search-link').click();
+	       
+	    }
+	});
+	
+	var $_GET = {};
+	
+	document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
+	    function decode(s) {
+	        return decodeURIComponent(s.split("+").join(" "));
+	    }
+	
+	    $_GET[decode(arguments[1])] = decode(arguments[2]);
+	});
+	
+	if(typeof $_GET["get-all-for-export"] != "undefined") {
+		Listview_launch_downloadAs($_GET['mode'],$_GET['url'],$_GET['token'],$_GET['session_name']);
+	}
+	
+});
diff --git a/htdocs/core/lib/accounting.lib.php b/htdocs/core/lib/accounting.lib.php
index 56fdc8e6de92678c338886508e694c73af72d5f8..c8863ce8f615f97b226448b7e83079bab01162e7 100644
--- a/htdocs/core/lib/accounting.lib.php
+++ b/htdocs/core/lib/accounting.lib.php
@@ -180,7 +180,7 @@ function length_accounta($accounta)
 
 	if ($accounta < 0 || empty($accounta)) return '';
 	
-	if (! empty($conf->global->ACCOUNTING_MANAGE_ZERO)) return $account;
+	if (! empty($conf->global->ACCOUNTING_MANAGE_ZERO)) return $accounta;
 	
 	$a = $conf->global->ACCOUNTING_LENGTH_AACCOUNT;
 	if (! empty($a)) {
@@ -202,3 +202,95 @@ function length_accounta($accounta)
 		return $accounta;
 	}
 }
+
+
+
+/**
+ *	Show header of a VAT report
+ *
+ *	@param	string				$nom            Name of report
+ *	@param 	string				$variante       Link for alternate report
+ *	@param 	string				$period         Period of report
+ *	@param 	string				$periodlink     Link to switch period
+ *	@param 	string				$description    Description
+ *	@param 	timestamp|integer	$builddate      Date generation
+ *	@param 	string				$exportlink     Link for export or ''
+ *	@param	array				$moreparam		Array with list of params to add into form
+ *	@param	string				$calcmode		Calculation mode
+ *  @param  string              $varlink        Add a variable into the address of the page
+ *	@return	void
+ */
+function journalHead($nom,$variante,$period,$periodlink,$description,$builddate,$exportlink='',$moreparam=array(),$calcmode='', $varlink='')
+{
+    global $langs;
+
+    if (empty($hselected)) $hselected='report';
+
+    print "\n\n<!-- debut cartouche journal -->\n";
+
+    if(! empty($varlink)) $varlink = '?'.$varlink;
+
+    $h=0;
+    $head[$h][0] = $_SERVER["PHP_SELF"].$varlink;
+    $head[$h][1] = $langs->trans("Journalization");
+    $head[$h][2] = 'journal';
+
+    dol_fiche_head($head, 'journal');
+
+    print '<form method="POST" action="'.$_SERVER["PHP_SELF"].$varlink.'">';
+    foreach($moreparam as $key => $value)
+    {
+        print '<input type="hidden" name="'.$key.'" value="'.$value.'">';
+    }
+    print '<table width="100%" class="border">';
+
+    // Ligne de titre
+    print '<tr>';
+    print '<td width="110">'.$langs->trans("Name").'</td>';
+    if (! $variantexxx) print '<td colspan="3">';
+    else print '<td>';
+    print $nom;
+    if ($variantexxx) print '</td><td colspan="2">'.$variantexxx;
+    print '</td>';
+    print '</tr>';
+
+    // Calculation mode
+    if ($calcmode)
+    {
+        print '<tr>';
+        print '<td width="110">'.$langs->trans("CalculationMode").'</td>';
+        if (! $variante) print '<td colspan="3">';
+        else print '<td>';
+        print $calcmode;
+        if ($variante) print '</td><td colspan="2">'.$variante;
+        print '</td>';
+        print '</tr>';
+    }
+
+    // Ligne de la periode d'analyse du rapport
+    print '<tr>';
+    print '<td>'.$langs->trans("ReportPeriod").'</td>';
+    if (! $periodlink) print '<td colspan="3">';
+    else print '<td>';
+    if ($period) print $period;
+    if ($periodlink) print '</td><td colspan="2">'.$periodlink;
+    print '</td>';
+    print '</tr>';
+
+    // Ligne de description
+    print '<tr>';
+    print '<td>'.$langs->trans("ReportDescription").'</td>';
+    print '<td colspan="3">'.$description.'</td>';
+    print '</tr>';
+
+    print '</table>';
+
+    print '<br><div class="center"><input type="submit" class="button" name="submit" value="'.$langs->trans("Refresh").'"></div>';
+
+    print '</form>';
+
+    dol_fiche_end();
+
+    print "\n<!-- fin cartouche journal -->\n\n";
+}
+
diff --git a/htdocs/core/lib/admin.lib.php b/htdocs/core/lib/admin.lib.php
index 2a734b5f161ea4eb09f1d7b254106a5ef6fd22dc..2016807efe9ca06d7e2f9a3dc00ae0c69061fd26 100644
--- a/htdocs/core/lib/admin.lib.php
+++ b/htdocs/core/lib/admin.lib.php
@@ -624,6 +624,11 @@ function defaultvalues_prepare_head()
     $head[$h][2] = 'sortorder';
     $h++;
 
+    $head[$h][0] = DOL_URL_ROOT."/admin/defaultvalues.php?mode=focus";
+    $head[$h][1] = $langs->trans("DefaultFocus");
+    $head[$h][2] = 'focus';
+    $h++;
+
     /*$head[$h][0] = DOL_URL_ROOT."/admin/translation.php?mode=searchkey";
     $head[$h][1] = $langs->trans("TranslationKeySearch");
     $head[$h][2] = 'searchkey';
@@ -807,7 +812,7 @@ function activateModule($value,$withdeps=1)
         return $ret;
     }
 
-    $result=$objMod->init();
+    $result=$objMod->init();    // Enable module
     if ($result <= 0) 
     {
         $ret['errors'][]=$objMod->error;
diff --git a/htdocs/core/lib/agenda.lib.php b/htdocs/core/lib/agenda.lib.php
index 1f83690b096b357e0650c8f751d188917f27bacc..4e9b458c3d0b54715801f3179e8dc48f64714a3d 100644
--- a/htdocs/core/lib/agenda.lib.php
+++ b/htdocs/core/lib/agenda.lib.php
@@ -76,7 +76,7 @@ function print_actions_filter($form, $canedit, $status, $year, $month, $day, $sh
 		print '<td class="nowrap" style="padding-bottom: 2px; padding-right: 4px;">';
 		print $langs->trans("ActionsToDoBy").' &nbsp; ';
 		print '</td><td style="padding-bottom: 2px; padding-right: 4px;">';
-		print $form->select_dolusers($filtert, 'usertodo', 1, '', ! $canedit, '', '', 0, 0, 0, '', 0, '', 'maxwidth300');
+		print $form->select_dolusers($filtert, 'filtert', 1, '', ! $canedit, '', '', 0, 0, 0, '', 0, '', 'maxwidth300');
 		if (empty($conf->dol_optimize_smallscreen)) print ' &nbsp; '.$langs->trans("or") . ' '.$langs->trans("ToUserOfGroup").' &nbsp; ';
 		print $form->select_dolgroups($usergroupid, 'usergroup', 1, '', ! $canedit);
 		print '</td></tr>';
diff --git a/htdocs/core/lib/ajax.lib.php b/htdocs/core/lib/ajax.lib.php
index 942c17f5df9938e1c91978f3a55040f064155de8..9ba57abf302bc7f395c379772941a2f725ce7e34 100644
--- a/htdocs/core/lib/ajax.lib.php
+++ b/htdocs/core/lib/ajax.lib.php
@@ -181,10 +181,12 @@ function ajax_autocompleter($selected, $htmlname, $url, $urloption='', $minLengt
     							});
     						}
     						console.log("ajax_autocompleter new value selected, we trigger change on original component so field #search_'.$htmlname.'");
+							
     						$("#search_'.$htmlname.'").trigger("change");	// We have changed value of the combo select, we must be sure to trigger all js hook binded on this event. This is required to trigger other javascript change method binded on original field by other code.
     					}
     					,delay: 500
 					}).data("ui-autocomplete")._renderItem = function( ul, item ) {
+						  
 						return $("<li>")
 						.data( "ui-autocomplete-item", item ) // jQuery UI > 1.10.0
 						.append( \'<a><span class="tag">\' + item.label + "</span></a>" )
@@ -349,7 +351,7 @@ function ajax_dialog($title,$message,$w=350,$h=150)
 
 
 /**
- * Make a input box content all selected
+ * Make content of an input box selected when we click into input field.
  * 
  * @param string	$htmlname	Id of html object 
  * @param int		$addlink	Add a link to after
diff --git a/htdocs/core/lib/company.lib.php b/htdocs/core/lib/company.lib.php
index 809a045bacffee3634982e52263bc4c175eb6ae1..6847cd7b9c2b7e61339c9ce5455e7a926d1bf635 100644
--- a/htdocs/core/lib/company.lib.php
+++ b/htdocs/core/lib/company.lib.php
@@ -496,6 +496,55 @@ function getFormeJuridiqueLabel($code)
     }
 }
 
+/**
+ *  Return if a country is inside the EEC (European Economic Community)
+ *  TODO Add a field into country dictionary.
+ *  
+ *  @param      Object      $object    Object
+ *  @return     boolean		           true = country inside EEC, false = country outside EEC
+ */
+function isInEEC($object)
+{
+    // List of all country codes that are in europe for european vat rules
+    // List found on http://ec.europa.eu/taxation_customs/common/faq/faq_1179_en.htm#9
+    $country_code_in_EEC=array(
+        'AT',	// Austria
+        'BE',	// Belgium
+        'BG',	// Bulgaria
+        'CY',	// Cyprus
+        'CZ',	// Czech republic
+        'DE',	// Germany
+        'DK',	// Danemark
+        'EE',	// Estonia
+        'ES',	// Spain
+        'FI',	// Finland
+        'FR',	// France
+        'GB',	// United Kingdom
+        'GR',	// Greece
+        'HR',   // Croatia
+        'NL',	// Holland
+        'HU',	// Hungary
+        'IE',	// Ireland
+        'IM',	// Isle of Man - Included in UK
+        'IT',	// Italy
+        'LT',	// Lithuania
+        'LU',	// Luxembourg
+        'LV',	// Latvia
+        'MC',	// Monaco - Included in France
+        'MT',	// Malta
+        //'NO',	// Norway
+        'PL',	// Poland
+        'PT',	// Portugal
+        'RO',	// Romania
+        'SE',	// Sweden
+        'SK',	// Slovakia
+        'SI',	// Slovenia
+        'UK',	// United Kingdom
+        //'CH',	// Switzerland - No. Swizerland in not in EEC
+    );
+    //print "dd".$this->country_code;
+    return in_array($object->country_code, $country_code_in_EEC);
+}
 
 
 /**
diff --git a/htdocs/core/lib/files.lib.php b/htdocs/core/lib/files.lib.php
index 77da09b3d647310ddbaecf9d405f634de6922dfc..3d33fcb71f2c7019f06ac34067027e385f064591 100644
--- a/htdocs/core/lib/files.lib.php
+++ b/htdocs/core/lib/files.lib.php
@@ -1495,10 +1495,10 @@ function dol_uncompress($inputfile,$outputdir)
 {
     global $conf, $langs;
 
-    if (defined('ODTPHP_PATHTOPCLZIP'))
+    if (! empty($conf->global->ODTPHP_PATHTOPCLZIP))
     {
-    	dol_syslog("Constant ODTPHP_PATHTOPCLZIP for pclzip library is set to ".constant('ODTPHP_PATHTOPCLZIP').", so we use Pclzip to unzip into ".$outputdir);
-        include_once ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php';
+    	dol_syslog("Constant ODTPHP_PATHTOPCLZIP for pclzip library is set to ".$conf->global->ODTPHP_PATHTOPCLZIP.", so we use Pclzip to unzip into ".$outputdir);
+        include_once $conf->global->ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php';
         $archive = new PclZip($inputfile);
         $result=$archive->extract(PCLZIP_OPT_PATH, $outputdir);
         //var_dump($result);
@@ -1628,8 +1628,26 @@ function dol_check_secure_access_document($modulepart,$original_file,$entity,$fu
 	// Wrapping pour les apercu intervention
 	elseif (($modulepart == 'apercufichinter' || $modulepart == 'apercuficheinter') && !empty($conf->ficheinter->dir_output))
 	{
-		if ($fuser->rights->ficheinter->lire) $accessallowed=1;
-		$original_file=$conf->ficheinter->dir_output.'/'.$original_file;
+	    if ($fuser->rights->ficheinter->lire) $accessallowed=1;
+	    $original_file=$conf->ficheinter->dir_output.'/'.$original_file;
+	}
+	// Wrapping pour les apercu supplier proposal
+	elseif (($modulepart == 'apercusupplier_proposal' || $modulepart == 'apercusupplier_proposal') && !empty($conf->supplier_proposal->dir_output))
+	{
+	    if ($fuser->rights->supplier_proposal->lire) $accessallowed=1;
+	    $original_file=$conf->supplier_proposal->dir_output.'/'.$original_file;
+	}
+	// Wrapping pour les apercu supplier order
+	elseif (($modulepart == 'apercusupplier_order' || $modulepart == 'apercusupplier_order') && !empty($conf->fournisseur->commande->dir_output))
+	{
+	    if ($fuser->rights->fournisseur->commande->lire) $accessallowed=1;
+	    $original_file=$conf->fournisseur->commande->dir_output.'/'.$original_file;
+	}
+	// Wrapping pour les apercu supplier invoice
+	elseif (($modulepart == 'apercusupplier_invoice' || $modulepart == 'apercusupplier_invoice') && !empty($conf->fournisseur->facture->dir_output))
+	{
+	    if ($fuser->rights->fournisseur->facture->lire) $accessallowed=1;
+	    $original_file=$conf->fournisseur->facture->dir_output.'/'.$original_file;
 	}
 	// Wrapping pour les images des stats propales
 	elseif ($modulepart == 'propalstats' && !empty($conf->propal->dir_temp))
@@ -2040,7 +2058,7 @@ function dol_check_secure_access_document($modulepart,$original_file,$entity,$fu
 	}
 
 	// Wrapping pour les dons
-	else if ($modulepart == 'donation' && !empty($conf->donation->dir_output))
+	else if ($modulepart == 'donation' && !empty($conf->don->dir_output))
 	{
 		if ($fuser->rights->don->lire || preg_match('/^specimen/i',$original_file))
 		{
diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php
index 0d54593f0db6182a2057534bbccd530a7963ba9a..e3c6cb7d5cd0718d32d28cee5d295f68eb39be8e 100644
--- a/htdocs/core/lib/functions.lib.php
+++ b/htdocs/core/lib/functions.lib.php
@@ -248,70 +248,74 @@ function dol_shutdown()
  */
 function GETPOST($paramname, $check='', $method=0, $filter=NULL, $options=NULL)
 {
-	if (empty($method))
-	{
-		$out = isset($_GET[$paramname])?$_GET[$paramname]:(isset($_POST[$paramname])?$_POST[$paramname]:'');
-
-		// Management of default values
-		if (! isset($_GET['sortfield']))	// If we did a click on a field to sort, we do no apply default values
-		{
-		    if (! empty($_GET['action']) && $_GET['action'] == 'create' && ! empty($paramname) && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname]))
-			{
-				$relativepathstring = $_SERVER["PHP_SELF"];
-				if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring);
-				$relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
-				$relativepathstring = preg_replace('/^\//', '', $relativepathstring);
-				global $user;
-				if (! empty($user->default_values))		// $user->default_values defined from menu default values, and values loaded not at first 
-				{
-					//var_dump($user->default_values[$relativepathstring]['createform']);
-					if (isset($user->default_values[$relativepathstring]['createform'][$paramname])) $out = $user->default_values[$relativepathstring]['createform'][$paramname];
-				}
-			}
-			// Management of default search_filters and sort order
-			elseif (preg_match('/list.php$/', $_SERVER["PHP_SELF"]) && ! empty($paramname) && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname]))
-			{
-			    $relativepathstring = $_SERVER["PHP_SELF"];
-				if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring);
-				$relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
-				$relativepathstring = preg_replace('/^\//', '', $relativepathstring);
-				global $user;
-				if (! empty($user->default_values))		// $user->default_values defined from menu default values, and values loaded not at first 
-				{
-				    //var_dump($user->default_values[$relativepathstring]);
-        			if ($paramname == 'sortfield')
-        			{
-        			    if (isset($user->default_values[$relativepathstring]['sortorder'])) 
-        			    {
-        			        foreach($user->default_values[$relativepathstring]['sortorder'] as $key => $val)
-        			        {
-        			            if ($out) $out.=', ';
-        			            $out.=$key;
-        			        }
-        			    }
-        			}
-        			elseif ($paramname == 'sortorder')
-        			{
-        			    if (isset($user->default_values[$relativepathstring]['sortorder'])) 
-        			    {
-        			        foreach($user->default_values[$relativepathstring]['sortorder'] as $key => $val)
-        			        {
-        			            if ($out) $out.=', ';
-        			            $out.=$val;
-        			        }
-        			    }
-        			}
-				    elseif (isset($user->default_values[$relativepathstring]['filters'][$paramname])) $out = $user->default_values[$relativepathstring]['filters'][$paramname];
-				}
-			}
-		}
-	}
+    if (empty($method)) $out = isset($_GET[$paramname])?$_GET[$paramname]:(isset($_POST[$paramname])?$_POST[$paramname]:'');
 	elseif ($method==1) $out = isset($_GET[$paramname])?$_GET[$paramname]:'';
 	elseif ($method==2) $out = isset($_POST[$paramname])?$_POST[$paramname]:'';
 	elseif ($method==3) $out = isset($_POST[$paramname])?$_POST[$paramname]:(isset($_GET[$paramname])?$_GET[$paramname]:'');
 	elseif ($method==4) $out = isset($_POST[$paramname])?$_POST[$paramname]:(isset($_GET[$paramname])?$_GET[$paramname]:(isset($_COOKIE[$paramname])?$_COOKIE[$paramname]:''));
 	else return 'BadThirdParameterForGETPOST';
-
+	
+	if (empty($method) || $method == 3 || $method == 4)
+	{
+	    global $conf;
+	    
+	    // Management of default values
+	    if (! isset($_GET['sortfield']) && ! empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES))	// If we did a click on a field to sort, we do no apply default values. Same if option MAIN_DISABLE_DEFAULT_VALUES is on
+	    {
+	        if (! empty($_GET['action']) && $_GET['action'] == 'create' && ! empty($paramname) && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname]))
+	        {
+	            $relativepathstring = $_SERVER["PHP_SELF"];
+	            if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring);
+	            $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
+	            $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
+	            global $user;
+	            if (! empty($user->default_values))		// $user->default_values defined from menu default values, and values loaded not at first
+	            {
+	                //var_dump($user->default_values[$relativepathstring]['createform']);
+	                if (isset($user->default_values[$relativepathstring]['createform'][$paramname])) $out = $user->default_values[$relativepathstring]['createform'][$paramname];
+	            }
+	        }
+	        // Management of default search_filters and sort order
+	        //elseif (preg_match('/list.php$/', $_SERVER["PHP_SELF"]) && ! empty($paramname) && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname]))
+	        elseif (! empty($paramname) && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname]))
+	        {
+	            $relativepathstring = $_SERVER["PHP_SELF"];
+	            if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring);
+	            $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
+	            $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
+	            global $user;
+	            if (! empty($user->default_values))		// $user->default_values defined from menu default values
+	            {
+	                //var_dump($user->default_values[$relativepathstring]);
+	                if ($paramname == 'sortfield')
+	                {
+	                    if (isset($user->default_values[$relativepathstring]['sortorder']))
+	                    {
+	                        foreach($user->default_values[$relativepathstring]['sortorder'] as $key => $val)
+	                        {
+	                            if ($out) $out.=', ';
+	                            $out.=dol_string_nospecial($key, '');
+	                        }
+	                    }
+	                }
+	                elseif ($paramname == 'sortorder')
+	                {
+	                    if (isset($user->default_values[$relativepathstring]['sortorder']))
+	                    {
+	                        foreach($user->default_values[$relativepathstring]['sortorder'] as $key => $val)
+	                        {
+	                            if ($out) $out.=', ';
+	                            $out.=dol_string_nospecial($val, '');
+	                        }
+	                    }
+	                }
+	                elseif (isset($user->default_values[$relativepathstring]['filters'][$paramname]))
+	                $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$paramname], '');
+	            }
+	        }
+	    }
+	}	
+	
 	if (! empty($check))
 	{
 	    // Replace vars like __DAY__, __MONTH__, __YEAR__, __MYCOUNTRYID__, __USERID__, __ENTITYID__
@@ -1065,11 +1069,12 @@ function dol_banner_tab($object, $paramid, $morehtml='', $shownav=1, $fieldid='r
 	if (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) $showbarcode=0;
 	$modulepart='unknown';
 
-	if ($object->element == 'societe')   $modulepart='societe';
-	if ($object->element == 'contact')   $modulepart='contact';
-	if ($object->element == 'member')    $modulepart='memberphoto';
-	if ($object->element == 'user')      $modulepart='userphoto';
-	if ($object->element == 'product')   $modulepart='product';
+	if ($object->element == 'societe')         $modulepart='societe';
+	if ($object->element == 'contact')         $modulepart='contact';
+	if ($object->element == 'member')          $modulepart='memberphoto';
+	if ($object->element == 'user')            $modulepart='userphoto';
+	if ($object->element == 'product')         $modulepart='product';
+
 	if (class_exists("Imagick"))
 	{
 		if ($object->element == 'propal')    $modulepart='propal';
@@ -1077,6 +1082,9 @@ function dol_banner_tab($object, $paramid, $morehtml='', $shownav=1, $fieldid='r
 		if ($object->element == 'facture')   $modulepart='facture';
 		if ($object->element == 'fichinter') $modulepart='ficheinter';
 		if ($object->element == 'contrat')   $modulepart='contract';
+	    if ($object->element == 'supplier_proposal') $modulepart='supplier_proposal';
+		if ($object->element == 'order_supplier')    $modulepart='supplier_order';
+	    if ($object->element == 'invoice_supplier')  $modulepart='supplier_invoice';
 	}
 
 	if ($object->element == 'product')
@@ -1102,19 +1110,26 @@ function dol_banner_tab($object, $paramid, $morehtml='', $shownav=1, $fieldid='r
 	{
 		if ($showimage)
         {
-        	if ($modulepart != 'unknown')
+            if ($modulepart != 'unknown')
             {
                 $phototoshow='';
-                
                 // Check if a preview file is available
-                if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract')) && class_exists("Imagick"))
+                if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice')) && class_exists("Imagick"))
                 {
                     $objectref = dol_sanitizeFileName($object->ref);
                     $dir_output = $conf->$modulepart->dir_output . "/";
-                    $filepath = $dir_output . $objectref . "/";
+                    if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice')))
+                    {
+                        $subdir = get_exdir($object->id, 2, 0, 0, $object, $modulepart).$objectref;
+                    }
+                    else
+                    {
+                        $subdir = get_exdir($object->id, 0, 0, 0, $object, $modulepart).$objectref;
+                    }
+                    $filepath = $dir_output . $subdir . "/";
                     $file = $filepath . $objectref . ".pdf";
-                    $relativepath = $objectref.'/'.$objectref.'.pdf';
-                    
+                    $relativepath = $subdir.'/'.$objectref.'.pdf';
+
                     // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png")
                     $fileimage = $file.'_preview.png';              // If PDF has 1 page
                     $fileimagebis = $file.'_preview-0.png';         // If PDF has more than one page
@@ -1137,7 +1152,7 @@ function dol_banner_tab($object, $paramid, $morehtml='', $shownav=1, $fieldid='r
                         if (file_exists($fileimage))
                         {
                             $phototoshow = '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
-                            $phototoshow.= '<img height="70" class="photo photowithmargin" src="'.DOL_URL_ROOT . '/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($relativepathimage).'">';
+                            $phototoshow.= '<img height="70" class="photo photowithmargin photowithborder" src="'.DOL_URL_ROOT . '/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($relativepathimage).'">';
                             $phototoshow.= '</div></div>';
                         }
                         // Si fichier png PDF de plus d'1 page trouve
@@ -1145,7 +1160,7 @@ function dol_banner_tab($object, $paramid, $morehtml='', $shownav=1, $fieldid='r
                         {
                             $preview = preg_replace('/\.png/','',$relativepathimage) . "-0.png";
                             $phototoshow = '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
-                            $phototoshow.= '<img height="70" class="photo photowithmargin" src="'.DOL_URL_ROOT . '/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($preview).'"><p>';
+                            $phototoshow.= '<img height="70" class="photo photowithmargin photowithborder" src="'.DOL_URL_ROOT . '/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($preview).'"><p>';
                             $phototoshow.= '</div></div>';
                         }
                     }
@@ -1171,7 +1186,6 @@ function dol_banner_tab($object, $paramid, $morehtml='', $shownav=1, $fieldid='r
                     $width=80;
                     $cssclass='photorefcenter';
                     $nophoto=img_picto('', 'title_agenda', '', false, 1);
-                    $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref"><img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="No photo" border="0"'.($width?' width="'.$width.'"':'').' src="'.$nophoto.'"></div></div>';
                 }
                 else
                 {
@@ -1179,8 +1193,8 @@ function dol_banner_tab($object, $paramid, $morehtml='', $shownav=1, $fieldid='r
                     $picto = $object->picto;
                     if ($object->element == 'project' && ! $object->public) $picto = 'project'; // instead of projectpub
     				$nophoto=img_picto('', 'object_'.$picto, '', false, 1);
-    				$morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref"><img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="No photo" border="0"'.($width?' width="'.$width.'"':'').' src="'.$nophoto.'"></div></div>';
                 }
+                $morehtmlleft.='<!-- No photo to show --><div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref"><img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="No photo" border="0"'.($width?' width="'.$width.'"':'').' src="'.$nophoto.'"></div></div>';
                 $morehtmlleft.='</div>';
             }
         }
@@ -3328,7 +3342,7 @@ function load_fiche_titre($titre, $morehtmlright='', $picto='title_generic.png',
 
 	$return.= "\n";
 	$return.= '<table '.($id?'id="'.$id.'" ':'').'summary="" class="centpercent notopnoleftnoright'.($morecssontable?' '.$morecssontable:'').'" style="margin-bottom: 2px;"><tr>';
-	if ($picto) $return.= '<td class="nobordernopadding widthpictotitle" valign="middle">'.img_picto('',$picto, 'id="pictotitle"', $pictoisfullpath).'</td>';
+	if ($picto) $return.= '<td class="nobordernopadding widthpictotitle" valign="middle">'.img_picto('',$picto, 'class="valignmiddle" id="pictotitle"', $pictoisfullpath).'</td>';
 	$return.= '<td class="nobordernopadding" valign="middle">';
 	$return.= '<div class="titre">'.$titre.'</div>';
 	$return.= '</td>';
@@ -3570,14 +3584,14 @@ function vatrate($rate, $addpercent=false, $info_bits=0, $usestarfornpr=0)
 	    $morelabel=' ('.$reg[1].')';
 	    $rate=preg_replace('/\s*'.preg_quote($morelabel,'/').'/','',$rate);
 	}
-	if (preg_match('/\*/',$rate) || preg_match('/'.constant('MAIN_LABEL_MENTION_NPR').'/i',$rate))
+	if (preg_match('/\*/',$rate))
 	{
 		$rate=str_replace('*','',$rate);
 		$info_bits |= 1;
 	}
 
 	$ret=price($rate,0,'',0,0).($addpercent?'%':'');
-	if ($info_bits & 1) $ret.=' '.($usestarfornpr?'*':constant('MAIN_LABEL_MENTION_NPR'));
+	if ($info_bits & 1) $ret.=' *';
 	$ret.=$morelabel;
 	return $ret;
 }
@@ -4466,7 +4480,8 @@ function yn($yesno, $case=1, $color=0)
 
 /**
  *	Return a path to have a directory according to object.
- *  New usage:       $conf->product->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, 'modulepart')
+ *  New usage:       $conf->module->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, 'modulepart')
+ *         or:       $conf->module->dir_output.'/'.get_exdir(0, 0, 0, 1, $object, 'modulepart')     if multidir_output not defined.
  *  Old usage:       '015' with level 3->"0/1/5/", '015' with level 1->"5/", 'ABC-1' with level 3 ->"0/0/1/"
  *
  *	@param	string	$num            Id of object (deprecated, $object will be used in future)
@@ -4487,7 +4502,7 @@ function get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart)
 	if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) $arrayforoldpath[]='product';
 	if (! empty($level) && in_array($modulepart, $arrayforoldpath))
 	{
-		// This part should be removed once all code is using "get_exdir" to forge path, with all parameters provided
+		// This part should be removed once all code is using "get_exdir" to forge path, with all parameters provided.
 		if (empty($alpha)) $num = preg_replace('/([^0-9])/i','',$num);
 		else $num = preg_replace('/^.*\-/i','',$num);
 		$num = substr("000".$num, -$level);
@@ -4953,7 +4968,8 @@ function make_substitutions($text, $substitutionarray, $outputlangs=null)
 }
 
 /**
- *  Complete the $substitutionarray with more entries
+ *  Complete the $substitutionarray with more entries.
+ *  Can also add substitution keys coming from external module that had set the "substitutions=1" into module_part array. In this case, method completesubstitutionarray provided by module is called. 
  *
  *  @param  array		$substitutionarray		Array substitution old value => new value value
  *  @param  Translate	$outputlangs            Output language
diff --git a/htdocs/core/lib/functions2.lib.php b/htdocs/core/lib/functions2.lib.php
index 66d66ec7c8f4f7fb47e0ac065baab943ab0068d4..b36da63163593c74f8d2d2269da9d3970e5ce7e3 100644
--- a/htdocs/core/lib/functions2.lib.php
+++ b/htdocs/core/lib/functions2.lib.php
@@ -1161,7 +1161,7 @@ function check_value($mask,$value)
 
     // If an offset is asked
     if (! empty($reg[2]) && preg_match('/^\+/',$reg[2])) $maskoffset=preg_replace('/^\+/','',$reg[2]);
-    if (! empty($reg[3]) && preg_match('^\+',$reg[3])) $maskoffset=preg_replace('/^\+/','',$reg[3]);
+    if (! empty($reg[3]) && preg_match('/^\+/',$reg[3])) $maskoffset=preg_replace('/^\+/','',$reg[3]);
 
     // Define $sqlwhere
 
diff --git a/htdocs/core/lib/pdf.lib.php b/htdocs/core/lib/pdf.lib.php
index 282bdec690e0ffb53bf0945c824a154dddc19194..e83faee6c8dd54b57f9cfcc1982ea7e67afb5787 100644
--- a/htdocs/core/lib/pdf.lib.php
+++ b/htdocs/core/lib/pdf.lib.php
@@ -599,7 +599,14 @@ function pdf_getSubstitutionArray($outputlangs)
 	$substitutionarray=array(
 		'__MYCOMPANY_NAME__' => $mysoc->name,
 		'__MYCOMPANY_EMAIL__' => $mysoc->email,
-		'__USER_ID__' => $user->id,
+		'__MYCOMPANY_PROFID1__' => $mysoc->idprof1,
+		'__MYCOMPANY_PROFID2__' => $mysoc->idprof2,
+		'__MYCOMPANY_PROFID3__' => $mysoc->idprof3,
+		'__MYCOMPANY_PROFID4__' => $mysoc->idprof4,
+		'__MYCOMPANY_PROFID5__' => $mysoc->idprof5,
+		'__MYCOMPANY_PROFID6__' => $mysoc->idprof6,
+		'__MYCOMPANY_CAPITAL__' => $mysoc->capital,
+	    '__USER_ID__' => $user->id,
 		'__USER_LOGIN__' => $user->login,
 		'__USER_LASTNAME__' => $user->lastname,
 		'__USER_FIRSTNAME__' => $user->firstname,
@@ -1808,8 +1815,17 @@ function pdf_getlineprogress($object, $i, $outputlangs, $hidedetails = 0, $hookm
 	}
 	if (empty($reshook))
 	{
-        if ($object->lines[$i]->special_code == 3) return '';
-	    if (empty($hidedetails) || $hidedetails > 1) $result.=$object->lines[$i]->situation_percent . '%';
+        	if ($object->lines[$i]->special_code == 3) return '';
+		if (empty($hidedetails) || $hidedetails > 1)
+		{
+			if($conf->global->SITUATION_DISPLAY_DIFF_ON_PDF)
+			{
+			 	$prev_progress = $object->lines[$i]->get_prev_progress($object->id);
+			 	$result = ( $object->lines[$i]->situation_percent - $prev_progress) . '%';
+			}
+			else
+				$result = $object->lines[$i]->situation_percent . '%';
+	  	}
 	}
 	return $result;
 }
@@ -1844,7 +1860,7 @@ function pdf_getlinetotalexcltax($object,$i,$outputlangs,$hidedetails=0)
 		if(!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
 	}
     if (empty($reshook))
-	{
+    {
 	    if ($object->lines[$i]->special_code == 3)
     	{
     		return $outputlangs->transnoentities("Option");
@@ -1852,9 +1868,16 @@ function pdf_getlinetotalexcltax($object,$i,$outputlangs,$hidedetails=0)
         if (empty($hidedetails) || $hidedetails > 1)
         {
         	$total_ht = ($conf->multicurrency->enabled && $object->multicurrency_tx != 1 ? $object->lines[$i]->multicurrency_total_ht : $object->lines[$i]->total_ht);
+        	if ($object->lines[$i]->situation_percent > 0 )
+        	{
+		 	$prev_progress = $object->lines[$i]->get_prev_progress($object->id);
+		 	$progress = ( $object->lines[$i]->situation_percent - $prev_progress) /100;
+		 	$result.=price($sign * ($total_ht/($object->lines[$i]->situation_percent/100)) * $progress, 0, $outputlangs);
+		}
+        	else
 			$result.=price($sign * $total_ht, 0, $outputlangs);
-        }
 	}
+    }
 	return $result;
 }
 
diff --git a/htdocs/core/lib/report.lib.php b/htdocs/core/lib/report.lib.php
index f58aa180d8829813edbfa1df8a1fc2ce2843afb2..2c13485d0e93a3b7466f1c40ae9cf23e9fb2fdde 100644
--- a/htdocs/core/lib/report.lib.php
+++ b/htdocs/core/lib/report.lib.php
@@ -24,20 +24,20 @@
 
 
 /**
-*	Show header of a VAT report
-*
-*	@param	string				$nom            Name of report
-*	@param 	string				$variante       Link for alternate report
-*	@param 	string				$period         Period of report
-*	@param 	string				$periodlink     Link to switch period
-*	@param 	string				$description    Description
-*	@param 	timestamp|integer	$builddate      Date generation
-*	@param 	string				$exportlink     Link for export or ''
-*	@param	array				$moreparam		Array with list of params to add into form
-*	@param	string				$calcmode		Calculation mode
-*   @param  string              $varlink        Add a variable into the address of the page
-*	@return	void
-*/
+ *	Show header of a VAT report
+ *
+ *	@param	string				$nom            Name of report
+ *	@param 	string				$variante       Link for alternate report
+ *	@param 	string				$period         Period of report
+ *	@param 	string				$periodlink     Link to switch period
+ *	@param 	string				$description    Description
+ *	@param 	timestamp|integer	$builddate      Date generation
+ *	@param 	string				$exportlink     Link for export or ''
+ *	@param	array				$moreparam		Array with list of params to add into form
+ *	@param	string				$calcmode		Calculation mode
+ *   @param  string              $varlink        Add a variable into the address of the page
+ *	@return	void
+ */
 function report_header($nom,$variante,$period,$periodlink,$description,$builddate,$exportlink='',$moreparam=array(),$calcmode='', $varlink='')
 {
 	global $langs;
diff --git a/htdocs/core/lib/security2.lib.php b/htdocs/core/lib/security2.lib.php
index cadf133169dab954563e0fdfc5126c440755164f..a14645a3152e1fd8f6c69447770b84fbeb2602fe 100644
--- a/htdocs/core/lib/security2.lib.php
+++ b/htdocs/core/lib/security2.lib.php
@@ -150,9 +150,9 @@ function dol_loginfunction($langs,$conf,$mysoc)
 
 	// Title
 	$appli=constant('DOL_APPLICATION_TITLE');
-	$title=$appli.' '.DOL_VERSION;
+	$title=$appli.' '.constant('DOL_VERSION');
 	if (! empty($conf->global->MAIN_APPLICATION_TITLE)) $title=$conf->global->MAIN_APPLICATION_TITLE;
-	$titletruedolibarrversion=DOL_VERSION;	// $title used by login template after the @ to inform of true Dolibarr version
+	$titletruedolibarrversion=constant('DOL_VERSION');	// $title used by login template after the @ to inform of true Dolibarr version
 
 	// Note: $conf->css looks like '/theme/eldy/style.css.php'
 	$conf->css = "/theme/".(GETPOST('theme')?GETPOST('theme','alpha'):$conf->theme)."/style.css.php";
@@ -197,12 +197,6 @@ function dol_loginfunction($langs,$conf,$mysoc)
 	if (! GETPOST("username")) $focus_element='username';
 	else $focus_element='password';
 
-	$login_background=DOL_URL_ROOT.'/theme/login_background.png';
-	if (file_exists(DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/login_background.png'))
-	{
-		$login_background=DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/login_background.png';
-	}
-
 	$demologin='';
 	$demopassword='';
 	if (! empty($dolibarr_main_demo))
diff --git a/htdocs/core/lib/usergroups.lib.php b/htdocs/core/lib/usergroups.lib.php
index 4350edc37972778dc3626788ffbd7c0dd29e78ea..3b3cde1d66a8066c0be0f98a974db89040667b1d 100644
--- a/htdocs/core/lib/usergroups.lib.php
+++ b/htdocs/core/lib/usergroups.lib.php
@@ -59,6 +59,11 @@ function user_prepare_head($object)
 	    $h++;
 	}
 
+    $head[$h][0] = DOL_URL_ROOT.'/user/param_ihm.php?id='.$object->id;
+    $head[$h][1] = $langs->trans("UserGUISetup");
+    $head[$h][2] = 'guisetup';
+    $h++;
+
 	if ($canreadperms)
 	{
 		$head[$h][0] = DOL_URL_ROOT.'/user/perms.php?id='.$object->id;
@@ -67,15 +72,27 @@ function user_prepare_head($object)
 		$h++;
 	}
 
-    $head[$h][0] = DOL_URL_ROOT.'/user/param_ihm.php?id='.$object->id;
-    $head[$h][1] = $langs->trans("UserGUISetup");
-    $head[$h][2] = 'guisetup';
-    $h++;
-
     if (! empty($conf->agenda->enabled))
     {
+        if (empty($conf->global->AGENDA_EXT_NB)) $conf->global->AGENDA_EXT_NB=5;
+        $MAXAGENDA=$conf->global->AGENDA_EXT_NB;
+        
+        $i=1;
+        $nbagenda = 0;
+        while ($i <= $MAXAGENDA)
+        {
+            $key=$i;
+            $name='AGENDA_EXT_NAME_'.$object->id.'_'.$key;
+            $src='AGENDA_EXT_SRC_'.$object->id.'_'.$key;
+            $offsettz='AGENDA_EXT_OFFSETTZ_'.$object->id.'_'.$key;
+            $color='AGENDA_EXT_COLOR_'.$object->id.'_'.$key;
+            $i++;
+        
+            if (! empty($object->conf->$name)) $nbagenda++;
+        }
+        
 	    $head[$h][0] = DOL_URL_ROOT.'/user/agenda_extsites.php?id='.$object->id;
-	    $head[$h][1] = $langs->trans("ExtSites");
+	    $head[$h][1] = $langs->trans("ExtSites").($nbagenda ? ' <span class="badge">'.$nbagenda.'</span>' : '');
 	    $head[$h][2] = 'extsites';
 	    $h++;
     }
@@ -426,7 +443,7 @@ function show_theme($fuser,$edit=0,$foruserprofile=false)
 
     print '</td></tr>';
 
-	// BackgroundColor
+	// Background color THEME_ELDY_BACKBODY
     if ($foruserprofile)
 	{
 	    /*
@@ -609,7 +626,7 @@ function show_theme($fuser,$edit=0,$foruserprofile=false)
 	    {
 	        print $formother->showColor($conf->global->THEME_ELDY_TEXTTITLENOTAB, $langs->trans("Default"));
 	    }
-	    print ' &nbsp; ('.$langs->trans("Default").': <strong>3c3c14</strong>) ';
+	    print ' &nbsp; ('.$langs->trans("Default").': <strong><span style="color: #3c3c14">3c3c14</span></strong>) ';
     	print $form->textwithpicto('', $langs->trans("NotSupportedByAllThemes").', '.$langs->trans("PressF5AfterChangingThis"));
 	    
 	    print '</td>';
@@ -654,9 +671,14 @@ function show_theme($fuser,$edit=0,$foruserprofile=false)
 	    {
 	        $color = colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_TEXTLINK,array()),'');
 	        if ($color) print '<input type="text" class="colorthumb" disabled="disabled" style="padding: 1px; margin-top: 0; margin-bottom: 0; background-color: #'.$color.'" value="'.$color.'">';
-	        else print $langs->trans("Default");
+	        else 
+	        {
+	            //print '<input type="text" class="colorthumb" disabled="disabled" style="padding: 1px; margin-top: 0; margin-bottom: 0; background-color: #'.$defaultcolor.'" value="'.$langs->trans("Default").'">';
+	            //print '<span style="color: #000078">'.$langs->trans("Default").'</span>';
+	            print $langs->trans("Default");
+	        }
 	    }
-	    print ' &nbsp; ('.$langs->trans("Default").': <strong>000078</strong>) ';
+	    print ' &nbsp; ('.$langs->trans("Default").': <strong><span style="color: #000078">000078</span></strong>) ';
     	print $form->textwithpicto('', $langs->trans("NotSupportedByAllThemes").', '.$langs->trans("PressF5AfterChangingThis"));
 	    print '</td>';
 	}
diff --git a/htdocs/core/menus/init_menu_auguria.sql b/htdocs/core/menus/init_menu_auguria.sql
index 54cddfcaa963fc425f367da2ba7b1cafc3fe0bd9..9106c345fdac8082542c931818915676ff8ed43c 100644
--- a/htdocs/core/menus/init_menu_auguria.sql
+++ b/htdocs/core/menus/init_menu_auguria.sql
@@ -211,14 +211,15 @@ insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, left
 insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled', __HANDLER__, 'left', 2400__+MAX_llx_menu__, 'accountancy', 'accounting', 6__+MAX_llx_menu__, '/accountancy/index.php?leftmenu=accountancy', 'MenuAccountancy', 0, 'accountancy', '! empty($conf->accounting->enabled) || $user->rights->accounting->bind->write || $user->rights->accounting->bind->write || $user->rights->compta->resultat->lire', '', 0, 7, __ENTITY__);
 	-- Setup
 	insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled', __HANDLER__, 'left', 2451__+MAX_llx_menu__, 'accountancy', 'accountancy_admin',            2400__+MAX_llx_menu__, '/accountancy/index.php?mainmenu=accountancy&leftmenu=accountancy_admin', 'Setup', 1, 'accountancy', '$user->rights->accounting->chartofaccount', '', 0, 1, __ENTITY__);
-	insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2455__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_chartmodel',    2451__+MAX_llx_menu__, '/accountancy/admin/account.php?mainmenu=accountancy&leftmenu=accountancy_admin', 'Pcg_version', 2, 'accountancy', '$user->rights->accounting->chartofaccount', '', 0, 10, __ENTITY__);
-	insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2456__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_chart',         2451__+MAX_llx_menu__, '/accountancy/admin/account.php?mainmenu=accountancy&leftmenu=accountancy_admin', 'Chartofaccounts', 2, 'accountancy', '$user->rights->accounting->chartofaccount', '', 0, 20, __ENTITY__);
-	insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2457__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_chart_group',   2451__+MAX_llx_menu__, '/accountancy/admin/categories_list.php?id=32&mainmenu=accountancy&leftmenu=accountancy_admin', 'AccountingCategory', 2, 'accountancy', '$user->rights->accounting->chartofaccount', '', 0, 22, __ENTITY__);
-	insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2458__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_default',       2451__+MAX_llx_menu__, '/accountancy/admin/defaultaccounts.php?mainmenu=accountancy&leftmenu=accountancy_admin', 'MenuDefaultAccounts', 2, 'accountancy', '$user->rights->accounting->chartofaccount', '', 0, 30, __ENTITY__);
-	insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2459__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_vat',           2451__+MAX_llx_menu__, '/admin/dict.php?id=10&from=accountancy&search_country_id=__MYCOUNTRYID__&mainmenu=accountancy&leftmenu=accountancy_admin', 'MenuVatAccounts', 2, 'accountancy', '$user->rights->accounting->chartofaccount', '', 0, 40, __ENTITY__);
-	insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2460__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_tax',           2451__+MAX_llx_menu__, '/admin/dict.php?id=7&from=accountancy&search_country_id=__MYCOUNTRYID__&mainmenu=accountancy&leftmenu=accountancy_admin', 'MenuTaxAccounts', 2, 'accountancy', '$user->rights->accounting->chartofaccount', '', 0, 50, __ENTITY__);
-	insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2461__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_expensereport', 2451__+MAX_llx_menu__, '/admin/dict.php?id=17&from=accountancy&mainmenu=accountancy&leftmenu=accountancy_admin', 'MenuExpenseReportAccounts', 2, 'accountancy', '$user->rights->accounting->chartofaccount', '', 0, 60, __ENTITY__);
-	insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2462__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_product',       2451__+MAX_llx_menu__, '/accountancy/admin/productaccount.php?mainmenu=accountancy&leftmenu=accountancy_admin', 'MenuProductsAccounts', 2, 'accountancy', '$user->rights->accounting->chartofaccount', '', 0, 70, __ENTITY__);
+	insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2457__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_journal',       2451__+MAX_llx_menu__, '/accountancy/admin/journals_list.php?id=35&mainmenu=accountancy&leftmenu=accountancy_admin', 'AccountingJournals', 2, 'accountancy', '$user->rights->accounting->chartofaccount', '', 0, 10, __ENTITY__);
+	insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2455__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_chartmodel',    2451__+MAX_llx_menu__, '/accountancy/admin/account.php?mainmenu=accountancy&leftmenu=accountancy_admin', 'Pcg_version', 2, 'accountancy', '$user->rights->accounting->chartofaccount', '', 0, 20, __ENTITY__);
+	insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2456__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_chart',         2451__+MAX_llx_menu__, '/accountancy/admin/account.php?mainmenu=accountancy&leftmenu=accountancy_admin', 'Chartofaccounts', 2, 'accountancy', '$user->rights->accounting->chartofaccount', '', 0, 30, __ENTITY__);
+	insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2457__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_chart_group',   2451__+MAX_llx_menu__, '/accountancy/admin/categories_list.php?id=32&mainmenu=accountancy&leftmenu=accountancy_admin', 'AccountingCategory', 2, 'accountancy', '$user->rights->accounting->chartofaccount', '', 0, 40, __ENTITY__);
+	insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2458__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_default',       2451__+MAX_llx_menu__, '/accountancy/admin/defaultaccounts.php?mainmenu=accountancy&leftmenu=accountancy_admin', 'MenuDefaultAccounts', 2, 'accountancy', '$user->rights->accounting->chartofaccount', '', 0, 50, __ENTITY__);
+	insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2459__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_vat',           2451__+MAX_llx_menu__, '/admin/dict.php?id=10&from=accountancy&search_country_id=__MYCOUNTRYID__&mainmenu=accountancy&leftmenu=accountancy_admin', 'MenuVatAccounts', 2, 'accountancy', '$user->rights->accounting->chartofaccount', '', 0, 60, __ENTITY__);
+	insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2460__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_tax',           2451__+MAX_llx_menu__, '/admin/dict.php?id=7&from=accountancy&search_country_id=__MYCOUNTRYID__&mainmenu=accountancy&leftmenu=accountancy_admin', 'MenuTaxAccounts', 2, 'accountancy', '$user->rights->accounting->chartofaccount', '', 0, 70, __ENTITY__);
+	insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2461__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_expensereport', 2451__+MAX_llx_menu__, '/admin/dict.php?id=17&from=accountancy&mainmenu=accountancy&leftmenu=accountancy_admin', 'MenuExpenseReportAccounts', 2, 'accountancy', '$user->rights->accounting->chartofaccount', '', 0, 80, __ENTITY__);
+	insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2462__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_product',       2451__+MAX_llx_menu__, '/accountancy/admin/productaccount.php?mainmenu=accountancy&leftmenu=accountancy_admin', 'MenuProductsAccounts', 2, 'accountancy', '$user->rights->accounting->chartofaccount', '', 0, 90, __ENTITY__);
 	-- Binding
 	insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled', __HANDLER__, 'left', 2401__+MAX_llx_menu__, 'accountancy', 'dispatch_customer', 2400__+MAX_llx_menu__, '/accountancy/customer/index.php?leftmenu=dispatch_customer', 'CustomersVentilation', 1, 'accountancy', '$user->rights->accounting->bind->write', '', 0, 2, __ENTITY__);
 	insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled && $leftmenu=="dispatch_customer"', __HANDLER__, 'left', 2402__+MAX_llx_menu__, 'accountancy', '', 2401__+MAX_llx_menu__, '/accountancy/customer/list.php', 'ToDispatch', 2, 'accountancy', '$user->rights->accounting->bind->write', '', 0, 3, __ENTITY__);
diff --git a/htdocs/core/menus/standard/auguria.lib.php b/htdocs/core/menus/standard/auguria.lib.php
index e95359e5683b79fa4d113ed2db31088d4326f99e..d2d8e36b8ca595e6d06fc38769924e4870534fa9 100644
--- a/htdocs/core/menus/standard/auguria.lib.php
+++ b/htdocs/core/menus/standard/auguria.lib.php
@@ -269,7 +269,7 @@ function print_left_auguria_menu($db,$menu_array_before,$menu_array_after,&$tabM
 		print '<div class="menu_titre" id="menu_titre_logo"></div>';
 		print '<div class="menu_top" id="menu_top_logo"></div>';
 		print '<div class="menu_contenu" id="menu_contenu_logo">';
-		print '<div class="center"><img title="'.dol_escape_htmltag($title).'" alt="" src="'.$urllogo.'" style="max-width: 80%"></div>'."\n";
+		print '<div class="center"><img title="'.dol_escape_htmltag($title).'" alt="" src="'.$urllogo.'" style="max-width: 70%"></div>'."\n";
 		print '</div>';
 		print '<div class="menu_end" id="menu_end_logo"></div>';
 		print '</div>'."\n";
diff --git a/htdocs/core/menus/standard/eldy.lib.php b/htdocs/core/menus/standard/eldy.lib.php
index 360a93cf61b1bacfdcf78ec60b086c0741dfccb0..b7a372e50bda61a6f490ebf999592b67b5784e0d 100644
--- a/htdocs/core/menus/standard/eldy.lib.php
+++ b/htdocs/core/menus/standard/eldy.lib.php
@@ -165,7 +165,7 @@ function print_eldy_menu($db,$atarget,$type_user,&$tabMenu,&$menu,$noout=0,$mode
 	if (! empty($conf->loan->enabled)) $menuqualified++;
 	$tmpentry=array(
 	   'enabled'=>$menuqualified,
-	   'perms'=>(! empty($user->rights->compta->resultat->lire) || ! empty($user->rights->accounting->plancompte->lire) || ! empty($user->rights->facture->lire) || ! empty($user->rights->don->lire) || ! empty($user->rights->tax->charges->lire) || ! empty($user->rights->salaries->read) || ! empty($user->rights->fournisseur->facture->lire) || ! empty($user->rights->loan->read)),
+	   'perms'=>(! empty($user->rights->compta->resultat->lire) || ! empty($user->rights->accounting->mouvements->lire) || ! empty($user->rights->facture->lire) || ! empty($user->rights->don->lire) || ! empty($user->rights->tax->charges->lire) || ! empty($user->rights->salaries->read) || ! empty($user->rights->fournisseur->facture->lire) || ! empty($user->rights->loan->read)),
 	   'module'=>'comptabilite|accounting|facture|supplier_invoice|don|tax|salaries|loan');
 	$showmode=dol_eldy_showmenu($type_user, $tmpentry, $listofmodulesforexternal);
 	if ($showmode)
@@ -478,7 +478,7 @@ function print_left_eldy_menu($db,$menu_array_before,$menu_array_after,&$tabMenu
 		print '<div class="menu_titre" id="menu_titre_logo"></div>';
 		print '<div class="menu_top" id="menu_top_logo"></div>';
 		print '<div class="menu_contenu" id="menu_contenu_logo">';
-		print '<div class="center"><img class="mycompany" title="'.dol_escape_htmltag($title).'" alt="" src="'.$urllogo.'" style="max-width: 80%"></div>'."\n";
+		print '<div class="center"><img class="mycompany" title="'.dol_escape_htmltag($title).'" alt="" src="'.$urllogo.'" style="max-width: 70%"></div>'."\n";
 		print '</div>';
 		print '<div class="menu_end" id="menu_end_logo"></div>';
 		print '</div>'."\n";
@@ -545,7 +545,7 @@ function print_left_eldy_menu($db,$menu_array_before,$menu_array_after,&$tabMenu
 				$newmenu->add("/admin/ihm.php?mainmenu=home", $langs->trans("GUISetup"),1);
 
 				$newmenu->add("/admin/translation.php?mainmenu=home", $langs->trans("Translation"),1);
-				$newmenu->add("/admin/defaultvalues.php?mainmenu=home", $langs->trans("DefaultValues"),1, $conf->global->MAIN_FEATURES_LEVEL);
+				$newmenu->add("/admin/defaultvalues.php?mainmenu=home", $langs->trans("DefaultValues"),1);
 				$newmenu->add("/admin/boxes.php?mainmenu=home", $langs->trans("Boxes"),1);
 				$newmenu->add("/admin/delais.php?mainmenu=home",$langs->trans("MenuWarnings"),1);
 				$newmenu->add("/admin/security_other.php?mainmenu=home", $langs->trans("Security"),1);
@@ -947,26 +947,27 @@ function print_left_eldy_menu($db,$menu_array_before,$menu_array_after,&$tabMenu
 			{
 				$langs->load("accountancy");
 
-				$permtoshowmenu=(! empty($conf->accounting->enabled) || $user->rights->accounting->bind->write || $user->rights->accounting->bind->write || $user->rights->compta->resultat->lire);
+				$permtoshowmenu=(! empty($conf->accounting->enabled) || $user->rights->accounting->bind->write || $user->rights->compta->resultat->lire);
 				$newmenu->add("/accountancy/index.php?leftmenu=accountancy",$langs->trans("MenuAccountancy"), 0, $permtoshowmenu, '', $mainmenu, 'accountancy');
 
 				// Chart of account
 				if ($usemenuhider || empty($leftmenu) || preg_match('/accountancy/',$leftmenu)) $newmenu->add("/accountancy/index.php?leftmenu=accountancy_admin", $langs->trans("Setup"),1,$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin', 1);
-				if ($usemenuhider || empty($leftmenu) || preg_match('/accountancy_admin/',$leftmenu)) $newmenu->add("/accountancy/admin/accountmodel.php?id=31&mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("Pcg_version"),2, $user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_chartmodel', 10);
-				if ($usemenuhider || empty($leftmenu) || preg_match('/accountancy_admin/',$leftmenu)) $newmenu->add("/accountancy/admin/account.php?mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("Chartofaccounts"),2, $user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_chart', 20);
-				if ($usemenuhider || empty($leftmenu) || preg_match('/accountancy_admin/',$leftmenu)) $newmenu->add("/accountancy/admin/categories_list.php?id=32&search_country_id=".$mysoc->country_id."&mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("AccountingCategory"),2, $user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_chart', 22);
+				if ($usemenuhider || empty($leftmenu) || preg_match('/accountancy_admin/',$leftmenu)) $newmenu->add("/accountancy/admin/journals_list.php?id=35&mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("AccountingJournals"),2, $user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_journal', 10);
+				if ($usemenuhider || empty($leftmenu) || preg_match('/accountancy_admin/',$leftmenu)) $newmenu->add("/accountancy/admin/accountmodel.php?id=31&mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("Pcg_version"),2, $user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_chartmodel', 20);
+				if ($usemenuhider || empty($leftmenu) || preg_match('/accountancy_admin/',$leftmenu)) $newmenu->add("/accountancy/admin/account.php?mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("Chartofaccounts"),2, $user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_chart', 30);
+				if ($usemenuhider || empty($leftmenu) || preg_match('/accountancy_admin/',$leftmenu)) $newmenu->add("/accountancy/admin/categories_list.php?id=32&search_country_id=".$mysoc->country_id."&mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("AccountingCategory"),2, $user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_chart', 31);
 				if ($usemenuhider || empty($leftmenu) || preg_match('/accountancy_admin/',$leftmenu)) $newmenu->add("/accountancy/admin/defaultaccounts.php?mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("MenuDefaultAccounts"),2, $user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_default', 40);
 				if (! empty($conf->facture->enabled) || ! empty($conf->fournisseur->enabled)) 
 				{
-				    if ($usemenuhider || empty($leftmenu) || preg_match('/accountancy_admin/',$leftmenu)) $newmenu->add("/admin/dict.php?id=10&from=accountancy&search_country_id=".$mysoc->country_id."&mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("MenuVatAccounts"),2, $user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_default', 30);
+				    if ($usemenuhider || empty($leftmenu) || preg_match('/accountancy_admin/',$leftmenu)) $newmenu->add("/admin/dict.php?id=10&from=accountancy&search_country_id=".$mysoc->country_id."&mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("MenuVatAccounts"),2, $user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_default', 50);
 				}
 				if (! empty($conf->tax->enabled)) 
 				{
-				    if ($usemenuhider || empty($leftmenu) || preg_match('/accountancy_admin/',$leftmenu)) $newmenu->add("/admin/dict.php?id=7&from=accountancy&search_country_id=".$mysoc->country_id."&mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("MenuTaxAccounts"),2, $user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_default', 30);
+				    if ($usemenuhider || empty($leftmenu) || preg_match('/accountancy_admin/',$leftmenu)) $newmenu->add("/admin/dict.php?id=7&from=accountancy&search_country_id=".$mysoc->country_id."&mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("MenuTaxAccounts"),2, $user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_default', 50);
 				}
 				if (! empty($conf->expensereport->enabled)) 
 				{
-				    if (preg_match('/accountancy_admin/',$leftmenu)) $newmenu->add("/admin/dict.php?id=17&from=accountancy&mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("MenuExpenseReportAccounts"),2, $user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_default', 30);
+				    if (preg_match('/accountancy_admin/',$leftmenu)) $newmenu->add("/admin/dict.php?id=17&from=accountancy&mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("MenuExpenseReportAccounts"),2, $user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_default', 50);
 				}
 				/* not required yet, already supported by default account
 				if (! empty($conf->loan->enabled)) 
@@ -977,7 +978,7 @@ function print_left_eldy_menu($db,$menu_array_before,$menu_array_after,&$tabMenu
 				{
 				    if (preg_match('/accountancy_admin/',$leftmenu)) $newmenu->add("/don/admin/donation.php?from=accountancy&mainmenu=accountancy&amp;leftmenu=accountancy_admin", $langs->trans("MenuDonationAccounts"), 2, $user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_donation', 47);
 				}*/
-				if ($usemenuhider || empty($leftmenu) || preg_match('/accountancy_admin/',$leftmenu)) $newmenu->add("/accountancy/admin/productaccount.php?mainmenu=accountancy&amp;leftmenu=accountancy_admin", $langs->trans("MenuProductsAccounts"), 2, $user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_product', 50);
+				if ($usemenuhider || empty($leftmenu) || preg_match('/accountancy_admin/',$leftmenu)) $newmenu->add("/accountancy/admin/productaccount.php?mainmenu=accountancy&amp;leftmenu=accountancy_admin", $langs->trans("MenuProductsAccounts"), 2, $user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_product', 60);
 				
 				// Binding
 				if ($usemenuhider || empty($leftmenu) || preg_match('/accountancy/',$leftmenu)) $newmenu->add("/accountancy/customer/index.php?leftmenu=accountancy_dispatch_customer&amp;mainmenu=accountancy",$langs->trans("CustomersVentilation"),1,$user->rights->accounting->bind->write, '', $mainmenu, 'dispatch_customer');
@@ -1006,8 +1007,8 @@ function print_left_eldy_menu($db,$menu_array_before,$menu_array_after,&$tabMenu
 					// Multi journal
 					$sql = "SELECT rowid, code, label, nature";
 					$sql.= " FROM ".MAIN_DB_PREFIX."accounting_journal";
-					// $sql.= " WHERE entity = ".$conf->entity;
-					$sql.= " ORDER BY code";
+					$sql.= " WHERE entity = ".$conf->entity;
+					$sql.= " ORDER BY nature";
 
 					$resql = $db->query($sql);
 					if ($resql)
@@ -1020,14 +1021,25 @@ function print_left_eldy_menu($db,$menu_array_before,$menu_array_after,&$tabMenu
     						while ($i < $numr)
     						{
     							$objp = $db->fetch_object($resql);
-    
-    							if ($objp->nature == 1) $nature="sells";
-    							if ($objp->nature == 2) $nature="purchases";
-    							if ($objp->nature == 3) $nature="bank";
-    							if ($objp->nature == 4) $nature="various";
+
+    							$nature='';
+    							// Must match array $sourceList defined into journals_list.php 
+    							if ($objp->nature == 2) $nature="sells";
+    							if ($objp->nature == 3) $nature="purchases";
+    							if ($objp->nature == 4) $nature="bank";
+    							if ($objp->nature == 1) $nature="various";
     							if ($objp->nature == 9) $nature="hasnew";
-    
-    							if ($usemenuhider || empty($leftmenu) || preg_match('/accountancy/',$leftmenu)) $newmenu->add('/accountancy/journal/'.$nature.'journal.php?mainmenu=accountancy&leftmenu=accountancy_journal&code_journal='.$objp->code,dol_trunc($objp->label,25),2,$user->rights->accounting->comptarapport->lire);
+    							
+    							// To enable when page exists
+    							if (empty($conf->global->MAIN_FEATURES_LEVEL))
+    							{
+    							    if ($nature == 'various' || $nature == 'hasnew') $nature='';	
+    							}
+    								
+    							if ($nature)
+    							{
+                                    if ($usemenuhider || empty($leftmenu) || preg_match('/accountancy/',$leftmenu)) $newmenu->add('/accountancy/journal/'.$nature.'journal.php?mainmenu=accountancy&leftmenu=accountancy_journal&code_journal='.$objp->code,dol_trunc($objp->label,25),2,$user->rights->accounting->comptarapport->lire);
+    							}
     							$i++;
     						}
 						}
@@ -1252,6 +1264,18 @@ function print_left_eldy_menu($db,$menu_array_before,$menu_array_after,&$tabMenu
                 if ($conf->supplier_order->enabled) $newmenu->add("/product/stock/replenish.php", $langs->trans("Replenishment"), 1, $user->rights->stock->mouvement->creer && $user->rights->fournisseur->lire);
 			}
 
+			// Inventory
+			if ($conf->global->MAIN_FEATURES_LEVEL >= 2)
+			{
+    			if (! empty($conf->stock->enabled))
+    			{
+    				$langs->load("stocks");
+    				$newmenu->add("/product/inventory/list.php?leftmenu=stock", $langs->trans("Inventory"), 0, $user->rights->stock->lire, '', $mainmenu, 'stock');
+    				$newmenu->add("/product/inventory/card.php?action=create", $langs->trans("NewInventory"), 1, $user->rights->stock->creer);
+    				$newmenu->add("/product/inventory/list.php", $langs->trans("List"), 1, $user->rights->stock->lire);
+    			}
+			}
+			
 			// Expeditions
 			if (! empty($conf->expedition->enabled))
 			{
diff --git a/htdocs/core/modules/DolibarrModules.class.php b/htdocs/core/modules/DolibarrModules.class.php
index 48ce35f1532c22cb5a5e2213982cff876db906cd..d0559268c529ef23c33de0f15fed4f850d6ece0b 100644
--- a/htdocs/core/modules/DolibarrModules.class.php
+++ b/htdocs/core/modules/DolibarrModules.class.php
@@ -795,6 +795,37 @@ class DolibarrModules           // Can not be abstract, because we need to insta
     }
     
     
+    /**
+     * Gives the last author of activation
+     *
+     * @return  array       Array array('authorid'=>Id of last activation user, 'lastactivationdate'=>Date of last activation)
+     */
+    function getLastActivationInfo()
+    {
+        global $conf;
+        
+        $sql = "SELECT tms, note FROM ".MAIN_DB_PREFIX."const";
+        $sql.= " WHERE ".$this->db->decrypt('name')." = '".$this->const_name."'";
+        $sql.= " AND entity IN (0, ".$conf->entity.")";
+        
+        dol_syslog(get_class($this)."::getLastActiveDate", LOG_DEBUG);
+        $resql=$this->db->query($sql);
+        if (! $resql) $err++;
+        else
+        {
+            $obj=$this->db->fetch_object($resql);
+            $tmp=array();
+            if ($obj->note)
+            {
+                $tmp=json_decode($obj->note, true);
+            }
+            if ($obj) return array('authorid'=>$tmp['authorid'], 'ip'=>$tmp['ip'], 'lastactivationdate'=>$this->db->jdate($obj->tms));
+        }
+        
+        return array();
+    }
+    
+    
     /**
      * Insert constants for module activation
      *
@@ -802,7 +833,7 @@ class DolibarrModules           // Can not be abstract, because we need to insta
      */
     function _active()
     {
-        global $conf;
+        global $conf, $user;
 
         $err = 0;
 
@@ -817,10 +848,13 @@ class DolibarrModules           // Can not be abstract, because we need to insta
         $resql=$this->db->query($sql);
         if (! $resql) $err++;
 
-        $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (name,value,visible,entity) VALUES";
+        $note=json_encode(array('authorid'=>$user->id, 'ip'=>$_SERVER['REMOTE_ADDR']));
+        
+        $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (name, value, visible, entity, note) VALUES";
         $sql.= " (".$this->db->encrypt($this->const_name,1);
-        $sql.= ",".$this->db->encrypt('1',1);
-        $sql.= ",0,".$entity.")";
+        $sql.= ", ".$this->db->encrypt('1',1);
+        $sql.= ", 0, ".$entity;
+        $sql.= ", '".$this->db->escape($note)."')";
 
         dol_syslog(get_class($this)."::_active", LOG_DEBUG);
         $resql=$this->db->query($sql);
diff --git a/htdocs/core/modules/expedition/doc/pdf_rouget.modules.php b/htdocs/core/modules/expedition/doc/pdf_rouget.modules.php
index d1697b767bd0d2c1b2681763c52ea89e994cad85..3f7a73a650c22b1c39ac0fc5ee7512677379fe72 100644
--- a/htdocs/core/modules/expedition/doc/pdf_rouget.modules.php
+++ b/htdocs/core/modules/expedition/doc/pdf_rouget.modules.php
@@ -49,7 +49,7 @@ class pdf_rouget extends ModelePdfExpedition
 
 		$this->db = $db;
 		$this->name = "rouget";
-		$this->description = $langs->trans("DocumentModelSimple");
+		$this->description = $langs->trans("DocumentModelStandardPDF");
 
 		$this->type = 'pdf';
 		$formatarray=pdf_getFormat();
diff --git a/htdocs/core/modules/fichinter/doc/pdf_soleil.modules.php b/htdocs/core/modules/fichinter/doc/pdf_soleil.modules.php
index 83306b95adbb2363987444dc2ef2026f04c380ce..4d889f84902b6e19b1159cc26cf393cc716d3b2d 100644
--- a/htdocs/core/modules/fichinter/doc/pdf_soleil.modules.php
+++ b/htdocs/core/modules/fichinter/doc/pdf_soleil.modules.php
@@ -65,7 +65,7 @@ class pdf_soleil extends ModelePDFFicheinter
 
 		$this->db = $db;
 		$this->name = 'soleil';
-		$this->description = $langs->trans("DocumentModelStandard");
+		$this->description = $langs->trans("DocumentModelStandardPDF");
 
 		// Dimension page pour format A4
 		$this->type = 'pdf';
diff --git a/htdocs/core/modules/modProduct.class.php b/htdocs/core/modules/modProduct.class.php
index b2349ab77a0fc87b857e8cdf149b0e974f01fbf5..30e64b5de2c0984be33251f0dd967eb70358ff5d 100644
--- a/htdocs/core/modules/modProduct.class.php
+++ b/htdocs/core/modules/modProduct.class.php
@@ -53,7 +53,7 @@ class modProduct extends DolibarrModules
 		$this->module_position = 20;
 		// Module label (no space allowed), used if translation string 'ModuleXXXName' not found (where XXX is value of numeric property 'numero' of module)
 		$this->name = preg_replace('/^mod/i','',get_class($this));
-		$this->description = "Gestion des produits";
+		$this->description = "Product management";
 
 		// Possible values for version are: 'development', 'experimental', 'dolibarr' or version
 		$this->version = 'dolibarr';
@@ -83,7 +83,14 @@ class modProduct extends DolibarrModules
 		$this->const[$r][3] = 'Module to control product codes';
 		$this->const[$r][4] = 0;
 		$r++;
-
+		
+		/*$this->const[$r][0] = "PRODUCT_ADDON_PDF";
+		$this->const[$r][1] = "chaine";
+		$this->const[$r][2] = "standard";
+		$this->const[$r][3] = 'Default module for document generation';
+		$this->const[$r][4] = 0;
+		$r++;*/
+		
 		// Boxes
 		$this->boxes = array(
 			0=>array('file'=>'box_produits.php','enabledbydefaulton'=>'Home'),
diff --git a/htdocs/core/modules/modResource.class.php b/htdocs/core/modules/modResource.class.php
index d3aa3405d0bf2b73cf11c7f689cc0fa48fc5a933..f6674bdcfd741c2fdab9ddef841e02f30da6f902 100644
--- a/htdocs/core/modules/modResource.class.php
+++ b/htdocs/core/modules/modResource.class.php
@@ -201,22 +201,6 @@ class modResource extends DolibarrModules
 		$this->menu = 1;        // This module add menu entries. They are coded into menu manager.
 
 
-		// Add here list of permission defined by
-		// an id, a label, a boolean and two constant strings.
-		// Example:
-		//// Permission id (must not be already used)
-		//$this->rights[$r][0] = 2000;
-		//// Permission label
-		//$this->rights[$r][1] = 'Permision label';
-		//// Permission by default for new user (0/1)
-		//$this->rights[$r][3] = 0;
-		//// In php code, permission will be checked by test
-		//// if ($user->rights->permkey->level1->level2)
-		//$this->rights[$r][4] = 'level1';
-		//// In php code, permission will be checked by test
-		//// if ($user->rights->permkey->level1->level2)
-		//$this->rights[$r][5] = 'level2';
-		//$r++;
 		// Main menu entries
 		$this->menu = array(); // List of menus to add
 		$r = 0;
@@ -267,98 +251,63 @@ class modResource extends DolibarrModules
 			'user'=> 0
 		);
 
-		// Exports
-		$r = 1;
 
-		// Example:
-		//$this->export_code[$r]=$this->rights_class.'_'.$r;
-		//// Translation key (used only if key ExportDataset_xxx_z not found)
-		//$this->export_label[$r]='CustomersInvoicesAndInvoiceLines';
-		//// Condition to show export in list (ie: '$user->id==3').
-		//// Set to 1 to always show when module is enabled.
-		//$this->export_enabled[$r]='1';
-		//$this->export_permission[$r]=array(array("facture","facture","export"));
-		//$this->export_fields_array[$r]=array(
-		//	's.rowid'=>"IdCompany",
-		//	's.nom'=>'CompanyName',
-		//	's.address'=>'Address',
-		//	's.cp'=>'Zip',
-		//	's.ville'=>'Town',
-		//	's.fk_pays'=>'Country',
-		//	's.tel'=>'Phone',
-		//	's.siren'=>'ProfId1',
-		//	's.siret'=>'ProfId2',
-		//	's.ape'=>'ProfId3',
-		//	's.idprof4'=>'ProfId4',
-		//	's.code_compta'=>'CustomerAccountancyCode',
-		//	's.code_compta_fournisseur'=>'SupplierAccountancyCode',
-		//	'f.rowid'=>"InvoiceId",
-		//	'f.facnumber'=>"InvoiceRef",
-		//	'f.datec'=>"InvoiceDateCreation",
-		//	'f.datef'=>"DateInvoice",
-		//	'f.total'=>"TotalHT",
-		//	'f.total_ttc'=>"TotalTTC",
-		//	'f.tva'=>"TotalVAT",
-		//	'f.paye'=>"InvoicePaid",
-		//	'f.fk_statut'=>'InvoiceStatus',
-		//	'f.note'=>"InvoiceNote",
-		//	'fd.rowid'=>'LineId',
-		//	'fd.description'=>"LineDescription",
-		//	'fd.price'=>"LineUnitPrice",
-		//	'fd.tva_tx'=>"LineVATRate",
-		//	'fd.qty'=>"LineQty",
-		//	'fd.total_ht'=>"LineTotalHT",
-		//	'fd.total_tva'=>"LineTotalTVA",
-		//	'fd.total_ttc'=>"LineTotalTTC",
-		//	'fd.date_start'=>"DateStart",
-		//	'fd.date_end'=>"DateEnd",
-		//	'fd.fk_product'=>'ProductId',
-		//	'p.ref'=>'ProductRef'
-		//);
-		//$this->export_entities_array[$r]=array('s.rowid'=>"company",
-		//	's.nom'=>'company',
-		//	's.address'=>'company',
-		//	's.cp'=>'company',
-		//	's.ville'=>'company',
-		//	's.fk_pays'=>'company',
-		//	's.tel'=>'company',
-		//	's.siren'=>'company',
-		//	's.siret'=>'company',
-		//	's.ape'=>'company',
-		//	's.idprof4'=>'company',
-		//	's.code_compta'=>'company',
-		//	's.code_compta_fournisseur'=>'company',
-		//	'f.rowid'=>"invoice",
-		//	'f.facnumber'=>"invoice",
-		//	'f.datec'=>"invoice",
-		//	'f.datef'=>"invoice",
-		//	'f.total'=>"invoice",
-		//	'f.total_ttc'=>"invoice",
-		//	'f.tva'=>"invoice",
-		//	'f.paye'=>"invoice",
-		//	'f.fk_statut'=>'invoice',
-		//	'f.note'=>"invoice",
-		//	'fd.rowid'=>'invoice_line',
-		//	'fd.description'=>"invoice_line",
-		//	'fd.price'=>"invoice_line",
-		//	'fd.total_ht'=>"invoice_line",
-		//	'fd.total_tva'=>"invoice_line",
-		//	'fd.total_ttc'=>"invoice_line",
-		//	'fd.tva_tx'=>"invoice_line",
-		//	'fd.qty'=>"invoice_line",
-		//	'fd.date_start'=>"invoice_line",
-		//	'fd.date_end'=>"invoice_line",
-		//	'fd.fk_product'=>'product',
-		//	'p.ref'=>'product'
-		//);
-		//$this->export_sql_start[$r] = 'SELECT DISTINCT ';
-		//$this->export_sql_end[$r] = ' FROM (' . MAIN_DB_PREFIX . 'facture as f, '
-		//	. MAIN_DB_PREFIX . 'facturedet as fd, ' . MAIN_DB_PREFIX . 'societe as s)';
-		//$this->export_sql_end[$r] .= ' LEFT JOIN ' . MAIN_DB_PREFIX
-		//	. 'product as p on (fd.fk_product = p.rowid)';
-		//$this->export_sql_end[$r] .= ' WHERE f.fk_soc = s.rowid '
-		//	. 'AND f.rowid = fd.fk_facture';
-		//$r++;
+		// Exports
+		//--------
+		$r=0;
+		
+		$r++;
+		$this->export_code[$r]=$this->rights_class.'_'.$r;
+		$this->export_label[$r]="ResourceSingular";	// Translation key (used only if key ExportDataset_xxx_z not found)
+		$this->export_permission[$r]=array(array("resource","read"));
+		$this->export_fields_array[$r]=array('r.rowid'=>'IdResource','r.ref'=>'ResourceFormLabel_ref','c.code'=>'ResourceTypeCode','c.label'=>'ResourceType','r.description'=>'ResourceFormLabel_description','r.note_private'=>"NotePrivate",'r.note_public'=>"NotePublic",'r.asset_number'=>'AssetNumber','r.datec'=>"DateCreation",'r.tms'=>"DateLastModification");
+		$this->export_TypeFields_array[$r]=array('r.rowid'=>'List:resource:ref','r.ref'=>'Text','r.asset_number'=>'Text','r.description'=>'Text','c.code'=>'Text','c.label'=>'List:c_type_resource:label','r.datec'=>'Date','r.tms'=>'Date','r.note_private'=>'Text','r.note_public'=>'Text');
+		$this->export_entities_array[$r]=array('r.rowid'=>'resource','r.ref'=>'resource','c.code'=>'resource','c.label'=>'resource','r.description'=>'resource','r.note_private'=>"resource",'r.resource'=>"resource",'r.asset_number'=>'resource','r.datec'=>"resource",'r.tms'=>"resource");
+		$keyforselect='resource'; $keyforelement='resource'; $keyforaliasextra='extra';
+		include DOL_DOCUMENT_ROOT.'/core/extrafieldsinexport.inc.php';
+		
+		$this->export_dependencies_array[$r]=array('resource'=>array('r.rowid')); // We must keep this until the aggregate_array is used. To add unique key if we ask a field of a child to avoid the DISTINCT to discard them.
+		$this->export_sql_start[$r]='SELECT DISTINCT ';
+		$this->export_sql_end[$r]  =' FROM '.MAIN_DB_PREFIX.'resource as r ';
+		$this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'c_type_resource as c ON c.rowid=r.fk_code_type_resource';
+		$this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'resource_extrafields as extra ON extra.fk_object = c.rowid';
+		$this->export_sql_end[$r] .=' AND r.entity IN ('.getEntity('resource',1).')';
+		
+
+		// Imports
+		//--------
+		$r=0;
+		
+		// Import list of third parties and attributes
+		$r++;
+		$this->import_code[$r]=$this->rights_class.'_'.$r;
+		$this->import_label[$r]='ImportDataset_resource_1';
+		$this->import_icon[$r]='resource';
+		$this->import_entities_array[$r]=array();		// We define here only fields that use another icon that the one defined into import_icon
+		$this->import_tables_array[$r]=array('r'=>MAIN_DB_PREFIX.'resource','extra'=>MAIN_DB_PREFIX.'resource_extrafields');	// List of tables to insert into (insert done in same order)
+		$this->import_fields_array[$r]=array('r.ref'=>"ResourceFormLabel_ref*",'r.fk_code_type_resource'=>'ResourceTypeCode','r.description'=>'ResourceFormLabel_description','r.note_private'=>"NotePrivate",'r.note_public'=>"NotePublic",'r.asset_number'=>'AssetNumber','r.datec'=>'DateCreation');
+		// Add extra fields
+		$sql="SELECT name, label, fieldrequired FROM ".MAIN_DB_PREFIX."extrafields WHERE elementtype = 'resource' AND entity = ".$conf->entity;
+		$resql=$this->db->query($sql);
+		if ($resql)    // This can fail when class is used on old database (during migration for example)
+		{
+			while ($obj=$this->db->fetch_object($resql))
+			{
+				$fieldname='extra.'.$obj->name;
+				$fieldlabel=ucfirst($obj->label);
+				$this->import_fields_array[$r][$fieldname]=$fieldlabel.($obj->fieldrequired?'*':'');
+			}
+		}
+		// End add extra fields
+		$this->import_fieldshidden_array[$r]=array('r.fk_user_author'=>'user->id','extra.fk_object'=>'lastrowid-'.MAIN_DB_PREFIX.'resource');    // aliastable.field => ('user->id' or 'lastrowid-'.tableparent)
+		$this->import_convertvalue_array[$r]=array(
+				'r.fk_code_type_resource'=>array('rule'=>'fetchidfromcodeorlabel','classfile'=>'/core/class/ctyperesource.class.php','class'=>'Ctyperesource','method'=>'fetch','dict'=>'DictionaryResourceType'),
+		);
+		//$this->import_convertvalue_array[$r]=array('s.fk_soc'=>array('rule'=>'lastrowid',table='t');
+		$this->import_regex_array[$r]=array('s.datec'=>'^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]( [0-9][0-9]:[0-9][0-9]:[0-9][0-9])?$');
+		$this->import_examplevalues_array[$r]=array('r.ref'=>"REF1",'r.fk_code_type_resource'=>"Code from dictionnary resource type",'r.datec'=>"2017-01-01 or 2017-01-01 12:30:00");
+		$this->import_updatekeys_array[$r]=array('r.rf'=>'ResourceFormLabel_ref');
+		
 	}
 
 	/**
diff --git a/htdocs/core/modules/modService.class.php b/htdocs/core/modules/modService.class.php
index 7a5db7fcffdfd9eb4b93ba1257246e77eafee7ac..c385ece4b2644dff9be71980dccd4c1333f66055 100644
--- a/htdocs/core/modules/modService.class.php
+++ b/htdocs/core/modules/modService.class.php
@@ -51,7 +51,7 @@ class modService extends DolibarrModules
 		$this->module_position = 30;
 		// Module label (no space allowed), used if translation string 'ModuleXXXName' not found (where XXX is value of numeric property 'numero' of module)
 		$this->name = preg_replace('/^mod/i','',get_class($this));
-		$this->description = "Gestion des services";
+		$this->description = "Service management";
 
 		// Possible values for version are: 'development', 'experimental', 'dolibarr' or version
 		$this->version = 'dolibarr';
diff --git a/htdocs/core/modules/modStock.class.php b/htdocs/core/modules/modStock.class.php
index 8fe4eb52abec4a3b8cad7e54a0dc125867a0ec8d..be6817062b65d3a51aac100ec4aa100fe52be38c 100644
--- a/htdocs/core/modules/modStock.class.php
+++ b/htdocs/core/modules/modStock.class.php
@@ -117,6 +117,43 @@ class modStock extends DolibarrModules
 		$this->rights[4][4] = 'mouvement';
 		$this->rights[4][5] = 'creer';
 
+		if ($conf->global->MAIN_FEATURES_LEVEL >= 2) {
+		
+		$this->rights[5][0] = 1011;
+		$this->rights[5][1] = 'inventoryReadPermission';	// Permission label
+		$this->rights[5][3] = 0; 					// Permission by default for new user (0/1)
+		$this->rights[5][4] = 'advance_inventory';			// In php code, permission will be checked by test if ($user->rights->permkey->level1->level2)
+		$this->rights[5][5] = 'read';			// In php code, permission will be checked by test if ($user->rights->permkey->level1->level2)
+		
+		$this->rights[6][0] = 1012;
+		$this->rights[6][1] = 'inventoryCreatePermission';	// Permission label
+		$this->rights[6][3] = 0; 					// Permission by default for new user (0/1)
+		$this->rights[6][4] = 'advance_inventory';			// In php code, permission will be checked by test if ($user->rights->permkey->level1->level2)
+		$this->rights[6][5] = 'create';			// In php code, permission will be checked by test if ($user->rights->permkey->level1->level2)
+		
+		$this->rights[7][0] = 1013;
+		$this->rights[7][1] = 'inventoryWritePermission';	// Permission label
+		$this->rights[7][3] = 0; 					// Permission by default for new user (0/1)
+		$this->rights[7][4] = 'advance_inventory';			// In php code, permission will be checked by test if ($user->rights->permkey->level1->level2)
+		$this->rights[7][5] = 'write';			// In php code, permission will be checked by test if ($user->rights->permkey->level1->level2)
+		
+		$this->rights[8][0] = 1014;
+		$this->rights[8][1] = 'inventoryValidatePermission';	// Permission label
+		$this->rights[8][3] = 0; 					// Permission by default for new user (0/1)
+		$this->rights[8][4] = 'advance_inventory';			// In php code, permission will be checked by test if ($user->rights->permkey->level1->level2)
+		$this->rights[8][5] = 'validate';			// In php code, permission will be checked by test if ($user->rights->permkey->level1->level2)
+		
+		$this->rights[9][0] = 1015;
+		$this->rights[9][1] = 'inventoryChangePMPPermission';	// Permission label
+		$this->rights[9][3] = 0; 					// Permission by default for new user (0/1)
+		$this->rights[9][4] = 'advance_inventory';			// In php code, permission will be checked by test if ($user->rights->permkey->level1->level2)
+		$this->rights[9][5] = 'changePMP';			// In php code, permission will be checked by test if ($user->rights->permkey->level1->level2)
+		
+		}
+		
+		// Main menu entries
+		$this->menu = array();			// List of menus to add
+		$r=0;
 		
 		// Menus
 		//-------
diff --git a/htdocs/core/modules/product/doc/pdf_standard.modules.php b/htdocs/core/modules/product/doc/pdf_standard.modules.php
index 5dca2b8378e2873f0d0b6dadbb15f09ffb9eb5ab..29df1127242aa160674bd25bb91fd417b6de484f 100644
--- a/htdocs/core/modules/product/doc/pdf_standard.modules.php
+++ b/htdocs/core/modules/product/doc/pdf_standard.modules.php
@@ -92,8 +92,8 @@ class pdf_standard extends ModelePDFProduct
 		$langs->load("companies");
 
 		$this->db = $db;
-		$this->name = "PDF template";
-		$this->description = $langs->trans("DocumentModelPdf");
+		$this->name = "standard";
+		$this->description = $langs->trans("DocumentModelStandardPDF");
 
 		// Dimension page pour format A4
 		$this->type = 'pdf';
@@ -107,15 +107,9 @@ class pdf_standard extends ModelePDFProduct
 		$this->marge_basse =isset($conf->global->MAIN_PDF_MARGIN_BOTTOM)?$conf->global->MAIN_PDF_MARGIN_BOTTOM:10;
 		
 		$this->option_logo = 1;                    // Affiche logo
-		$this->option_tva = 0;                     // Gere option tva PRODUCT_TVAOPTION
-		$this->option_modereg = 0;                 // Affiche mode reglement
-		$this->option_condreg = 0;                 // Affiche conditions reglement
 		$this->option_codeproduitservice = 0;      // Affiche code produit-service
 		$this->option_multilang = 1;               // Dispo en plusieurs langues
-		$this->option_escompte = 0;                // Affiche si il y a eu escompte
-		$this->option_credit_note = 0;             // Support credit notes
-		$this->option_freetext = 1;				   // Support add of a personalised text
-		$this->option_draft_watermark = 1;		   // Support add of a watermark on drafts
+		$this->option_freetext = 0;				   // Support add of a personalised text
 
 		// Recupere emetteur
 		$this->emetteur=$mysoc;
@@ -262,7 +256,7 @@ class pdf_standard extends ModelePDFProduct
 				}
 				if ($object->weight)
 				{
-				    $pdf->writeHTMLCell(190, 3, $this->marge_gauche, $nexY, $langs->trans("Length").' x '.$langs->trans("Width").' x '.$langs->trans("Height").': '.$object->length.'x'.$object->width.'x'.$object->height, 0, 1);
+				    $pdf->writeHTMLCell(190, 3, $this->marge_gauche, $nexY, $langs->trans("Length").' x '.$langs->trans("Width").' x '.$langs->trans("Height").': '.($object->length != ''?$object->length:'?').' x '.($object->width != ''?$object->width:'?').' x '.($object->height != ''?$object->height:'?'), 0, 1);
 				    $nexY = $pdf->GetY();
 				}
 				if ($object->surface)
diff --git a/htdocs/core/modules/supplier_payment/pdf/index.html b/htdocs/core/modules/supplier_payment/doc/index.html
similarity index 100%
rename from htdocs/core/modules/supplier_payment/pdf/index.html
rename to htdocs/core/modules/supplier_payment/doc/index.html
diff --git a/htdocs/core/modules/supplier_payment/pdf/pdf_cow.modules.php b/htdocs/core/modules/supplier_payment/doc/pdf_standard.modules.php
similarity index 98%
rename from htdocs/core/modules/supplier_payment/pdf/pdf_cow.modules.php
rename to htdocs/core/modules/supplier_payment/doc/pdf_standard.modules.php
index edb37ddcdde848d44bef19cdfd5690f2c8778ef8..2b645e4a263d3a7aca8edb86a9b3f4bdc87bac5e 100644
--- a/htdocs/core/modules/supplier_payment/pdf/pdf_cow.modules.php
+++ b/htdocs/core/modules/supplier_payment/doc/pdf_standard.modules.php
@@ -36,7 +36,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functionsnumtoword.lib.php';
 /**
  *	Class to generate the supplier invoices with the canelle model
  */
-class pdf_cow extends ModelePDFSuppliersPayments
+class pdf_standard extends ModelePDFSuppliersPayments
 {
     var $db;
     var $name;
@@ -70,8 +70,8 @@ class pdf_cow extends ModelePDFSuppliersPayments
 		$langs->load("bills");
 
 		$this->db = $db;
-		$this->name = "cow";
-		$this->description = $langs->trans('SuppliersPaymentModel');
+		$this->name = "standard";
+		$this->description = $langs->trans('DocumentModelStandardPDF');
 
 		// Dimension page pour format A4
 		$this->type = 'pdf';
@@ -85,10 +85,6 @@ class pdf_cow extends ModelePDFSuppliersPayments
 		$this->marge_basse =isset($conf->global->MAIN_PDF_MARGIN_BOTTOM)?$conf->global->MAIN_PDF_MARGIN_BOTTOM:10;
 
 		$this->option_logo = 1;                    // Affiche logo
-		$this->option_tva = 1;                     // Gere option tva FACTURE_TVAOPTION
-		$this->option_modereg = 1;                 // Affiche mode reglement
-		$this->option_condreg = 1;                 // Affiche conditions reglement
-		$this->option_codeproduitservice = 1;      // Affiche code produit-service
 		$this->option_multilang = 1;               // Dispo en plusieurs langues
 
 		$this->franchise=!$mysoc->tva_assuj;
diff --git a/htdocs/core/modules/supplier_proposal/doc/pdf_aurore.modules.php b/htdocs/core/modules/supplier_proposal/doc/pdf_aurore.modules.php
index 3b2812c7b90de9130c88b0ad65e3eeee0ce801a9..6efe3ead81c9451bd431084908c3856be531b35c 100644
--- a/htdocs/core/modules/supplier_proposal/doc/pdf_aurore.modules.php
+++ b/htdocs/core/modules/supplier_proposal/doc/pdf_aurore.modules.php
@@ -635,16 +635,6 @@ class pdf_aurore extends ModelePDFSupplierProposal
 
 		$pdf->SetFont('','', $default_font_size - 1);
 
-		// If France, show VAT mention if not applicable
-		if ($this->emetteur->country_code == 'FR' && $this->franchise == 1)
-		{
-			$pdf->SetFont('','B', $default_font_size - 2);
-			$pdf->SetXY($this->marge_gauche, $posy);
-			$pdf->MultiCell(100, 3, $outputlangs->transnoentities("VATIsNotUsedForInvoice"), 0, 'L', 0);
-
-			$posy=$pdf->GetY()+4;
-		}
-
 		$posxval=52;
 
         // Show shipping date
@@ -723,7 +713,7 @@ class pdf_aurore extends ModelePDFSupplierProposal
 			$posy=$pdf->GetY()+3;
 		}
 
-		if (empty($conf->global->SUPPLIER_PROPOSAL_PDF_HIDE_PAYMENTTERMCOND))
+		if (! empty($conf->global->SUPPLIER_PROPOSAL_PDF_SHOW_PAYMENTTERMCOND))
 		{
 			// Show payment mode
 			if ($object->mode_reglement_code
@@ -1037,7 +1027,7 @@ class pdf_aurore extends ModelePDFSupplierProposal
 		$resteapayer = $object->total_ttc - $deja_regle;
 		if (! empty($object->paye)) $resteapayer=0;
 		*/
-
+        
 		if ($deja_regle > 0)
 		{
 			$index++;
diff --git a/htdocs/core/modules/syslog/mod_syslog_chromephp.php b/htdocs/core/modules/syslog/mod_syslog_chromephp.php
index 42a660ab0ae1c66a259c14fb5d0133792665d620..a9b9ccd5836decf952ea2c5019d513ad44a6d7ea 100644
--- a/htdocs/core/modules/syslog/mod_syslog_chromephp.php
+++ b/htdocs/core/modules/syslog/mod_syslog_chromephp.php
@@ -48,7 +48,7 @@ class mod_syslog_chromephp extends LogHandler implements LogHandlerInterface
 	{
 		global $langs;
 
-		return $this->isActive()?'':$langs->trans('ClassNotFoundIntoPathWarning','ChromePhp.class.php');
+		return ($this->isActive() == 1)?'':$langs->trans('ClassNotFoundIntoPathWarning','ChromePhp.class.php');
 	}
 	
 	/**
@@ -73,7 +73,7 @@ class mod_syslog_chromephp extends LogHandler implements LogHandlerInterface
 
 		    if ($res)
 		    {
-		        return 1;
+        		return empty($conf->global->SYSLOG_DISABLE_LOGHANDLER_CHROMEPHP)?1:0;    // Set SYSLOG_DISABLE_LOGHANDLER_CHROMEPHP to 1 to disable this loghandler
 		    }
 		    else
 		    {
diff --git a/htdocs/core/modules/syslog/mod_syslog_file.php b/htdocs/core/modules/syslog/mod_syslog_file.php
index 195cab19f7f04692c799f0932c39eb52a991b1e8..68493fd4eb4e994df3dab9e9c4bf7bc4adf00b9b 100644
--- a/htdocs/core/modules/syslog/mod_syslog_file.php
+++ b/htdocs/core/modules/syslog/mod_syslog_file.php
@@ -51,7 +51,8 @@ class mod_syslog_file extends LogHandler implements LogHandlerInterface
 	 */
 	public function isActive()
 	{
-		return 1;
+	    global $conf;
+		return empty($conf->global->SYSLOG_DISABLE_LOGHANDLER_FILE)?1:0;    // Set SYSLOG_DISABLE_LOGHANDLER_FILE to 1 to disable this loghandler
 	}
 
 	/**
diff --git a/htdocs/core/modules/syslog/mod_syslog_firephp.php b/htdocs/core/modules/syslog/mod_syslog_firephp.php
index fa6111c80a3d532cf9c62b1c58f0a28436ad6d35..69bc98230af78d1e90bc16e25bd9f98cb21ef0fc 100644
--- a/htdocs/core/modules/syslog/mod_syslog_firephp.php
+++ b/htdocs/core/modules/syslog/mod_syslog_firephp.php
@@ -56,7 +56,7 @@ class mod_syslog_firephp extends LogHandler implements LogHandlerInterface
 	{
 		global $langs;
 
-		return $this->isActive()?'':$langs->trans('ClassNotFoundIntoPathWarning', self::$firephp_class_path);
+		return ($this->isActive() == 1)?'':$langs->trans('ClassNotFoundIntoPathWarning', self::$firephp_class_path);
 	}
 
 	/**
@@ -76,7 +76,7 @@ class mod_syslog_firephp extends LogHandler implements LogHandlerInterface
 			$res = @include_once self::$firephp_class_path;
 			restore_include_path();
 			if ($res) {
-				return 1;
+        		return empty($conf->global->SYSLOG_DISABLE_LOGHANDLER_FIREPHP)?1:0;    // Set SYSLOG_DISABLE_LOGHANDLER_FIREPHP to 1 to disable this loghandler
 			} else {
 				return 0;
 			}
diff --git a/htdocs/core/modules/syslog/mod_syslog_syslog.php b/htdocs/core/modules/syslog/mod_syslog_syslog.php
index c2885f1c89ad33904d318e3193062129f669b087..e0283ac9a9f4cc8ec84f9c025dc8ccf594bf6516 100644
--- a/htdocs/core/modules/syslog/mod_syslog_syslog.php
+++ b/htdocs/core/modules/syslog/mod_syslog_syslog.php
@@ -48,10 +48,12 @@ class mod_syslog_syslog extends LogHandler implements LogHandlerInterface
 	 */
 	public function isActive()
 	{
+	    global $conf;
+	    
 		// This function does not exists on some ISP (Ex: Free in France)
 		if (!function_exists('openlog')) return 0;
 
-		return 1;
+		return empty($conf->global->SYSLOG_DISABLE_LOGHANDLER_SYSLOG)?1:0;    // Set SYSLOG_DISABLE_LOGHANDLER_SYSLOG to 1 to disable this loghandler
 	}
 
 	/**
@@ -111,11 +113,11 @@ class mod_syslog_syslog extends LogHandler implements LogHandlerInterface
 
 		if (! empty($conf->global->MAIN_SYSLOG_DISABLE_SYSLOG)) return;	// Global option to disable output of this handler
 
-		if (! empty($conf->global->SYSLOG_FACILITY))
+		if (! empty($conf->global->SYSLOG_FACILITY))  // Example LOG_USER
 		{
 			$facility = constant($conf->global->SYSLOG_FACILITY);
 		}
-		else $facility = LOG_USER;
+		else $facility = constant('LOG_USER');
 
 		// (int) is required to avoid error parameter 3 expected to be long
 		openlog('dolibarr', LOG_PID | LOG_PERROR, (int) $facility);
diff --git a/htdocs/core/tpl/admin_extrafields_view.tpl.php b/htdocs/core/tpl/admin_extrafields_view.tpl.php
index c14927ec0483fdf4a5725c5dd5518269a79a0653..3242a388a3d8fa3e5f13f12181603b93b676b60e 100644
--- a/htdocs/core/tpl/admin_extrafields_view.tpl.php
+++ b/htdocs/core/tpl/admin_extrafields_view.tpl.php
@@ -1,5 +1,5 @@
 <?php
-/* Copyright (C) 2010-2016	Laurent Destailleur	<eldy@users.sourceforge.net>
+/* Copyright (C) 2010-2017	Laurent Destailleur	<eldy@users.sourceforge.net>
  * Copyright (C) 2012		Regis Houssin		<regis.houssin@capnetworks.com>
  *
  * This program is free software; you can redistribute it and/or modify
@@ -49,23 +49,36 @@ if (! empty($conf->global->MAIN_CAN_HIDE_EXTRAFIELDS)) print '<td align="center"
 print '<td width="80">&nbsp;</td>';
 print "</tr>\n";
 
-$var=True;
-foreach($extrafields->attribute_type as $key => $value)
+if (count($extrafields->attribute_type))
 {
+    foreach($extrafields->attribute_type as $key => $value)
+    {
+        
+        print '<tr class="oddeven">';
+        print "<td>".$extrafields->attribute_pos[$key]."</td>\n";
+        print "<td>".$extrafields->attribute_label[$key]."</td>\n";
+        print "<td>".$key."</td>\n";
+        print "<td>".$type2label[$extrafields->attribute_type[$key]]."</td>\n";
+        print '<td align="right">'.$extrafields->attribute_size[$key]."</td>\n";
+        print '<td align="center">'.yn($extrafields->attribute_unique[$key])."</td>\n";
+        print '<td align="center">'.yn($extrafields->attribute_required[$key])."</td>\n";
+        print '<td align="center">'.yn($extrafields->attribute_alwayseditable[$key])."</td>\n";
+    	if (! empty($conf->global->MAIN_CAN_HIDE_EXTRAFIELDS)) print '<td align="center">'.yn($extrafields->attribute_hidden[$key])."</td>\n";	// Add hidden option on not working feature. Why hide if user can't see it.
+        print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=edit&attrname='.$key.'">'.img_edit().'</a>';
+        print "&nbsp; <a href=\"".$_SERVER["PHP_SELF"]."?action=delete&attrname=$key\">".img_delete()."</a></td>\n";
+        print "</tr>";
+    }
+}
+else
+{
+    $colspan=9;
+    if (! empty($conf->global->MAIN_CAN_HIDE_EXTRAFIELDS)) $colspan++;
     
     print '<tr class="oddeven">';
-    print "<td>".$extrafields->attribute_pos[$key]."</td>\n";
-    print "<td>".$extrafields->attribute_label[$key]."</td>\n";
-    print "<td>".$key."</td>\n";
-    print "<td>".$type2label[$extrafields->attribute_type[$key]]."</td>\n";
-    print '<td align="right">'.$extrafields->attribute_size[$key]."</td>\n";
-    print '<td align="center">'.yn($extrafields->attribute_unique[$key])."</td>\n";
-    print '<td align="center">'.yn($extrafields->attribute_required[$key])."</td>\n";
-    print '<td align="center">'.yn($extrafields->attribute_alwayseditable[$key])."</td>\n";
-	if (! empty($conf->global->MAIN_CAN_HIDE_EXTRAFIELDS)) print '<td align="center">'.yn($extrafields->attribute_hidden[$key])."</td>\n";	// Add hidden option on not working feature. Why hide if user can't see it.
-    print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=edit&attrname='.$key.'">'.img_edit().'</a>';
-    print "&nbsp; <a href=\"".$_SERVER["PHP_SELF"]."?action=delete&attrname=$key\">".img_delete()."</a></td>\n";
-    print "</tr>";
+    print '<td class="opacitymedium" colspan="'.$colspan.'">';
+    print $langs->trans("None");
+    print '</td>';
+    print '</tr>';
 }
 
 print "</table>";
diff --git a/htdocs/core/tpl/login.tpl.php b/htdocs/core/tpl/login.tpl.php
index 1245041d98aa1dea746f19c1969ed68064c71f85..81e3936d300fb06924ee055dd2fc2355565da31a 100644
--- a/htdocs/core/tpl/login.tpl.php
+++ b/htdocs/core/tpl/login.tpl.php
@@ -258,7 +258,7 @@ if (!empty($conf->global->MAIN_EASTER_EGG_COMMITSTRIP)) {
 <?php if ($main_home)
 {
 ?>
-	<div class="center login_main_home" style="max-width: 80%">
+	<div class="center login_main_home" style="max-width: 70%">
 	<?php echo $main_home; ?>
 	</div><br>
 <?php
diff --git a/htdocs/core/tpl/passwordforgotten.tpl.php b/htdocs/core/tpl/passwordforgotten.tpl.php
index bdc38b0887380733f53612bc1afac5a582eb1538..ad29cbfcd3d40e8a37cfab57dd6d1a531049d95d 100644
--- a/htdocs/core/tpl/passwordforgotten.tpl.php
+++ b/htdocs/core/tpl/passwordforgotten.tpl.php
@@ -151,7 +151,7 @@ if (! empty($hookmanager->resArray['options'])) {
 </form>
 
 
-<div class="center login_main_home" style="max-width: 80%">
+<div class="center login_main_home" style="max-width: 70%">
 <?php if ($mode == 'dolibarr' || ! $disabled) { ?>
 	<font style="font-size: 12px;">
 	<?php echo $langs->trans('SendNewPasswordDesc'); ?>
diff --git a/htdocs/core/triggers/interface_50_modAgenda_ActionsAuto.class.php b/htdocs/core/triggers/interface_50_modAgenda_ActionsAuto.class.php
index 84517e36c0836c52744ab95632fb40d70b956b52..9da1ada59adc54c96bdbc97d0e0a761fd70b03d7 100644
--- a/htdocs/core/triggers/interface_50_modAgenda_ActionsAuto.class.php
+++ b/htdocs/core/triggers/interface_50_modAgenda_ActionsAuto.class.php
@@ -48,7 +48,7 @@ class InterfaceActionsAuto extends DolibarrTriggers
 	 *      $object->actionmsg (note, long text)
 	 *      $object->actionmsg2 (label, short text)
 	 *      $object->sendtoid (id of contact or array of ids)
-	 *      $object->socid
+	 *      $object->socid (id of thirdparty)
 	 *      $object->fk_project
 	 *      $object->fk_element
 	 *      $object->elementtype
@@ -87,7 +87,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
             if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("NewCompanyToDolibarr",$object->name);
             $object->actionmsg=$langs->transnoentities("NewCompanyToDolibarr",$object->name);
             if (! empty($object->prefix)) $object->actionmsg.=" (".$object->prefix.")";
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
 			$object->sendtoid=0;
 			$object->socid=$object->id;
@@ -100,7 +99,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
 
             if (empty($object->actiontypecode)) $object->actiontypecode='AC_OTH_AUTO';
             if (empty($object->actionmsg2)) dol_syslog('Trigger called with property actionmsg2 on object not defined', LOG_ERR);
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
             // Parameters $object->sendtoid defined by caller
             //$object->sendtoid=0;
@@ -114,7 +112,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
 			$object->actiontypecode='AC_OTH_AUTO';
             if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("ContractValidatedInDolibarr",($object->newref?$object->newref:$object->ref));
             $object->actionmsg=$langs->transnoentities("ContractValidatedInDolibarr",($object->newref?$object->newref:$object->ref));
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
             $object->sendtoid=0;
 		}
@@ -127,7 +124,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
 			$object->actiontypecode='AC_OTH_AUTO';
             if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("PropalValidatedInDolibarr",($object->newref?$object->newref:$object->ref));
             $object->actionmsg=$langs->transnoentities("PropalValidatedInDolibarr",($object->newref?$object->newref:$object->ref));
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
 			$object->sendtoid=0;
 		}
@@ -142,7 +138,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
             if (empty($object->actionmsg))
             {
                 $object->actionmsg=$langs->transnoentities("ProposalSentByEMail",$object->ref);
-                $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
             }
 
             // Parameters $object->sendtoid defined by caller
@@ -157,7 +152,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
 			$object->actiontypecode='AC_OTH_AUTO';
             if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("PropalClosedSignedInDolibarr",$object->ref);
             $object->actionmsg=$langs->transnoentities("PropalClosedSignedInDolibarr",$object->ref);
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
 			$object->sendtoid=0;
 		}
@@ -170,7 +164,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
 			$object->actiontypecode='AC_OTH_AUTO';
             if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("PropalClassifiedBilledInDolibarr",$object->ref);
             $object->actionmsg=$langs->transnoentities("PropalClassifiedBilledInDolibarr",$object->ref);
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
 			$object->sendtoid=0;
 		}
@@ -183,7 +176,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
 			$object->actiontypecode='AC_OTH_AUTO';
             if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("PropalClosedRefusedInDolibarr",$object->ref);
             $object->actionmsg=$langs->transnoentities("PropalClosedRefusedInDolibarr",$object->ref);
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
 			$object->sendtoid=0;
 		}
@@ -195,7 +187,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
 			$object->actiontypecode='AC_OTH_AUTO';
             if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("OrderValidatedInDolibarr",($object->newref?$object->newref:$object->ref));
             $object->actionmsg=$langs->transnoentities("OrderValidatedInDolibarr",($object->newref?$object->newref:$object->ref));
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
 			$object->sendtoid=0;
 		}
@@ -208,7 +199,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
 			$object->actiontypecode='AC_OTH_AUTO';
             if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("OrderDeliveredInDolibarr",$object->ref);
             $object->actionmsg=$langs->transnoentities("OrderDeliveredInDolibarr",$object->ref);
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
 			$object->sendtoid=0;
 		}
@@ -221,7 +211,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
 			$object->actiontypecode='AC_OTH_AUTO';
             if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("OrderBilledInDolibarr",$object->ref);
             $object->actionmsg=$langs->transnoentities("OrderBilledInDolibarr",$object->ref);
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
 			$object->sendtoid=0;
 		}
@@ -234,7 +223,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
 			$object->actiontypecode='AC_OTH_AUTO';
             if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("OrderCanceledInDolibarr",$object->ref);
             $object->actionmsg=$langs->transnoentities("OrderCanceledInDolibarr",$object->ref);
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
 			$object->sendtoid=0;
 		}
@@ -249,7 +237,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
             if (empty($object->actionmsg))
             {
                 $object->actionmsg=$langs->transnoentities("OrderSentByEMail",$object->ref);
-                $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
             }
 
             // Parameters $object->sendtoid defined by caller
@@ -264,7 +251,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
 			$object->actiontypecode='AC_OTH_AUTO';
             if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InvoiceValidatedInDolibarr",($object->newref?$object->newref:$object->ref));
             $object->actionmsg=$langs->transnoentities("InvoiceValidatedInDolibarr",($object->newref?$object->newref:$object->ref));
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
 			$object->sendtoid=0;
 		}
@@ -277,7 +263,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
 			$object->actiontypecode='AC_OTH_AUTO';
             if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InvoiceBackToDraftInDolibarr",$object->ref);
             $object->actionmsg=$langs->transnoentities("InvoiceBackToDraftInDolibarr",$object->ref);
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
 			$object->sendtoid=0;
 		}
@@ -292,7 +277,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
             if (empty($object->actionmsg))
             {
                 $object->actionmsg=$langs->transnoentities("InvoiceSentByEMail",$object->ref);
-                $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
             }
 
             // Parameters $object->sendtoid defined by caller
@@ -308,7 +292,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
 			$object->actiontypecode='AC_OTH_AUTO';
             $object->actionmsg2=$langs->transnoentities("InvoicePaidInDolibarr",$object->ref);
             $object->actionmsg=$langs->transnoentities("InvoicePaidInDolibarr",$object->ref);
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
             $object->sendtoid=0;
 		}
@@ -321,7 +304,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
 			$object->actiontypecode='AC_OTH_AUTO';
             if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InvoiceCanceledInDolibarr",$object->ref);
             $object->actionmsg=$langs->transnoentities("InvoiceCanceledInDolibarr",$object->ref);
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
             $object->sendtoid=0;
 		}
@@ -334,7 +316,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
 			$object->actiontypecode='AC_OTH_AUTO';
             if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InterventionCreatedInDolibarr",$object->ref);
             $object->actionmsg=$langs->transnoentities("InterventionCreatedInDolibarr",$object->ref);
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
             $object->sendtoid=0;
 			$object->fk_element=0;
@@ -349,7 +330,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
 			$object->actiontypecode='AC_OTH_AUTO';
             if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InterventionValidatedInDolibarr",($object->newref?$object->newref:$object->ref));
             $object->actionmsg=$langs->transnoentities("InterventionValidatedInDolibarr",($object->newref?$object->newref:$object->ref));
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
             $object->sendtoid=0;
 			$object->fk_element=0;
@@ -364,7 +344,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
 			$object->actiontypecode='AC_OTH_AUTO';
             if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InterventionModifiedInDolibarr",$object->ref);
             $object->actionmsg=$langs->transnoentities("InterventionModifiedInDolibarr",$object->ref);
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
             $object->sendtoid=0;
 			$object->fk_element=0;
@@ -379,7 +358,7 @@ class InterfaceActionsAuto extends DolibarrTriggers
             $object->actiontypecode='AC_OTH_AUTO';
             if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InterventionSentByEMail",$object->ref);
             $object->actionmsg=$langs->transnoentities("InterventionSentByEMail",$object->ref);
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
+
             // Parameters $object->sendtoid defined by caller
             //$object->sendtoid=0;
         }
@@ -392,7 +371,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
             $object->actiontypecode='AC_OTH_AUTO';
            	if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InterventionClassifiedBilledInDolibarr",$object->ref);
            	$object->actionmsg=$langs->transnoentities("InterventionClassifiedBilledInDolibarr",$object->ref);
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
             $object->sendtoid=0;
         }
@@ -405,7 +383,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
             $object->actiontypecode='AC_OTH_AUTO';
            	if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InterventionClassifiedUnbilledInDolibarr",$object->ref);
            	$object->actionmsg=$langs->transnoentities("InterventionClassifiedUnbilledInDolibarr",$object->ref);
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
             $object->sendtoid=0;
         }
@@ -418,7 +395,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
 			$object->actiontypecode='AC_OTH_AUTO';
             if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InterventionDeletedInDolibarr",$object->ref);
             $object->actionmsg=$langs->transnoentities("InterventionDeletedInDolibarr",$object->ref);
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
             $object->sendtoid=0;
 			$object->fk_element=0;
@@ -435,7 +411,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
         	if (empty($object->actionmsg))
         	{
         		$object->actionmsg=$langs->transnoentities("ShippingValidated",($object->newref?$object->newref:$object->ref));
-        		$object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
         	}
 
         	// Parameters $object->sendtoid defined by caller
@@ -452,7 +427,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
             if (empty($object->actionmsg))
             {
                 $object->actionmsg=$langs->transnoentities("ShippingSentByEMail",$object->ref);
-                $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
             }
 
             // Parameters $object->sendtoid defined by caller
@@ -467,7 +441,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
 			$object->actiontypecode='AC_OTH_AUTO';
             if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("OrderCreatedInDolibarr",($object->newref?$object->newref:$object->ref));
             $object->actionmsg=$langs->transnoentities("OrderCreatedInDolibarr",($object->newref?$object->newref:$object->ref));
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
             $object->sendtoid=0;
 		}
@@ -480,7 +453,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
 			$object->actiontypecode='AC_OTH_AUTO';
             if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("OrderValidatedInDolibarr",($object->newref?$object->newref:$object->ref));
             $object->actionmsg=$langs->transnoentities("OrderValidatedInDolibarr",($object->newref?$object->newref:$object->ref));
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
             $object->sendtoid=0;
 		}
@@ -493,7 +465,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
 			$object->actiontypecode='AC_OTH_AUTO';
 			if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("OrderApprovedInDolibarr",$object->ref);
 			$object->actionmsg=$langs->transnoentities("OrderApprovedInDolibarr",$object->ref);
-			$object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
 			$object->sendtoid=0;
 		}
@@ -506,7 +477,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
 			$object->actiontypecode='AC_OTH_AUTO';
 			if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("OrderRefusedInDolibarr",$object->ref);
 			$object->actionmsg=$langs->transnoentities("OrderRefusedInDolibarr",$object->ref);
-			$object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
 			$object->sendtoid=0;
 		}
@@ -519,7 +489,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
 			$object->actiontypecode='AC_OTH_AUTO';
             if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("SupplierOrderSubmitedInDolibarr",($object->newref?$object->newref:$object->ref));
             $object->actionmsg=$langs->transnoentities("SupplierOrderSubmitedInDolibarr",($object->newref?$object->newref:$object->ref));
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
             $object->sendtoid=0;
 		}
@@ -532,7 +501,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
 			$object->actiontypecode='AC_OTH_AUTO';
             if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("SupplierOrderReceivedInDolibarr",($object->newref?$object->newref:$object->ref));
             $object->actionmsg=$langs->transnoentities("SupplierOrderReceivedInDolibarr",($object->newref?$object->newref:$object->ref));
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
             $object->sendtoid=0;
 		}
@@ -548,7 +516,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
             if (empty($object->actionmsg))
             {
                 $object->actionmsg=$langs->transnoentities("SupplierOrderSentByEMail",$object->ref);
-                $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
             }
 
             // Parameters $object->sendtoid defined by caller
@@ -566,7 +533,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
             if (empty($object->actionmsg))
             {
                 $object->actionmsg=$langs->transnoentities("SupplierOrderClassifiedBilled",$object->ref);
-                $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
             }
 
             $object->sendtoid=0;
@@ -580,7 +546,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
 			$object->actiontypecode='AC_OTH_AUTO';
             if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InvoiceValidatedInDolibarr",($object->newref?$object->newref:$object->ref));
             $object->actionmsg=$langs->transnoentities("InvoiceValidatedInDolibarr",($object->newref?$object->newref:$object->ref));
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
             $object->sendtoid=0;
 		}
@@ -593,7 +558,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
 			$object->actiontypecode='AC_OTH_AUTO';
             if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InvoiceBackToDraftInDolibarr",$object->ref);
             $object->actionmsg=$langs->transnoentities("InvoiceBackToDraftInDolibarr",$object->ref);
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
             $object->sendtoid=0;
 		}
@@ -609,7 +573,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
             if (empty($object->actionmsg))
             {
                 $object->actionmsg=$langs->transnoentities("SupplierInvoiceSentByEMail",$object->ref);
-                $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
             }
 
             // Parameters $object->sendtoid defined by caller
@@ -624,7 +587,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
 			$object->actiontypecode='AC_OTH_AUTO';
             if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InvoicePaidInDolibarr",$object->ref);
             $object->actionmsg=$langs->transnoentities("InvoicePaidInDolibarr",$object->ref);
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
 			$object->sendtoid=0;
 		}
@@ -637,7 +599,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
 			$object->actiontypecode='AC_OTH_AUTO';
             if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InvoiceCanceledInDolibarr",$object->ref);
             $object->actionmsg=$langs->transnoentities("InvoiceCanceledInDolibarr",$object->ref);
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
 			$object->sendtoid=0;
 		}
@@ -654,7 +615,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
             $object->actionmsg=$langs->transnoentities("MemberValidatedInDolibarr",($object->newref?$object->newref:$object->ref));
             $object->actionmsg.="\n".$langs->transnoentities("Member").': '.$object->getFullName($langs);
             $object->actionmsg.="\n".$langs->transnoentities("Type").': '.$object->type;
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
 			$object->sendtoid=0;
         }
@@ -669,7 +629,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
             $object->actionmsg=$langs->transnoentities("MemberModifiedInDolibarr",$object->ref);
             $object->actionmsg.="\n".$langs->transnoentities("Member").': '.$object->getFullName($langs);
             $object->actionmsg.="\n".$langs->transnoentities("Type").': '.$object->type;
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
             $object->sendtoid=0;
 		}
@@ -686,7 +645,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
             $object->actionmsg.="\n".$langs->transnoentities("Type").': '.$object->type;
             $object->actionmsg.="\n".$langs->transnoentities("Amount").': '.$object->last_subscription_amount;
             $object->actionmsg.="\n".$langs->transnoentities("Period").': '.dol_print_date($object->last_subscription_date_start,'day').' - '.dol_print_date($object->last_subscription_date_end,'day');
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
 			$object->sendtoid=0;
         }
@@ -701,7 +659,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
             $object->actionmsg=$langs->transnoentities("MemberResiliatedInDolibarr",$object->ref);
             $object->actionmsg.="\n".$langs->transnoentities("Member").': '.$object->getFullName($langs);
             $object->actionmsg.="\n".$langs->transnoentities("Type").': '.$object->type;
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
 			$object->sendtoid=0;
         }
@@ -716,7 +673,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
             $object->actionmsg=$langs->transnoentities("MemberDeletedInDolibarr",$object->ref);
             $object->actionmsg.="\n".$langs->transnoentities("Member").': '.$object->getFullName($langs);
             $object->actionmsg.="\n".$langs->transnoentities("Type").': '.$object->type;
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
 			$object->sendtoid=0;
         }
@@ -732,7 +688,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
         	if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("ProjectCreatedInDolibarr",$object->ref);
         	$object->actionmsg=$langs->transnoentities("ProjectCreatedInDolibarr",$object->ref);
         	$object->actionmsg.="\n".$langs->transnoentities("Project").': '.$object->ref;
-        	$object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
         	$object->sendtoid=0;
         }
@@ -746,7 +701,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
             if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("ProjectValidatedInDolibarr",$object->ref);
             $object->actionmsg=$langs->transnoentities("ProjectValidatedInDolibarr",$object->ref);
             $object->actionmsg.="\n".$langs->transnoentities("Project").': '.$object->ref;
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
         
             $object->sendtoid=0;
         }
@@ -759,7 +713,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
             if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("ProjectModifiedInDolibarr",$object->ref);
             $object->actionmsg=$langs->transnoentities("ProjectModifieddInDolibarr",$object->ref);
             $object->actionmsg.="\n".$langs->transnoentities("Task").': '.$object->ref;
-            $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
         
             $object->sendtoid=0;
         }
@@ -775,7 +728,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
 			if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("TaskCreatedInDolibarr",$object->ref);
 			$object->actionmsg=$langs->transnoentities("TaskCreatedInDolibarr",$object->ref);
 			$object->actionmsg.="\n".$langs->transnoentities("Task").': '.$object->ref;
-			$object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
 			$object->sendtoid=0;
 		}
@@ -789,7 +741,6 @@ class InterfaceActionsAuto extends DolibarrTriggers
 			if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("TaskModifiedInDolibarr",$object->ref);
 			$object->actionmsg=$langs->transnoentities("TaskModifieddInDolibarr",$object->ref);
 			$object->actionmsg.="\n".$langs->transnoentities("Task").': '.$object->ref;
-			$object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
 			$object->sendtoid=0;
 		}
@@ -803,18 +754,24 @@ class InterfaceActionsAuto extends DolibarrTriggers
 			if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("TaskDeletedInDolibarr",$object->ref);
 			$object->actionmsg=$langs->transnoentities("TaskDeletedInDolibarr",$object->ref);
 			$object->actionmsg.="\n".$langs->transnoentities("Task").': '.$object->ref;
-			$object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
 
 			$object->sendtoid=0;
 		}
-
-		// The trigger was enabled but we are missing the implementation, let the log know
-		else
-		{
-			dol_syslog("Trigger '".$this->name."' for action '$action' was ran by ".__FILE__." but no handler found for this action.", LOG_WARNING);
-			return 0;
+		// TODO Merge all previous cases into this generic one
+		else {
+		    // Note: We are here only if $conf->global->MAIN_AGENDA_ACTIONAUTO_action is on (tested at begining of this function) 
+		    $langs->load("agenda");
+		    $langs->load("other");
+		    
+		    $object->actiontypecode='AC_OTH_AUTO';
+		    if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities($action."InDolibarr",$object->ref);
+		    $object->actionmsg=$langs->transnoentities($action."InDolibarr",$object->ref);
+		    
+		    $object->sendtoid=0;
 		}
-
+		
+		$object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login;
+		
 		dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id);
 
         // Add entry in event table
diff --git a/htdocs/expedition/contact.php b/htdocs/expedition/contact.php
index 1354b3d49f11dcad76b66f8bd64107a0665b2bf8..7c721d7cf471b5cea02bff96e320c877299ff06d 100644
--- a/htdocs/expedition/contact.php
+++ b/htdocs/expedition/contact.php
@@ -123,13 +123,13 @@ else if ($action == 'deletecontact' && $user->rights->expedition->creer)
 		dol_print_error($db);
 	}
 }
-
+/*
 else if ($action == 'setaddress' && $user->rights->expedition->creer)
 {
 	$object->fetch($id);
 	$result=$object->setDeliveryAddress($_POST['fk_address']);
 	if ($result < 0) dol_print_error($db,$object->error);
-}
+}*/
 
 
 /*
diff --git a/htdocs/expedition/shipment.php b/htdocs/expedition/shipment.php
index 57ad04a8a1a39396b1ca18380b1bf17afbdad4d3..ede1cc6bec964a90c8c4c74a1fea490c501f4075 100644
--- a/htdocs/expedition/shipment.php
+++ b/htdocs/expedition/shipment.php
@@ -113,7 +113,7 @@ if (empty($reshook))
     	if ($result < 0)
     		setEventMessages($object->error, $object->errors, 'errors');
     }
-    
+    /*
     if ($action == 'setdeliveryaddress' && $user->rights->commande->creer)
     {
     	$object = new Commande($db);
@@ -122,7 +122,7 @@ if (empty($reshook))
     	if ($result < 0)
     		setEventMessages($object->error, $object->errors, 'errors');
     }
-    
+    */
     if ($action == 'setmode' && $user->rights->commande->creer)
     {
     	$object = new Commande($db);
diff --git a/htdocs/expensereport/card.php b/htdocs/expensereport/card.php
index db2328cdfb4693ef7f14e47d68fe3320969672d2..9a2433994bd49dbb04b0300a5ee7573b049f834f 100644
--- a/htdocs/expensereport/card.php
+++ b/htdocs/expensereport/card.php
@@ -444,14 +444,16 @@ if (empty($reshook))
    			$destinataire->fetch($object->fk_user_validator);
    			$emailTo = $destinataire->email;
     
-   			if ($emailTo)
-   			{
-   				// FROM
-   				$expediteur = new User($db);
-   				$expediteur->fetch($object->fk_user_author);
-   				$emailFrom = $expediteur->email;
+			// FROM
+			$expediteur = new User($db);
+			$expediteur->fetch($object->fk_user_author);
+			$emailFrom = $expediteur->email;
 
-    			// SUBJECT
+   			if ($emailFrom && $emailTo)
+   			{
+    			$filename=array(); $filedir=array(); $mimetype=array();
+   			    
+   			    // SUBJECT
     			$subject = $langs->transnoentities("ExpenseReportWaitingForReApproval");
     
     			// CONTENT
@@ -561,73 +563,83 @@ if (empty($reshook))
 
    			// CC
    			$emailCC = $conf->global->NDF_CC_EMAILS;
+            if (empty($emailTo)) $emailTo=$emailCC;
 
 			// FROM
    			$expediteur = new User($db);
    			$expediteur->fetch($object->fk_user_valid);
    			$emailFrom = $expediteur->email;
 
-			// SUBJECT
-   			$subject = $langs->transnoentities("ExpenseReportApproved");
-
-   			// CONTENT
-   			$link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
-   			$message = $langs->transnoentities("ExpenseReportApprovedMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $link);
-
-   			// Rebuilt pdf
-			/*
-    		$object->setDocModel($user,"");
-    		$resultPDF = expensereport_pdf_create($db,$object,'',"",$langs);
-    
-    		if($resultPDF
-			{
-    			// ATTACHMENT
+   			if ($emailFrom && $emailTo)
+   			{
     			$filename=array(); $filedir=array(); $mimetype=array();
-    			array_push($filename,dol_sanitizeFileName($object->ref).".pdf");
-    			array_push($filedir, $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref)."/".dol_sanitizeFileName($object->ref).".pdf");
-    			array_push($mimetype,"application/pdf");
-			}
-			*/
-
-        	// PREPARE SEND
-    		$mailfile = new CMailFile($subject,$emailTo,$emailFrom,$message,$filedir,$mimetype,$filename);
+   			    
+   			    // SUBJECT
+       			$subject = $langs->transnoentities("ExpenseReportApproved");
+    
+       			// CONTENT
+       			$link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
+       			$message = $langs->transnoentities("ExpenseReportApprovedMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $link);
+    
+       			// Rebuilt pdf
+    			/*
+        		$object->setDocModel($user,"");
+        		$resultPDF = expensereport_pdf_create($db,$object,'',"",$langs);
+        
+        		if($resultPDF
+    			{
+        			// ATTACHMENT
+        			$filename=array(); $filedir=array(); $mimetype=array();
+        			array_push($filename,dol_sanitizeFileName($object->ref).".pdf");
+        			array_push($filedir, $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref)."/".dol_sanitizeFileName($object->ref).".pdf");
+        			array_push($mimetype,"application/pdf");
+    			}
+    			*/
 
-   			if ($mailfile)
-   			{
-   				// SEND
-   				$result=$mailfile->sendfile();
-   				if ($result)
-   				{
-   					$mesg=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($emailFrom,2),$mailfile->getValidAddress($emailTo,2));
-   					setEventMessages($mesg, null, 'mesgs');
-   					header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
-   					exit;
-   				}
-   				else
-   				{
-   					$langs->load("other");
-   					if ($mailfile->error)
-   					{
-   						$mesg='';
-   						$mesg.=$langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo);
-   						$mesg.='<br>'.$mailfile->error;
-   						setEventMessages($mesg, null, 'errors');
-   					}
-   					else
-   					{
-   						setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings');
-   					}
-   				}
+        		$mailfile = new CMailFile($subject,$emailTo,$emailFrom,$message,$filedir,$mimetype,$filename);
+    
+       			if ($mailfile)
+       			{
+       				// SEND
+       				$result=$mailfile->sendfile();
+       				if ($result)
+       				{
+       					$mesg=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($emailFrom,2),$mailfile->getValidAddress($emailTo,2));
+       					setEventMessages($mesg, null, 'mesgs');
+       					header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
+       					exit;
+       				}
+       				else
+       				{
+       					$langs->load("other");
+       					if ($mailfile->error)
+       					{
+       						$mesg='';
+       						$mesg.=$langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo);
+       						$mesg.='<br>'.$mailfile->error;
+       						setEventMessages($mesg, null, 'errors');
+       					}
+       					else
+       					{
+       						setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings');
+       					}
+       				}
+       			}
+       			else
+       			{
+       				setEventMessages($mailfile->error,$mailfile->errors,'errors');
+       				$action='';
+       			}
    			}
-   			else
-   			{
-   				setEventMessages($mailfile->error,$mailfile->errors,'errors');
-   				$action='';
-   			}
-   		}
+    		else
+    		{
+    			setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings');
+    			$action='';
+    		}
+    	}
    		else
    		{
-   			setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings');
+   			setEventMessages($langs->trans("FailedtoSetToApprove"), null, 'warnings');
    			$action='';
    		}
    	}
@@ -677,68 +689,78 @@ if (empty($reshook))
     		$expediteur->fetch($object->fk_user_refuse);
     		$emailFrom = $expediteur->email;
     
-			// SUBJECT
-   			$subject = $langs->transnoentities("ExpenseReportRefused");
-
-   			// CONTENT
-   			$link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
-			$message = $langs->transnoentities("ExpenseReportRefusedMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $_POST['detail_refuse'], $link);
-
-   			// Rebuilt pdf
-			/*
-    		$object->setDocModel($user,"");
-    		$resultPDF = expensereport_pdf_create($db,$object,'',"",$langs);
-    
-    		if($resultPDF
-			{
-    			// ATTACHMENT
+    		if ($emailFrom && $emailTo)
+    		{
     			$filename=array(); $filedir=array(); $mimetype=array();
-    			array_push($filename,dol_sanitizeFileName($object->ref).".pdf");
-    			array_push($filedir, $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref)."/".dol_sanitizeFileName($object->ref).".pdf");
-    			array_push($mimetype,"application/pdf");
-			}
-			*/
+    		    
+    		    // SUBJECT
+       			$subject = $langs->transnoentities("ExpenseReportRefused");
     
-    		// PREPARE SEND
-    		$mailfile = new CMailFile($subject,$emailTo,$emailFrom,$message,$filedir,$mimetype,$filename);
+       			// CONTENT
+       			$link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
+    			$message = $langs->transnoentities("ExpenseReportRefusedMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $_POST['detail_refuse'], $link);
     
-    		if ($mailfile)
-    		{
-    			// SEND
-    			$result=$mailfile->sendfile();
-    			if ($result)
-    			{
-    				$mesg=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($emailFrom,2),$mailfile->getValidAddress($emailTo,2));
-    				setEventMessages($mesg, null, 'mesgs');
-    				header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
-    				exit;
-    			}
-    			else
+       			// Rebuilt pdf
+    			/*
+        		$object->setDocModel($user,"");
+        		$resultPDF = expensereport_pdf_create($db,$object,'',"",$langs);
+        
+        		if($resultPDF
     			{
-    				$langs->load("other");
-    				if ($mailfile->error)
-    				{
-    					$mesg='';
-    					$mesg.=$langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo);
-    					$mesg.='<br>'.$mailfile->error;
-    					setEventMessages($mesg, null, 'errors');
-    				}
-    				else
-    				{
-    					setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings');
-    				}
+        			// ATTACHMENT
+        			$filename=array(); $filedir=array(); $mimetype=array();
+        			array_push($filename,dol_sanitizeFileName($object->ref).".pdf");
+        			array_push($filedir, $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref)."/".dol_sanitizeFileName($object->ref).".pdf");
+        			array_push($mimetype,"application/pdf");
     			}
-    		}
-    		else
-    		{
-    			setEventMessages($mailfile->error,$mailfile->errors,'errors');
-    			$action='';
-    		}
+    			*/
+        
+        		// PREPARE SEND
+        		$mailfile = new CMailFile($subject,$emailTo,$emailFrom,$message,$filedir,$mimetype,$filename);
+        
+        		if ($mailfile)
+        		{
+        			// SEND
+        			$result=$mailfile->sendfile();
+        			if ($result)
+        			{
+        				$mesg=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($emailFrom,2),$mailfile->getValidAddress($emailTo,2));
+        				setEventMessages($mesg, null, 'mesgs');
+        				header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
+        				exit;
+        			}
+        			else
+        			{
+        				$langs->load("other");
+        				if ($mailfile->error)
+        				{
+        					$mesg='';
+        					$mesg.=$langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo);
+        					$mesg.='<br>'.$mailfile->error;
+        					setEventMessages($mesg, null, 'errors');
+        				}
+        				else
+        				{
+        					setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings');
+        				}
+        			}
+        		}
+        		else
+        		{
+        			setEventMessages($mailfile->error,$mailfile->errors,'errors');
+        			$action='';
+        		}
+        	}
+        	else
+        	{
+        		setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings');
+        		$action='';
+        	}
     	}
     	else
     	{
-    		setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings');
-    		$action='';
+    	    setEventMessages($langs->trans("FailedtoSetToDeny"), null, 'warnings');
+    	    $action='';
     	}
     }
     else
@@ -790,67 +812,77 @@ if (empty($reshook))
     			$expediteur->fetch($object->fk_user_cancel);
     			$emailFrom = $expediteur->email;
     
-				// SUBJECT
-				$subject = $langs->transnoentities("ExpenseReportCanceled");
-
-				// CONTENT
-				$link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
-				$message = $langs->transnoentities("ExpenseReportCanceledMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $_POST['detail_cancel'], $link);
-
-				// Rebuilt pdf
-				/*
-				$object->setDocModel($user,"");
-				$resultPDF = expensereport_pdf_create($db,$object,'',"",$langs);
-		
-				if($resultPDF
-				{
-					// ATTACHMENT
-					$filename=array(); $filedir=array(); $mimetype=array();
-					array_push($filename,dol_sanitizeFileName($object->ref).".pdf");
-					array_push($filedir, $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref)."/".dol_sanitizeFileName($object->ref).".pdf");
-					array_push($mimetype,"application/pdf");
-				}
-				*/
-
-    			// PREPARE SEND
-    			$mailfile = new CMailFile($subject,$emailTo,$emailFrom,$message,$filedir,$mimetype,$filename);
-    
-    			if ($mailfile)
+    			if ($emailFrom && $emailTo)
     			{
-    				// SEND
-    				$result=$mailfile->sendfile();
-    				if ($result)
+    			    $filename=array(); $filedir=array(); $mimetype=array();
+    			    
+    			    // SUBJECT
+    				$subject = $langs->transnoentities("ExpenseReportCanceled");
+    
+    				// CONTENT
+    				$link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
+    				$message = $langs->transnoentities("ExpenseReportCanceledMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $_POST['detail_cancel'], $link);
+    
+    				// Rebuilt pdf
+    				/*
+    				$object->setDocModel($user,"");
+    				$resultPDF = expensereport_pdf_create($db,$object,'',"",$langs);
+    		
+    				if($resultPDF
     				{
-    					$mesg=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($emailFrom,2),$mailfile->getValidAddress($emailTo,2));
-    					setEventMessages($mesg, null, 'mesgs');
-    					header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
-    					exit;
-    				}
-    				else
-    				{
-    					$langs->load("other");
-    					if ($mailfile->error)
-    					{
-    						$mesg='';
-    						$mesg.=$langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo);
-    						$mesg.='<br>'.$mailfile->error;
-    						setEventMessages($mesg, null, 'errors');
-    					}
-    					else
-    					{
-    						setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings');
-    					}
+    					// ATTACHMENT
+    					$filename=array(); $filedir=array(); $mimetype=array();
+    					array_push($filename,dol_sanitizeFileName($object->ref).".pdf");
+    					array_push($filedir, $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref)."/".dol_sanitizeFileName($object->ref).".pdf");
+    					array_push($mimetype,"application/pdf");
     				}
+    				*/
+    
+        			// PREPARE SEND
+        			$mailfile = new CMailFile($subject,$emailTo,$emailFrom,$message,$filedir,$mimetype,$filename);
+        
+        			if ($mailfile)
+        			{
+        				// SEND
+        				$result=$mailfile->sendfile();
+        				if ($result)
+        				{
+        					$mesg=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($emailFrom,2),$mailfile->getValidAddress($emailTo,2));
+        					setEventMessages($mesg, null, 'mesgs');
+        					header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
+        					exit;
+        				}
+        				else
+        				{
+        					$langs->load("other");
+        					if ($mailfile->error)
+        					{
+        						$mesg='';
+        						$mesg.=$langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo);
+        						$mesg.='<br>'.$mailfile->error;
+        						setEventMessages($mesg, null, 'errors');
+        					}
+        					else
+        					{
+        						setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings');
+        					}
+        				}
+        			}
+        			else
+        			{
+        				setEventMessages($mailfile->error,$mailfile->errors,'errors');
+        				$action='';
+        			}
     			}
     			else
     			{
-    				setEventMessages($mailfile->error,$mailfile->errors,'errors');
-    				$action='';
-    			}
+    			    setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings');
+    			    $action='';
+    			}        			
     		}
     		else
     		{
-    			setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings');
+    			setEventMessages($langs->trans("FailedToSetToCancel"), null, 'warnings');
     			$action='';
     		}
     	}
@@ -945,63 +977,73 @@ if (empty($reshook))
     		$expediteur->fetch($user->id);
     		$emailFrom = $expediteur->email;
     
-			// SUBJECT
-			$subject = $langs->transnoentities("ExpenseReportPaid");
-
-			// CONTENT
-			$link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
-			$message = $langs->transnoentities("ExpenseReportPaidMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $link);
-    
-    		// CONTENT
-    		$message = "Bonjour {$destinataire->firstname},\n\n";
-    		$message.= "Votre note de frais \"{$object->ref}\" vient d'être payée.\n";
-    		$message.= "- Payeur : {$expediteur->firstname} {$expediteur->lastname}\n";
-    		$message.= "- Lien : {$dolibarr_main_url_root}/expensereport/card.php?id={$object->id}\n\n";
-    		$message.= "Bien cordialement,\n' SI";
-    
-    		// Generate pdf before attachment
-    		$object->setDocModel($user,"");
-    		$resultPDF = expensereport_pdf_create($db,$object,'',"",$langs);
-    
-    		// PREPARE SEND
-    		$mailfile = new CMailFile($subject,$emailTo,$emailFrom,$message,$filedir,$mimetype,$filename);
-    
-    		if ($mailfile)
+    		if ($emailFrom && $emailTo)
     		{
-    			// SEND
-				$result=$mailfile->sendfile();
-    			if ($result)
-    			{
-    				$mesg=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($emailFrom,2),$mailfile->getValidAddress($emailTo,2));
-    				setEventMessages($mesg, null, 'mesgs');
-    				header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
-    				exit;
-    			}
-    			else
-    			{
-					$langs->load("other");
-    				if ($mailfile->error)
-    				{
-    					$mesg='';
-    					$mesg.=$langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo);
-    					$mesg.='<br>'.$mailfile->error;
-    					setEventMessages($mesg, null, 'errors');
-    				}
-    				else
-    				{
-    					setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings');
-    				}
-    			}
+    			$filename=array(); $filedir=array(); $mimetype=array();
+    		    
+    		    // SUBJECT
+    			$subject = $langs->transnoentities("ExpenseReportPaid");
+    
+    			// CONTENT
+    			$link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
+    			$message = $langs->transnoentities("ExpenseReportPaidMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $link);
+        
+        		// CONTENT
+        		$message = "Bonjour {$destinataire->firstname},\n\n";
+        		$message.= "Votre note de frais \"{$object->ref}\" vient d'être payée.\n";
+        		$message.= "- Payeur : {$expediteur->firstname} {$expediteur->lastname}\n";
+        		$message.= "- Lien : {$dolibarr_main_url_root}/expensereport/card.php?id={$object->id}\n\n";
+        		$message.= "Bien cordialement,\n' SI";
+        
+        		// Generate pdf before attachment
+        		$object->setDocModel($user,"");
+        		$resultPDF = expensereport_pdf_create($db,$object,'',"",$langs);
+        
+        		// PREPARE SEND
+        		$mailfile = new CMailFile($subject,$emailTo,$emailFrom,$message,$filedir,$mimetype,$filename);
+        
+        		if ($mailfile)
+        		{
+        			// SEND
+    				$result=$mailfile->sendfile();
+        			if ($result)
+        			{
+        				$mesg=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($emailFrom,2),$mailfile->getValidAddress($emailTo,2));
+        				setEventMessages($mesg, null, 'mesgs');
+        				header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
+        				exit;
+        			}
+        			else
+        			{
+    					$langs->load("other");
+        				if ($mailfile->error)
+        				{
+        					$mesg='';
+        					$mesg.=$langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo);
+        					$mesg.='<br>'.$mailfile->error;
+        					setEventMessages($mesg, null, 'errors');
+        				}
+        				else
+        				{
+        					setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings');
+        				}
+        			}
+        		}
+        		else
+        		{
+        			setEventMessages($mailfile->error,$mailfile->errors,'errors');
+        			$action='';
+        		}
     		}
     		else
     		{
-    			setEventMessages($mailfile->error,$mailfile->errors,'errors');
-    			$action='';
+    		    setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings');
+    		    $action='';
     		}
     	}
     	else
     	{
-    		setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings');
+    		setEventMessages($langs->trans("FailedToSetPaid"), null, 'warnings');
     		$action='';
     	}
     }
diff --git a/htdocs/fichinter/admin/fichinter_extrafields.php b/htdocs/fichinter/admin/fichinter_extrafields.php
index b7b809d277dc2f17c3cbb0d4e07fcdbfbadff00f..bab7572e60a39463d30f9a1cbd5cf2af7061aa01 100644
--- a/htdocs/fichinter/admin/fichinter_extrafields.php
+++ b/htdocs/fichinter/admin/fichinter_extrafields.php
@@ -71,7 +71,7 @@ print load_fiche_titre($langs->trans("InterventionsSetup"),$linkback,'title_setu
 
 $head=fichinter_admin_prepare_head();
 
-dol_fiche_head($head, 'attributes', $langs->trans("Interventions"), 0, 'intervention');
+dol_fiche_head($head, 'attributes', $langs->trans("Interventions"), -1, 'intervention');
 
 require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_view.tpl.php';
 
diff --git a/htdocs/fichinter/admin/fichinterdet_extrafields.php b/htdocs/fichinter/admin/fichinterdet_extrafields.php
index 776229a4c2916e0a65740fc1bec5e3d74815c9b1..5fadc3f4c2c3a5859c38a4755b020b89838afeb6 100644
--- a/htdocs/fichinter/admin/fichinterdet_extrafields.php
+++ b/htdocs/fichinter/admin/fichinterdet_extrafields.php
@@ -72,7 +72,7 @@ print load_fiche_titre($langs->trans("InterventionsSetup"),$linkback,'title_setu
 
 $head=fichinter_admin_prepare_head();
 
-dol_fiche_head($head, 'attributesdet', $langs->trans("Interventions"), 0, 'intervention');
+dol_fiche_head($head, 'attributesdet', $langs->trans("Interventions"), -1, 'intervention');
 
 require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_view.tpl.php';
 
diff --git a/htdocs/fourn/class/fournisseur.commande.class.php b/htdocs/fourn/class/fournisseur.commande.class.php
index 04f50e9fbcb90671f93eddefdccc3b1b822f8220..6b9ded021602bac8ca5234e50b5a69198bc7d28e 100644
--- a/htdocs/fourn/class/fournisseur.commande.class.php
+++ b/htdocs/fourn/class/fournisseur.commande.class.php
@@ -1487,6 +1487,9 @@ class CommandeFournisseur extends CommonOrder
 			$localtax2_type=$localtaxes_type[2];
 
             $subprice = price2num($pu,'MU');
+            
+            $rangmax = $this->line_max();
+            $rang = $rangmax + 1;
 
             // Insert line
             $this->line=new CommandeFournisseurLigne($this->db);
@@ -2669,21 +2672,22 @@ class CommandeFournisseur extends CommonOrder
             $sql.= " FROM ".MAIN_DB_PREFIX.'c_input_method';
             $sql.= " WHERE active=1 AND rowid = ".$db->escape($this->methode_commande_id);
 
-            $query = $db->query($sql);
-            if ($query && $db->num_rows($query))
+            $resql = $db->query($sql);
+            if ($resql)
             {
-                $obj = $db->fetch_object($query);
-
-                $string = $langs->trans($obj->code);
-                if ($string == $obj->code)
+                if ($db->num_rows($query))
                 {
-                    $string = $obj->label != '-' ? $obj->label : '';
-                }
-
-                return $string;
+                    $obj = $db->fetch_object($query);
+    
+                    $string = $langs->trans($obj->code);
+                    if ($string == $obj->code)
+                    {
+                        $string = $obj->label != '-' ? $obj->label : '';
+                    }
+                    return $string;
+                }    
             }
-
-            dol_print_error($db);
+            else dol_print_error($db);
         }
 
         return '';
@@ -2817,7 +2821,7 @@ class CommandeFournisseur extends CommonOrder
 
     
     /**
-     * Calc status regarding dispatch stock
+     * Calc status regarding to dispatched stock
      *
      * @param 		User 	$user                   User action
      * @param       int     $closeopenorder         Close if received
diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php
index 42daafe9c2d018a52213e4dae23ef00ed1e335f5..1798eb190599f684386725393a000617636d5317 100644
--- a/htdocs/fourn/class/fournisseur.facture.class.php
+++ b/htdocs/fourn/class/fournisseur.facture.class.php
@@ -128,7 +128,9 @@ class FactureFournisseur extends CommonInvoice
     public $multicurrency_total_ht;
     public $multicurrency_total_tva;
     public $multicurrency_total_ttc;
-
+    //! id of source invoice if replacement invoice or credit note
+    public $fk_facture_source;
+    
     /**
      * Standard invoice
      */
@@ -263,6 +265,7 @@ class FactureFournisseur extends CommonInvoice
         $sql.= ", fk_multicurrency";
         $sql.= ", multicurrency_code";
         $sql.= ", multicurrency_tx";
+        $sql.= ", fk_facture_source";
         $sql.= ")";
         $sql.= " VALUES (";
 		$sql.= "'(PROV)'";
@@ -286,6 +289,7 @@ class FactureFournisseur extends CommonInvoice
 		$sql.= ", ".(int) $this->fk_multicurrency;
 		$sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
 		$sql.= ", ".(double) $this->multicurrency_tx;
+        $sql.= ", ".(isset($this->fk_facture_source)?$this->fk_facture_source:"NULL");
         $sql.= ")";
 
         dol_syslog(get_class($this)."::create", LOG_DEBUG);
diff --git a/htdocs/fourn/commande/dispatch.php b/htdocs/fourn/commande/dispatch.php
index c87b3a62bedc0fd688236bdd099077525711926e..b7e3830ad5c1987f0e947fb82f8bf745ba5b52c7 100644
--- a/htdocs/fourn/commande/dispatch.php
+++ b/htdocs/fourn/commande/dispatch.php
@@ -467,16 +467,14 @@ if ($id > 0 || ! empty($ref)) {
 					if ($remaintodispatch || empty($conf->global->SUPPLIER_ORDER_DISABLE_STOCK_DISPATCH_WHEN_TOTAL_REACHED)) {
 						$nbproduct++;
 
-						$var = ! $var;
-
 						// To show detail cref and description value, we must make calculation by cref
 						// print ($objp->cref?' ('.$objp->cref.')':'');
 						// if ($objp->description) print '<br>'.nl2br($objp->description);
 						$suffix = '_0_' . $i;
 
 						print "\n";
-						print '<!-- Line ' . $suffix . ' -->' . "\n";
-						print "<tr " . $bc[$var] . ">";
+						print '<!-- Line to dispatch ' . $suffix . ' -->' . "\n";
+						print '<tr class="oddeven">';
 
 						$linktoprod = '<a href="' . DOL_URL_ROOT . '/product/fournisseurs.php?id=' . $objp->fk_product . '">' . img_object($langs->trans("ShowProduct"), 'product') . ' ' . $objp->ref . '</a>';
 						$linktoprod .= ' - ' . $objp->label . "\n";
@@ -500,7 +498,7 @@ if ($id > 0 || ! empty($ref)) {
 							print "</td>";
 						}
 
-						$var = ! $var;
+						// Define unit price for PMP calculation
 						$up_ht_disc = $objp->subprice;
 						if (! empty($objp->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP))
 							$up_ht_disc = price2num($up_ht_disc * (100 - $objp->remise_percent) / 100, 'MU');
@@ -517,11 +515,21 @@ if ($id > 0 || ! empty($ref)) {
 							print '<td></td>'; // Warehouse column
 							print '</tr>';
 
-							print '<tr ' . $bc[$var] . ' name="' . $type . $suffix . '">';
+							print '<tr class="oddeven" name="' . $type . $suffix . '">';
 							print '<td>';
 							print '<input name="fk_commandefourndet' . $suffix . '" type="hidden" value="' . $objp->rowid . '">';
 							print '<input name="product_batch' . $suffix . '" type="hidden" value="' . $objp->fk_product . '">';
-							print '<input name="pu' . $suffix . '" type="hidden" value="' . $up_ht_disc . '"><!-- This is a up including discount -->';
+							
+							print '<!-- This is a up (may include discount or not depending on STOCK_EXCLUDE_DISCOUNT_FOR_PMP. will be used for PMP calculation) -->';
+							if (! empty($conf->global->SUPPLIER_ORDER_EDIT_BUYINGPRICE_DURING_RECEIPT)) // Not tested !
+							{
+							    print $langs->trans("BuyingPrice").': <input class="maxwidth75" name="pu' . $suffix . '" type="text" value="' . price2num($up_ht_disc, 'MU') . '">';
+							}
+							else
+							{
+							    print '<input class="maxwidth75" name="pu' . $suffix . '" type="hidden" value="' . price2num($up_ht_disc, 'MU') . '">';
+							}
+
 							// hidden fields for js function
 							print '<input id="qty_ordered' . $suffix . '" type="hidden" value="' . $objp->qty . '">';
 							print '<input id="qty_dispatched' . $suffix . '" type="hidden" value="' . ( float ) $products_dispatched[$objp->rowid] . '">';
@@ -544,11 +552,22 @@ if ($id > 0 || ! empty($ref)) {
 							print '<td align="right">' . img_picto($langs->trans('AddStockLocationLine'), 'split.png', 'onClick="addDispatchLine(' . $i . ',\'' . $type . '\')"') . '</td>'; // Dispatch column
 							print '<td></td>';
 							print '</tr>';
-							print '<tr ' . $bc[$var] . ' name="' . $type . $suffix . '">';
+
+							print '<tr class="oddeven" name="' . $type . $suffix . '">';
 							print '<td colspan="6">';
 							print '<input name="fk_commandefourndet' . $suffix . '" type="hidden" value="' . $objp->rowid . '">';
 							print '<input name="product' . $suffix . '" type="hidden" value="' . $objp->fk_product . '">';
-							print '<input name="pu' . $suffix . '" type="hidden" value="' . $up_ht_disc . '"><!-- This is a up including discount -->';
+							
+							print '<!-- This is a up (may include discount or not depending on STOCK_EXCLUDE_DISCOUNT_FOR_PMP. will be used for PMP calculation) -->';
+							if (! empty($conf->global->SUPPLIER_ORDER_EDIT_BUYINGPRICE_DURING_RECEIPT)) // Not tested !
+							{
+							    print $langs->trans("BuyingPrice").': <input class="maxwidth75" name="pu' . $suffix . '" type="text" value="' . price2num($up_ht_disc, 'MU') . '">';
+							}
+							else
+							{
+							    print '<input class="maxwidth75" name="pu' . $suffix . '" type="hidden" value="' . price2num($up_ht_disc, 'MU') . '">';
+							}
+							
 							// hidden fields for js function
 							print '<input id="qty_ordered' . $suffix . '" type="hidden" value="' . $objp->qty . '">';
 							print '<input id="qty_dispatched' . $suffix . '" type="hidden" value="' . ( float ) $products_dispatched[$objp->rowid] . '">';
diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php
index 04af9470e6d928a73b7c576ebe5ecf39e9ed8eb9..f930ad879796ca6b3516cefdc56af62fe074fffe 100644
--- a/htdocs/fourn/facture/card.php
+++ b/htdocs/fourn/facture/card.php
@@ -70,7 +70,7 @@ $projectid	= GETPOST('projectid','int');
 $origin		= GETPOST('origin', 'alpha');
 $originid	= GETPOST('originid', 'int');
 
-//PDF
+// PDF
 $hidedetails = (GETPOST('hidedetails','int') ? GETPOST('hidedetails','int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0));
 $hidedesc 	 = (GETPOST('hidedesc','int') ? GETPOST('hidedesc','int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ?  1 : 0));
 $hideref 	 = (GETPOST('hideref','int') ? GETPOST('hideref','int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0));
@@ -1194,32 +1194,11 @@ if (empty($reshook))
 	$trackid='sin'.$object->id;
 	include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
 
-
-	// Build document
-	if ($action == 'builddoc')
-	{
-		// Save modele used
-	    $object->fetch($id);
-	    $object->fetch_thirdparty();
-
-		// Save last template used to generate document
-		if (GETPOST('model')) $object->setDocModel($user, GETPOST('model','alpha'));
-
-	    $outputlangs = $langs;
-	    $newlang=GETPOST('lang_id','alpha');
-	    if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$object->thirdparty->default_lang;
-	    if (! empty($newlang))
-	    {
-	        $outputlangs = new Translate("",$conf);
-	        $outputlangs->setDefaultLang($newlang);
-	    }
-		$result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
-	    if ($result	< 0)
-	    {
-			setEventMessages($object->error, $object->errors, 'errors');
-    	    $action='';
-	    }
-	}
+	// Actions to build doc
+	$upload_dir = $conf->fournisseur->facture->dir_output;
+	$permissioncreate = $user->rights->fournisseur->facture->creer;
+	include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
+	
 	// Make calculation according to calculationrule
 	if ($action == 'calculate')
 	{
@@ -1234,22 +1213,6 @@ if (empty($reshook))
 	        exit;
 	    }
 	}
-	// Delete file in doc form
-	if ($action == 'remove_file')
-	{
-	    require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
-
-	    if ($object->fetch($id))
-	    {
-	    	$object->fetch_thirdparty();
-	        $upload_dir =	$conf->fournisseur->facture->dir_output . "/";
-	        $file =	$upload_dir	. '/' .	GETPOST('file');
-	        $ret=dol_delete_file($file,0,0,0,$object);
-	        if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('urlfile')), null, 'mesgs');
-	        else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile')), null, 'errors');
-	    }
-	}
-
 	if ($action == 'update_extras')
 	{
 		// Fill array 'array_options' with data from add form
@@ -1924,7 +1887,7 @@ else
         $head = facturefourn_prepare_head($object);
         $titre=$langs->trans('SupplierInvoice');
 
-        dol_fiche_head($head, 'card', $titre, 0, 'bill');
+        dol_fiche_head($head, 'card', $titre, -1, 'bill');
 
         // Clone confirmation
         if ($action == 'clone')
@@ -2792,8 +2755,8 @@ else
 	                 * Documents generes
 	                 */
 	                $ref=dol_sanitizeFileName($object->ref);
-	                $subdir = get_exdir($object->id,2,0,0,$object,'invoice_supplier').$ref;
-	                $filedir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($object->id,2,0,0,$object,'invoice_supplier').$ref;
+	                $subdir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$ref;
+	                $filedir = $conf->fournisseur->facture->dir_output.'/'.$subdir;
 	                $urlsource=$_SERVER['PHP_SELF'].'?id='.$object->id;
 	                $genallowed=$user->rights->fournisseur->facture->creer;
 	                $delallowed=$user->rights->fournisseur->facture->supprimer;
diff --git a/htdocs/fourn/facture/contact.php b/htdocs/fourn/facture/contact.php
index cafc6c1a496fb69814c928f0888fe46d887c5274..0f56c5f7bae732e4c93a86c723bb9377d05eb2a4 100644
--- a/htdocs/fourn/facture/contact.php
+++ b/htdocs/fourn/facture/contact.php
@@ -138,7 +138,7 @@ if ($id > 0 || ! empty($ref))
 		
 		$head = facturefourn_prepare_head($object);
 
-		dol_fiche_head($head, 'contact', $langs->trans('SupplierInvoice'), 0, 'bill');
+		dol_fiche_head($head, 'contact', $langs->trans('SupplierInvoice'), -1, 'bill');
 
 		$linkback = '<a href="' . DOL_URL_ROOT . '/compta/facture/list.php' . (! empty($socid) ? '?socid=' . $socid : '') . '">' . $langs->trans("BackToList") . '</a>';
 
diff --git a/htdocs/fourn/facture/document.php b/htdocs/fourn/facture/document.php
index 2563a176346bd6699ccdb75c707db427b7909bdd..ab56a66d8a7e77998a0a96b4c1261b2c5ae43186 100644
--- a/htdocs/fourn/facture/document.php
+++ b/htdocs/fourn/facture/document.php
@@ -89,7 +89,7 @@ llxHeader('', $title, $helpurl);
 if ($object->id > 0)
 {
 	$head = facturefourn_prepare_head($object);
-	dol_fiche_head($head, 'documents', $langs->trans('SupplierInvoice'), 0, 'bill');
+	dol_fiche_head($head, 'documents', $langs->trans('SupplierInvoice'), -1, 'bill');
     
 	$totalpaye = $object->getSommePaiement();
 
@@ -230,6 +230,8 @@ if ($object->id > 0)
 
 	print '</table><br>';
 
+	print '<div class="underbanner clearboth"></div>';
+	
 	print '<table class="border" width="100%">';
 
 	// Nb of files
diff --git a/htdocs/fourn/facture/info.php b/htdocs/fourn/facture/info.php
index af98c4f9b6648ebb7c8dcd0e7ccbeacbc83b7ebb..f5ab9164042b4e086a354ca91648cb406c2f93e3 100644
--- a/htdocs/fourn/facture/info.php
+++ b/htdocs/fourn/facture/info.php
@@ -59,7 +59,7 @@ $alreadypaid=$object->getSommePaiement();
 
 $head = facturefourn_prepare_head($object);
 $titre=$langs->trans('SupplierInvoice');
-dol_fiche_head($head, 'info', $langs->trans('SupplierInvoice'), 0, 'bill');
+dol_fiche_head($head, 'info', $langs->trans('SupplierInvoice'), -1, 'bill');
 
 $linkback = '<a href="' . DOL_URL_ROOT . '/compta/facture/list.php' . (! empty($socid) ? '?socid=' . $socid : '') . '">' . $langs->trans("BackToList") . '</a>';
 
diff --git a/htdocs/fourn/facture/note.php b/htdocs/fourn/facture/note.php
index cd009e394f66185015db168ac9a491963e48c029..9df425040e1a41305bde66f7c2c67a805b2207b8 100644
--- a/htdocs/fourn/facture/note.php
+++ b/htdocs/fourn/facture/note.php
@@ -79,11 +79,9 @@ if ($object->id > 0)
 	
 	$head = facturefourn_prepare_head($object);
 	$titre=$langs->trans('SupplierInvoice');
-	dol_fiche_head($head, 'note', $titre, 0, 'bill');
+	dol_fiche_head($head, 'note', $titre, -1, 'bill');
 
 
-	print '<table class="border" width="100%">';
-
 	// Supplier invoice card
     $linkback = '<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php'.(! empty($socid)?'?socid='.$socid:'').'">'.$langs->trans("BackToList").'</a>';
 
@@ -135,7 +133,9 @@ if ($object->id > 0)
     print '<div class="fichecenter">';
     print '<div class="underbanner clearboth"></div>';
 
-	// Type
+	print '<table class="border" width="100%">';
+
+    // Type
 	print '<tr><td class="titlefield">'.$langs->trans('Type').'</td><td>';
 	print $object->getLibType();
 	if ($object->type == FactureFournisseur::TYPE_REPLACEMENT)
@@ -203,6 +203,7 @@ if ($object->id > 0)
 
 	print '<br>';
 
+    print '<div class="underbanner clearboth"></div>';
 	$cssclass="titlefield";
 	include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php';
 
diff --git a/htdocs/ftp/admin/ftpclient.php b/htdocs/ftp/admin/ftpclient.php
index 158d9fed3da9ace5138510266c18dd90b1d19b4d..845760c26b7f7123ece08090ef8da15fdcd89630 100644
--- a/htdocs/ftp/admin/ftpclient.php
+++ b/htdocs/ftp/admin/ftpclient.php
@@ -247,40 +247,46 @@ else
 			print '<td></td>';
 			print "</tr>";
 
-			
+			$keyforname="FTP_NAME_" . $idrss;
+			$keyforserver="FTP_SERVER_" . $idrss;
+			$keyforport="FTP_PORT_" . $idrss;
+			$keyforuser="FTP_USER_" . $idrss;
+			$keyforpassword="FTP_PASSWORD_" . $idrss;
+			$keyforpassive="FTP_PASSIVE_" . $idrss;
+				
 			print '<tr class="oddeven">';
 			print "<td>".$langs->trans("Name")."</td>";
-			print "<td><input type=\"text\" class=\"flat\" name=\"FTP_NAME_" . $idrss . "\" value=\"" . @constant("FTP_NAME_" . $idrss) . "\" size=\"64\"></td>";
+			print "<td><input type=\"text\" class=\"flat\" name=\"FTP_NAME_" . $idrss . "\" value=\"" . $conf->global->$keyforname . "\" size=\"64\"></td>";
 			print "</tr>";
 
 			
 			print '<tr class="oddeven">';
 			print "<td>".$langs->trans("Server")."</td>";
-			print "<td><input type=\"text\" class=\"flat\" name=\"FTP_SERVER_" . $idrss . "\" value=\"" . @constant("FTP_SERVER_" . $idrss) . "\" size=\"64\"></td>";
+			print "<td><input type=\"text\" class=\"flat\" name=\"FTP_SERVER_" . $idrss . "\" value=\"" . $conf->global->$keyforserver . "\" size=\"64\"></td>";
 			print "</tr>";
 
 			
 			print '<tr class="oddeven">';
 			print "<td width=\"100\">".$langs->trans("Port")."</td>";
-			print "<td><input type=\"text\" class=\"flat\" name=\"FTP_PORT_" . $idrss . "\" value=\"" . @constant("FTP_PORT_" . $idrss) . "\" size=\"64\"></td>";
+			print "<td><input type=\"text\" class=\"flat\" name=\"FTP_PORT_" . $idrss . "\" value=\"" . $conf->global->$keyforport . "\" size=\"64\"></td>";
 			print "</tr>";
 
 			
 			print '<tr class="oddeven">';
 			print "<td width=\"100\">".$langs->trans("User")."</td>";
-			print "<td><input type=\"text\" class=\"flat\" name=\"FTP_USER_" . $idrss . "\" value=\"" . @constant("FTP_USER_" . $idrss) . "\" size=\"24\"></td>";
+			print "<td><input type=\"text\" class=\"flat\" name=\"FTP_USER_" . $idrss . "\" value=\"" . $conf->global->$keyforuser . "\" size=\"24\"></td>";
 			print "</tr>";
 
 			
 			print '<tr class="oddeven">';
 			print "<td width=\"100\">".$langs->trans("Password")."</td>";
-			print "<td><input type=\"password\" class=\"flat\" name=\"FTP_PASSWORD_" . $idrss . "\" value=\"" . @constant("FTP_PASSWORD_" . $idrss) . "\" size=\"24\"></td>";
+			print "<td><input type=\"password\" class=\"flat\" name=\"FTP_PASSWORD_" . $idrss . "\" value=\"" . $conf->global->$keyforpassword . "\" size=\"24\"></td>";
 			print "</tr>";
 
 			
 			print '<tr class="oddeven">';
 			print "<td width=\"100\">".$langs->trans("FTPPassiveMode")."</td>";
-			print '<td>'.$form->selectyesno('FTP_PASSIVE_'.$idrss, @constant("FTP_PASSIVE_" . $idrss), 1).'</td>';
+			print '<td>'.$form->selectyesno('FTP_PASSIVE_'.$idrss, $conf->global->$keyforpassive, 1).'</td>';
 			print "</tr>";
 
 			print "<tr>";
diff --git a/htdocs/holiday/list.php b/htdocs/holiday/list.php
index d9c5fdf43c080ddd2957b9760e90f77735676d58..d35fa9293c375a2d4ef36a4dba810a2ed42a4f6f 100644
--- a/htdocs/holiday/list.php
+++ b/htdocs/holiday/list.php
@@ -202,7 +202,7 @@ $user_id = $user->id;
 if ($id > 0)
 {
 	// Charge utilisateur edite
-	$fuser->fetch($id);
+	$fuser->fetch($id, '', '', 1);
 	$fuser->getrights();
 	$user_id = $fuser->id;
 }
@@ -282,6 +282,7 @@ print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
 print '<input type="hidden" name="action" value="list">';
 print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
 print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
+if ($id > 0) print '<input type="hidden" name="id" value="'.$id.'">';
 
 if ($sall)
 {
diff --git a/htdocs/includes/odtphp/Segment.php b/htdocs/includes/odtphp/Segment.php
index 39761aa4d0439504198810deaacd59a2d106a707..40668215647625589800f1fa08f3d448667196d1 100644
--- a/htdocs/includes/odtphp/Segment.php
+++ b/htdocs/includes/odtphp/Segment.php
@@ -1,14 +1,16 @@
 <?php
 require 'SegmentIterator.php';
 class SegmentException extends Exception
-{}
+{
+}
+
 /**
  * Class for handling templating segments with odt files
  * You need PHP 5.2 at least
  * You need Zip Extension or PclZip library
  *
- * @copyright  GPL License 2008 - Julien Pauli - Cyril PIERRE de GEYER - Anaska (http://www.anaska.com)
- * @copyright  GPL License 2012 - Stephen Larroque - lrq3000@gmail.com
+ * @copyright  2008 - Julien Pauli - Cyril PIERRE de GEYER - Anaska (http://www.anaska.com)
+ * @copyright  2012 - Stephen Larroque - lrq3000@gmail.com
  * @license    http://www.gnu.org/copyleft/gpl.html  GPL License
  * @version 1.4.5 (last update 2013-04-07)
  */
@@ -22,11 +24,13 @@ class Segment implements IteratorAggregate, Countable
 	protected $images = array();
 	protected $odf;
 	protected $file;
+	
     /**
      * Constructor
      *
-     * @param string $name name of the segment to construct
-     * @param string $xml XML tree of the segment
+     * @param string $name  name of the segment to construct
+     * @param string $xml   XML tree of the segment
+     * @param string $odf   odf
      */
     public function __construct($name, $xml, $odf)
     {
@@ -139,6 +143,8 @@ class Segment implements IteratorAggregate, Countable
         }
         $reg = "/\[!--\sBEGIN\s$this->name\s--\](.*)\[!--\sEND\s$this->name\s--\]/sm";
         $this->xmlParsed = preg_replace($reg, '$1', $this->xmlParsed);
+	// Miguel Erill 09704/2017 - Add macro replacement to invoice lines
+        $this->xmlParsed = $this->macroReplace($this->xmlParsed);
         $this->file->open($this->odf->getTmpfile());
         foreach ($this->images as $imageKey => $imageValue) {
 			if ($this->file->getFromName('Pictures/' . $imageValue) === false) {
@@ -152,10 +158,35 @@ class Segment implements IteratorAggregate, Countable
         
         return $this->xmlParsed;
     }
+
+   /**
+    * Function to replace macros for invoice short and long month, invoice year
+    * 
+    * Substitution occur when the invoice is generated, not considering the invoice date
+    * so do not (re)generate in a diferent date than the one that the invoice belongs to
+    * Perhaps it would be better to use the invoice issued date but I still do not know
+    * how to get it here
+    *
+    * Miguel Erill 09/04/2017
+    * 
+    * @param	string	$value	String to convert
+    */
+    public function macroReplace($text)
+    {
+        global $langs;
+
+        $patterns=array( '__CURRENTDAY__','__CURRENTDAYTEXT__','__CURRENTMONTHSHORT__','__CURRENTMONTH__','__CURRENTYEAR__' );
+        $values=array( date('j'), $langs->trans(date('l')), $langs->trans(date('M')), $langs->trans(date('F')), date('Y') );
+
+        $text=preg_replace($patterns, $values, $text);
+
+	return $text;
+    }
+
     /**
      * Analyse the XML code in order to find children
      *
-     * @param string $xml
+     * @param string $xml   Xml
      * @return Segment
      */
     protected function _analyseChildren($xml)
@@ -172,11 +203,14 @@ class Segment implements IteratorAggregate, Countable
         }
         return $this;
     }
+    
     /**
      * Assign a template variable to replace
      *
-     * @param string $key
-     * @param string $value
+     * @param string $key       Key
+     * @param string $value     Value
+     * @param string $encode    Encode
+     * @param string $charset   Charset
      * @throws SegmentException
      * @return Segment
      */
@@ -230,7 +264,7 @@ IMG;
     /**
      * Shortcut to retrieve a child
      *
-     * @param string $prop
+     * @param string $prop      Prop
      * @return Segment
      * @throws SegmentException
      */
@@ -245,8 +279,8 @@ IMG;
     /**
      * Proxy for setVars
      *
-     * @param string $meth
-     * @param array $args
+     * @param string $meth      Meth
+     * @param array $args       Args
      * @return Segment
      */
     public function __call($meth, $args)
diff --git a/htdocs/includes/odtphp/odf.php b/htdocs/includes/odtphp/odf.php
index d052482845cdcb4f9adc9f1b1df545a1ccb5ade0..01633634705a3ab3372c225a548815b44d6a1bb6 100644
--- a/htdocs/includes/odtphp/odf.php
+++ b/htdocs/includes/odtphp/odf.php
@@ -1,16 +1,20 @@
 <?php
+
 require 'Segment.php';
+
 class OdfException extends Exception
-{}
+{
+}
+
 /**
  * Templating class for odt file
  * You need PHP 5.2 at least
  * You need Zip Extension or PclZip library
  *
- * @copyright  GPL License 2008 - Julien Pauli - Cyril PIERRE de GEYER - Anaska (http://www.anaska.com)
- * @copyright  GPL License 2010-2015 - Laurent Destailleur - eldy@users.sourceforge.net
- * @copyright  GPL License 2010 - Vikas Mahajan - http://vikasmahajan.wordpress.com
- * @copyright  GPL License 2012 - Stephen Larroque - lrq3000@gmail.com
+ * @copyright  2008 - Julien Pauli - Cyril PIERRE de GEYER - Anaska (http://www.anaska.com)
+ * @copyright  2010-2015 - Laurent Destailleur - eldy@users.sourceforge.net
+ * @copyright  2010 - Vikas Mahajan - http://vikasmahajan.wordpress.com
+ * @copyright  2012 - Stephen Larroque - lrq3000@gmail.com
  * @license    http://www.gnu.org/copyleft/gpl.html  GPL License
  * @version 1.5.0
  */
@@ -43,7 +47,8 @@ class Odf
 	/**
 	 * Class constructor
 	 *
-	 * @param string $filename the name of the odt file
+	 * @param string $filename     The name of the odt file
+	 * @param string $config       Array of config data
 	 * @throws OdfException
 	 */
 	public function __construct($filename, $config = array())
@@ -116,9 +121,10 @@ class Odf
 	/**
 	 * Assing a template variable
 	 *
-	 * @param string $key name of the variable within the template
-	 * @param string $value replacement value
-	 * @param bool $encode if true, special XML characters are encoded
+	 * @param string   $key        Name of the variable within the template
+	 * @param string   $value      Replacement value
+	 * @param bool     $encode     If true, special XML characters are encoded
+	 * @param string   $charset    Charset  
 	 * @throws OdfException
 	 * @return odf
 	 */
@@ -129,7 +135,7 @@ class Odf
 		// <text:span text:style-name="T13">{</text:span><text:span text:style-name="T12">aaa</text:span><text:span text:style-name="T13">}</text:span>
 		// instead of {aaa} so we should enhance this function.
 		//print $key.'-'.$value.'-'.strpos($this->contentXml, $this->config['DELIMITER_LEFT'] . $key . $this->config['DELIMITER_RIGHT']).'<br>';
-		if (strpos($this->contentXml, $tag) === false && strpos($this->stylesXml , $tag) === false) {
+		if (strpos($this->contentXml, $tag) === false && strpos($this->stylesXml, $tag) === false) {
 			//if (strpos($this->contentXml, '">'. $key . '</text;span>') === false) {
 			throw new OdfException("var $key not found in the document");
 			//}
@@ -577,6 +583,7 @@ IMG;
 		}
 		else
 		{
+		    dol_syslog(get_class($this).'::exportAsAttachedPDF is used but the constant MAIN_DOL_SCRIPTS_ROOT with path to script directory was not defined.', LOG_WARNING);
 			$command = '../../scripts/odt2pdf/odt2pdf.sh '.escapeshellcmd($name).' '.(is_numeric($conf->global->MAIN_ODT_AS_PDF)?'jodconverter':$conf->global->MAIN_ODT_AS_PDF);
 		}
 
@@ -642,7 +649,8 @@ IMG;
 	/**
 	 * Returns a variable of configuration
 	 *
-	 * @return string The requested variable of configuration
+	 * @param  string  $configKey  Config key
+	 * @return string              The requested variable of configuration
 	 */
 	public function getConfig($configKey)
 	{
@@ -678,7 +686,8 @@ IMG;
 
 	/**
 	 * Empty the temporary working directory recursively
-	 * @param $dir the temporary working directory
+	 * 
+	 * @param  string  $dir    The temporary working directory
 	 * @return void
 	 */
 	private function _rrmdir($dir)
@@ -701,8 +710,8 @@ IMG;
 	/**
 	 * return the value present on odt in [valuename][/valuename]
 	 * 
-	 * @param  string $value   name balise in the template
-	 * @return string          the value inside the balise
+	 * @param  string $valuename   Balise in the template
+	 * @return string              The value inside the balise
 	 */
 	public function getvalue($valuename)
 	{
diff --git a/htdocs/install/mysql/data/llx_accounting.sql b/htdocs/install/mysql/data/llx_accounting.sql
index 5f0e8dd5416f8007d841e077e777f0e52cb35c5d..e81d13dd2b8b447882b8c8a7351482c931fe3d6e 100644
--- a/htdocs/install/mysql/data/llx_accounting.sql
+++ b/htdocs/install/mysql/data/llx_accounting.sql
@@ -27,15 +27,11 @@
 -- de l'install et tous les sigles '--' sont supprimés.
 --
 
-delete from llx_accounting_account;
-delete from llx_accounting_system;
-delete from llx_accounting_journal;
-
-INSERT INTO llx_accounting_journal (rowid, code, label, nature, active) VALUES (1,'VT', 'Journal des ventes', 1, 1);
-INSERT INTO llx_accounting_journal (rowid, code, label, nature, active) VALUES (2,'AC', 'Journal des achats', 2, 1);
-INSERT INTO llx_accounting_journal (rowid, code, label, nature, active) VALUES (3,'BQ', 'Journal de banque', 3, 1);
-INSERT INTO llx_accounting_journal (rowid, code, label, nature, active) VALUES (4,'OD', 'Journal des opérations diverses', 0, 1);
-INSERT INTO llx_accounting_journal (rowid, code, label, nature, active) VALUES (5,'AN', 'Journal des à-nouveaux', 9, 1);
+INSERT INTO llx_accounting_journal (code, label, nature, active) VALUES ('VT', 'Journal des ventes', 2, 1);
+INSERT INTO llx_accounting_journal (code, label, nature, active) VALUES ('AC', 'Journal des achats', 3, 1);
+INSERT INTO llx_accounting_journal (code, label, nature, active) VALUES ('BQ', 'Journal de banque', 4, 1);
+INSERT INTO llx_accounting_journal (code, label, nature, active) VALUES ('OD', 'Journal des opérations diverses', 1, 1);
+INSERT INTO llx_accounting_journal (code, label, nature, active) VALUES ('AN', 'Journal des à-nouveaux', 9, 1);
 --
 -- Descriptif des plans comptables FR PCG99-ABREGE
 --
diff --git a/htdocs/install/mysql/data/llx_c_action_trigger.sql b/htdocs/install/mysql/data/llx_c_action_trigger.sql
index 9aadb0c083eed013573e44650b5fea2494cc1d96..d25963e8c3aa4f6abba536b4fc0ec3f93e7028a0 100644
--- a/htdocs/install/mysql/data/llx_c_action_trigger.sql
+++ b/htdocs/install/mysql/data/llx_c_action_trigger.sql
@@ -78,6 +78,10 @@ insert into llx_c_action_trigger (code,label,description,elementtype,rang) value
 insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('FICHINTER_SENTBYMAIL','Intervention sent by mail','Executed when a intervention is sent by mail','ficheinter',35);
 insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('PRODUCT_CREATE','Product or service created','Executed when a product or sevice is created','product',40);
 insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('PRODUCT_DELETE','Product or service deleted','Executed when a product or sevice is deleted','product',42);
+insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('EXPENSE_REPORT_CREATE','Expense report created','Executed when an expense report is created','expensereport',201);
+insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('EXPENSE_REPORT_VALIDATE','Expense report validated','Executed when an expense report is validated','expensereport',202);
+insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('EXPENSE_REPORT_APPROVE','Expense report approved','Executed when an expense report is approved','expensereport',203);
+insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('EXPENSE_REPORT_PAYED','Expense report billed','Executed when an expense report is set as billed','expensereport',204);
 insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('PROJECT_VALIDATE','Project validation','Executed when a project is validated','project',141);
 insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('PROJECT_DELETE','Project deleted','Executed when a project is deleted','project',143);
 -- actions not enabled by default (no constant created for that) when we enable module agenda 
diff --git a/htdocs/install/mysql/data/llx_c_hrm_department.sql b/htdocs/install/mysql/data/llx_c_hrm_department.sql
index e6e4921f3727352246560c634cf4abf488d16c26..c4865ad9e305d5c816bf1bb71a39486841524a27 100644
--- a/htdocs/install/mysql/data/llx_c_hrm_department.sql
+++ b/htdocs/install/mysql/data/llx_c_hrm_department.sql
@@ -24,20 +24,16 @@
 --
 
 INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(1, 5,'MANAGEMENT', 'Management', 1);
-INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(2, 10,'GESTION', 'Gestion', 1);
 INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(3, 15,'TRAINING', 'Training', 1);
-INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(4, 20,'IT', 'Inform. Technology (IT)', 1);
-INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(5, 25,'MARKETING', 'Marketing', 1);
+INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(4, 20,'IT', 'Inform. Technology (IT)', 0);
+INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(5, 25,'MARKETING', 'Marketing', 0);
 INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(6, 30,'SALES', 'Sales', 1);
-INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(7, 35,'LEGAL', 'Legal', 1);
+INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(7, 35,'LEGAL', 'Legal', 0);
 INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(8, 40,'FINANCIAL', 'Financial accounting', 1);
 INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(9, 45,'HUMANRES', 'Human resources', 1);
 INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(10, 50,'PURCHASING', 'Purchasing', 1);
-INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(11, 55,'SERVICES', 'Services', 1);
-INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(12, 60,'CUSTOMSERV', 'Customer service', 1);
-INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(13, 65,'CONSULTING', 'Consulting', 1);
+INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(12, 60,'CUSTOMSERV', 'Customer service', 0);
 INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(14, 70,'LOGISTIC', 'Logistics', 1);
-INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(15, 75,'CONSTRUCT', 'Engineering/design', 1);
-INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(16, 80,'PRODUCTION', 'Manufacturing', 1);
-INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(17, 85,'QUALITY', 'Quality assurance', 1);
-INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(18, 85,'MAINT', 'Plant assurance', 1);
+INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(15, 75,'CONSTRUCT', 'Engineering/design', 0);
+INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(16, 80,'PRODUCTION', 'Production', 1);
+INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(17, 85,'QUALITY', 'Quality assurance', 0);
\ No newline at end of file
diff --git a/htdocs/install/mysql/data/llx_c_tva.sql b/htdocs/install/mysql/data/llx_c_tva.sql
index 81c72eccb8f290cedf2c265d881feb5d615577f3..3b401abd37d82bd6999c416e85ac2debaba6a4f7 100644
--- a/htdocs/install/mysql/data/llx_c_tva.sql
+++ b/htdocs/install/mysql/data/llx_c_tva.sql
@@ -96,12 +96,14 @@ insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values (80
 
 -- FRANCE (id country=1)
 insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values ( 11,  1,  '20','0','VAT standard rate (France hors DOM-TOM)',1);
-insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values ( 12,  1, '8.5','0','VAT standard rate (DOM sauf Guyane et Saint-Martin)',0);
-insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values ( 13,  1, '8.5','1','VAT standard rate (DOM sauf Guyane et Saint-Martin), non perçu par le vendeur mais récupérable par acheteur',0);
 insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values ( 14,  1, '5.5','0','VAT reduced rate (France hors DOM-TOM)',1);
 insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values ( 15,  1,   '0','0','VAT Rate 0 ou non applicable',1);
 insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values ( 16,  1, '2.1','0','VAT super-reduced rate',1);
 insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values ( 17,  1,  '10','0','VAT reduced rate',1);
+insert into llx_c_tva(fk_pays,taux,code,recuperableonly,note,active)                                                   values (1, '8.5', '85', '0','VAT standard rate (DOM sauf Guyane et Saint-Martin)',0);
+insert into llx_c_tva(fk_pays,taux,code,recuperableonly,note,active)                                                   values (1, '8.5', '85NPR', '1','VAT standard rate (DOM sauf Guyane et Saint-Martin), non perçu par le vendeur mais récupérable par acheteur',0);
+insert into llx_c_tva(fk_pays,taux,code,recuperableonly,localtax1,localtax1_type,note,active)                          values (1, '8.5', '85NPROM', '1', 2, 3, 'VAT standard rate (DOM sauf Guyane et Saint-Martin), NPR, Octroi de Mer',0);
+insert into llx_c_tva(fk_pays,taux,code,recuperableonly,localtax1,localtax1_type,localtax2,localtax2_type,note,active) values (1, '8.5', '85NPROMOMR', '1', 2, 3, 2.5, 3, 'VAT standard rate (DOM sauf Guyane et Saint-Martin), NPR, Octroi de Mer et Octroi de Mer Regional',0);
 
 -- GERMANY (id country=5)
 insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values ( 51,  5,  '19.0','0','allgemeine Ust.',1);
diff --git a/htdocs/install/mysql/migration/4.0.0-5.0.0.sql b/htdocs/install/mysql/migration/4.0.0-5.0.0.sql
index f52802dc356445e3f9573caa1f189dc35964320d..1b2cabb573d2813bad4f2489264d678550606e62 100644
--- a/htdocs/install/mysql/migration/4.0.0-5.0.0.sql
+++ b/htdocs/install/mysql/migration/4.0.0-5.0.0.sql
@@ -263,3 +263,4 @@ ALTER TABLE llx_product_price ALTER COLUMN date_price SET DEFAULT NULL;
 ALTER TABLE llx_product_price ADD COLUMN default_vat_code	varchar(10) after tva_tx;
 ALTER TABLE llx_product_fournisseur_price ADD COLUMN default_vat_code	varchar(10) after tva_tx;
 
+ALTER TABLE llx_events MODIFY COLUMN ip varchar(250);
diff --git a/htdocs/install/mysql/migration/5.0.0-6.0.0.sql b/htdocs/install/mysql/migration/5.0.0-6.0.0.sql
index c2edae8b59263e47e621e87dbcb402b85c391499..d96210dcbfed5023ca7844b190ed0441d6f192ea 100644
--- a/htdocs/install/mysql/migration/5.0.0-6.0.0.sql
+++ b/htdocs/install/mysql/migration/5.0.0-6.0.0.sql
@@ -42,10 +42,22 @@ ALTER TABLE llx_ecm_files ADD UNIQUE INDEX uk_ecm_files (filepath, filename, ent
 ALTER TABLE llx_ecm_files ADD INDEX idx_ecm_files_label (label);
 
 
+ALTER TABLE llx_holiday ADD COLUMN import_key				varchar(14);
+ALTER TABLE llx_holiday ADD COLUMN extraparams				varchar(255);	
+
+ALTER TABLE llx_expensereport ADD COLUMN import_key			varchar(14);
+ALTER TABLE llx_expensereport ADD COLUMN extraparams		varchar(255);	
+
+
 insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('PRODUCT_CREATE','Product or service created','Executed when a product or sevice is created','product',30);
 insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('PRODUCT_MODIFY','Product or service modified','Executed when a product or sevice is modified','product',30);
 insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('PRODUCT_DELETE','Product or service deleted','Executed when a product or sevice is deleted','product',30);
 
+insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('EXPENSE_REPORT_CREATE','Expense report created','Executed when an expense report is created','expense_report',201);
+insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('EXPENSE_REPORT_VALIDATE','Expense report validated','Executed when an expense report is validated','expense_report',202);
+insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('EXPENSE_REPORT_APPROVE','Expense report approved','Executed when an expense report is approved','expense_report',203);
+insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('EXPENSE_REPORT_PAYED','Expense report billed','Executed when an expense report is set as billed','expense_report',204);
+
 ALTER TABLE llx_c_email_templates ADD COLUMN content_lines text;
 
 ALTER TABLE llx_loan ADD COLUMN fk_projet integer DEFAULT NULL;
@@ -108,9 +120,21 @@ INSERT INTO llx_accounting_journal (rowid, code, label, nature, active) VALUES (
 INSERT INTO llx_accounting_journal (rowid, code, label, nature, active) VALUES (4,'OD', 'Journal des opérations diverses', 0, 1);
 INSERT INTO llx_accounting_journal (rowid, code, label, nature, active) VALUES (5,'AN', 'Journal des à-nouveaux', 9, 1);
 
+ALTER TABLE llx_accounting_journal ADD COLUMN entity integer DEFAULT 1;
+
 ALTER TABLE llx_paiementfourn ADD COLUMN model_pdf varchar(255);
 
 
+insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('EXPENSE_REPORT_CREATE','Expense report created','Executed when an expense report is created','expensereport',201);
+insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('EXPENSE_REPORT_VALIDATE','Expense report validated','Executed when an expense report is validated','expensereport',202);
+insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('EXPENSE_REPORT_APPROVE','Expense report approved','Executed when an expense report is approved','expensereport',203);
+insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('EXPENSE_REPORT_PAYED','Expense report billed','Executed when an expense report is set as billed','expensereport',204);
+
+insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('HOLIDAY_CREATE'  ,'Leave request created','Executed when a leave request is created','holiday',221);
+insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('HOLIDAY_VALIDATE','Leave request validated','Executed when a leave request is validated','holiday',222);
+insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('HOLIDAY_APPROVE' ,'Leave request approved','Executed when a leave request is approved','holiday',223);
+
+
 ALTER TABLE llx_societe_remise_except ADD COLUMN fk_invoice_supplier_line	integer;
 ALTER TABLE llx_societe_remise_except ADD COLUMN fk_invoice_supplier		integer;
 ALTER TABLE llx_societe_remise_except ADD COLUMN fk_invoice_supplier_source	integer;
@@ -119,6 +143,8 @@ ALTER TABLE llx_societe_remise_except ADD CONSTRAINT fk_soc_remise_fk_invoice_su
 ALTER TABLE llx_societe_remise_except ADD CONSTRAINT fk_societe_remise_fk_invoice_supplier        FOREIGN KEY (fk_invoice_supplier)      REFERENCES llx_facture_fourn (rowid);
 ALTER TABLE llx_societe_remise_except ADD CONSTRAINT fk_societe_remise_fk_invoice_supplier_source FOREIGN KEY (fk_invoice_supplier)      REFERENCES llx_facture_fourn (rowid);
 
+ALTER TABLE llx_facture_rec ADD COLUMN vat_src_code	varchar(10) DEFAULT '';
+
 UPDATE llx_const set value='moono-lisa' where value = 'moono' AND name = 'FCKEDITOR_SKIN';
 
 ALTER TABLE llx_product_price ADD COLUMN default_vat_code	varchar(10) after tva_tx;
@@ -182,3 +208,55 @@ ALTER TABLE llx_supplier_proposaldet ADD INDEX idx_supplier_proposaldet_fk_produ
 ALTER TABLE llx_supplier_proposaldet ADD CONSTRAINT fk_supplier_proposaldet_fk_unit FOREIGN KEY (fk_unit) REFERENCES llx_c_units (rowid);
 ALTER TABLE llx_supplier_proposaldet ADD CONSTRAINT fk_supplier_proposaldet_fk_supplier_proposal FOREIGN KEY (fk_supplier_proposal) REFERENCES llx_supplier_proposal (rowid);
 
+-- NEW inventory module
+CREATE TABLE llx_inventory 
+( 
+rowid integer NOT NULL AUTO_INCREMENT PRIMARY KEY, 
+datec datetime DEFAULT NULL,
+tms timestamp, 
+fk_warehouse integer DEFAULT 0, 
+entity integer DEFAULT 0, 
+status integer DEFAULT 0, 
+title varchar(255) NOT NULL, 
+date_inventory datetime DEFAULT NULL
+) 
+ENGINE=InnoDB;
+
+CREATE TABLE llx_inventorydet 
+( 
+rowid integer NOT NULL AUTO_INCREMENT PRIMARY KEY, 
+datec datetime DEFAULT NULL,
+tms timestamp, 
+fk_inventory integer DEFAULT 0, 
+fk_warehouse integer DEFAULT 0,
+fk_product integer DEFAULT 0,  
+batch varchar(30) DEFAULT NULL,
+qty_view double DEFAULT NULL,
+qty_stock double DEFAULT NULL,
+qty_regulated double DEFAULT NULL,
+pmp double DEFAULT 0, 
+pa double DEFAULT 0, 
+new_pmp double DEFAULT 0
+) 
+ENGINE=InnoDB;
+
+ALTER TABLE llx_inventory ADD INDEX idx_inventory_tms (tms);
+ALTER TABLE llx_inventory ADD INDEX idx_inventory_datec (datec);
+ALTER TABLE llx_inventorydet ADD INDEX idx_inventorydet_tms (tms);
+ALTER TABLE llx_inventorydet ADD INDEX idx_inventorydet_datec (datec);
+ALTER TABLE llx_inventorydet ADD INDEX idx_inventorydet_fk_inventory (fk_inventory);
+
+insert into llx_c_tva(fk_pays,taux,code,recuperableonly,note,active)                                                   values (1, '8.5', '85', '0','VAT standard rate (DOM sauf Guyane et Saint-Martin)',0);
+insert into llx_c_tva(fk_pays,taux,code,recuperableonly,note,active)                                                   values (1, '8.5', '85NPR', '1','VAT standard rate (DOM sauf Guyane et Saint-Martin), non perçu par le vendeur mais récupérable par acheteur',0);
+insert into llx_c_tva(fk_pays,taux,code,recuperableonly,localtax1,localtax1_type,note,active)                          values (1, '8.5', '85NPROM', '1', 2, 3, 'VAT standard rate (DOM sauf Guyane et Saint-Martin), NPR, Octroi de Mer',0);
+insert into llx_c_tva(fk_pays,taux,code,recuperableonly,localtax1,localtax1_type,localtax2,localtax2_type,note,active) values (1, '8.5', '85NPROMOMR', '1', 2, 3, 2.5, 3, 'VAT standard rate (DOM sauf Guyane et Saint-Martin), NPR, Octroi de Mer et Octroi de Mer Regional',0);
+
+ALTER TABLE llx_events MODIFY COLUMN ip varchar(250);
+
+UPDATE llx_accounting_journal SET nature = 1 where code = 'OD' and nature = 0;
+UPDATE llx_accounting_journal SET nature = 2 where code = 'VT' and nature = 1;
+UPDATE llx_accounting_journal SET nature = 3 where code = 'AC' and nature = 2;
+UPDATE llx_accounting_journal SET nature = 4 where (code = 'BK' or code = 'BQ') and nature = 3;
+
+
+
diff --git a/htdocs/install/mysql/migration/repair.sql b/htdocs/install/mysql/migration/repair.sql
index 32696ecf593e58518e1093f95f5accca3b919e49..6ff7356847f8abcba7aafc84d05d112b79266c0c 100755
--- a/htdocs/install/mysql/migration/repair.sql
+++ b/htdocs/install/mysql/migration/repair.sql
@@ -306,6 +306,18 @@ DELETE FROM llx_c_shipment_mode where code IN (select code from tmp_c_shipment_m
 drop table tmp_c_shipment_mode;
 
 
+-- Clean product prices
+--delete from llx_product_price where date_price between '2017-04-20 06:51:00' and '2017-04-20 06:51:05'; 
+-- Set product prices into llx_product with last price into llx_product_prices
+--update llx_product as p set 
+-- p.price = (select pp.price from llx_product_price as pp where pp.price_level = 1 and pp.fk_product = p.rowid order by pp.tms desc limit 1),
+-- p.price_ttc = (select pp.price_ttc from llx_product_price as pp where pp.price_level = 1 and pp.fk_product = p.rowid order by pp.tms desc limit 1),
+-- p.price_min = (select pp.price_min from llx_product_price as pp where pp.price_level = 1 and pp.fk_product = p.rowid order by pp.tms desc limit 1),
+-- p.price_min_ttc = (select pp.price_min_ttc from llx_product_price as pp where pp.price_level = 1 and pp.fk_product = p.rowid order by pp.tms desc limit 1),
+-- p.tva_tx = 0
+-- where price = 17.5
+
+
 -- VMYSQL4.1 SET sql_mode = 'ALLOW_INVALID_DATES';
 -- VMYSQL4.1 update llx_expensereport set date_debut = date_create where DATE(STR_TO_DATE(date_debut, '%Y-%m-%d')) IS NULL;
 -- VMYSQL4.1 SET sql_mode = 'NO_ZERO_DATE';
@@ -324,3 +336,4 @@ drop table tmp_c_shipment_mode;
 -- VMYSQL4.1 SET sql_mode = 'ALLOW_INVALID_DATES';
 -- VMYSQL4.1 update llx_expensereport_det as ed set date = (select date_debut from llx_expensereport as e where ed.fk_expensereport = e.rowid) where DATE(STR_TO_DATE(date, '%Y-%m-%d')) < '1000-00-00';
 -- VMYSQL4.1 SET sql_mode = 'NO_ZERO_DATE';
+
diff --git a/htdocs/install/mysql/tables/llx_accounting_journal.sql b/htdocs/install/mysql/tables/llx_accounting_journal.sql
index d9c6ea76e3e25b9cf0aee82deee056064461a3e6..a435de3cd8006abb04e4ae46b06615a9fc83b0db 100644
--- a/htdocs/install/mysql/tables/llx_accounting_journal.sql
+++ b/htdocs/install/mysql/tables/llx_accounting_journal.sql
@@ -20,8 +20,9 @@
 create table llx_accounting_journal
 (
   rowid             integer AUTO_INCREMENT PRIMARY KEY,
+  entity            integer DEFAULT 1,
   code       		varchar(32) NOT NULL,
   label             varchar(128) NOT NULL,
-  nature			smallint DEFAULT 0 NOT NULL,			-- type of journals (0:various operations / 1:sale / 2:purchase / 3:bank / 9: has-new)
+  nature			smallint DEFAULT 0 NOT NULL,			-- type of journals (1:various operations / 2:sale / 3:purchase / 4:bank / 9: has-new)
   active            smallint DEFAULT 0
 )ENGINE=innodb;
diff --git a/htdocs/install/mysql/tables/llx_events.sql b/htdocs/install/mysql/tables/llx_events.sql
index 29a369269c33e9d07332ad8cac5765b456e6a065..c153522cb09333d09432276924d2d14fc451b937 100644
--- a/htdocs/install/mysql/tables/llx_events.sql
+++ b/htdocs/install/mysql/tables/llx_events.sql
@@ -30,7 +30,7 @@ create table llx_events
   dateevent      datetime,                    -- date event
   fk_user        integer,                     -- id user
   description    varchar(250) NOT NULL,       -- full description of action
-  ip             varchar(32) NOT NULL,        -- ip
+  ip             varchar(250) NOT NULL,       -- ip (must contains ip v4 and v6 or dns names)
   user_agent     varchar(255) NULL,           -- user agent
   fk_object      integer                      -- id of related object
 ) ENGINE=innodb;
diff --git a/htdocs/install/mysql/tables/llx_facture_rec.sql b/htdocs/install/mysql/tables/llx_facture_rec.sql
index d0d79ef57dcea7c37201c7709f6c079fd600d02d..0e25100386b88bfb0b0f91f04b17cf8adda07440 100644
--- a/htdocs/install/mysql/tables/llx_facture_rec.sql
+++ b/htdocs/install/mysql/tables/llx_facture_rec.sql
@@ -32,6 +32,7 @@ create table llx_facture_rec
   remise_percent     real     DEFAULT 0,
   remise_absolue     real     DEFAULT 0,
   
+  vat_src_code		 varchar(10)  DEFAULT '',			-- Vat code used as source of vat fields. Not strict foreign key here.
   tva                double(24,8)     DEFAULT 0,
   localtax1			 double(24,8)     DEFAULT 0,           -- amount localtax1
   localtax2          double(24,8)     DEFAULT 0,           -- amount localtax2
diff --git a/htdocs/install/mysql/tables/llx_fichinter.sql b/htdocs/install/mysql/tables/llx_fichinter.sql
index b3e2001f9c33f129b05ac79b276646139a43e1bf..926a05a738ee20eb6b37ef7c79e399c4c4c27e3f 100644
--- a/htdocs/install/mysql/tables/llx_fichinter.sql
+++ b/htdocs/install/mysql/tables/llx_fichinter.sql
@@ -43,5 +43,4 @@ create table llx_fichinter
   note_public		text,
   model_pdf			varchar(255),
   extraparams		varchar(255)				-- for stock other parameters with json format
-  
 )ENGINE=innodb;
diff --git a/htdocs/install/mysql/tables/llx_holiday.sql b/htdocs/install/mysql/tables/llx_holiday.sql
index 2a981444df3677c0ed3246af3ffe9271a54de6bc..2091dea9541f015b3f930a01fa44f87faae6b5d3 100644
--- a/htdocs/install/mysql/tables/llx_holiday.sql
+++ b/htdocs/install/mysql/tables/llx_holiday.sql
@@ -40,6 +40,8 @@ fk_user_cancel integer DEFAULT NULL,
 detail_refuse  varchar( 250 ) DEFAULT NULL,
 note_private   text,
 note_public    text,
-tms            timestamp
+tms            timestamp,
+import_key			varchar(14),
+extraparams			varchar(255)				-- for other parameters with json format
 ) 
 ENGINE=innodb;
diff --git a/htdocs/install/mysql/tables/llx_inventory.key.sql b/htdocs/install/mysql/tables/llx_inventory.key.sql
new file mode 100644
index 0000000000000000000000000000000000000000..bf76381e1084a983f78bd098a6953ef4fa3c6d0f
--- /dev/null
+++ b/htdocs/install/mysql/tables/llx_inventory.key.sql
@@ -0,0 +1,21 @@
+-- ===================================================================
+-- Copyright (C) 2012	Laurent Destailleur	<eldy@users.sourceforge.net>
+-- Copyright (C) 2017	ATM Consulting		<support@atm-consulting.fr>
+--
+-- This program 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.
+--
+-- This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
+--
+-- ===================================================================
+
+ALTER TABLE llx_inventory ADD INDEX idx_inventory_tms (tms);
+ALTER TABLE llx_inventory ADD INDEX idx_inventory_datec (datec);
diff --git a/htdocs/install/mysql/tables/llx_inventory.sql b/htdocs/install/mysql/tables/llx_inventory.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ce1a2c9374483d8764280601ac1538b6a18f5536
--- /dev/null
+++ b/htdocs/install/mysql/tables/llx_inventory.sql
@@ -0,0 +1,36 @@
+-- ===================================================================
+-- Copyright (C) 2017   Laurent Destailleur  <eldy@users.sourceforge.net>
+-- Copyright (C) 2017	ATM Consulting		 <support@atm-consulting.fr>
+--
+-- This program 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.
+--
+-- This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
+--
+-- ===================================================================
+
+CREATE TABLE llx_inventory 
+( 
+  rowid integer NOT NULL AUTO_INCREMENT PRIMARY KEY, 
+  entity integer DEFAULT 0, 
+  ref varchar(48),
+  datec datetime DEFAULT NULL,
+  tms timestamp, 
+  fk_user_author	integer,					-- user making creation
+  fk_user_modif     integer,                   -- user making last change
+  fk_user_valid		integer,                   -- valideur de la fiche
+  fk_warehouse integer DEFAULT 0, 
+  status integer DEFAULT 0, 
+  title varchar(255) NOT NULL, 
+  date_inventory datetime DEFAULT NULL,
+  import_key               varchar(14)       	-- import key
+) 
+ENGINE=InnoDB;
diff --git a/htdocs/install/mysql/tables/llx_inventorydet.key.sql b/htdocs/install/mysql/tables/llx_inventorydet.key.sql
new file mode 100644
index 0000000000000000000000000000000000000000..3cef44ba52a1041b74fcbcaa6e47919de37983cb
--- /dev/null
+++ b/htdocs/install/mysql/tables/llx_inventorydet.key.sql
@@ -0,0 +1,22 @@
+-- ===================================================================
+-- Copyright (C) 2012	Laurent Destailleur	<eldy@users.sourceforge.net>
+-- Copyright (C) 2017	ATM Consulting		<support@atm-consulting.fr>
+--
+-- This program 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.
+--
+-- This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
+--
+-- ===================================================================
+
+ALTER TABLE llx_inventorydet ADD INDEX idx_inventorydet_tms (tms);
+ALTER TABLE llx_inventorydet ADD INDEX idx_inventorydet_datec (datec);
+ALTER TABLE llx_inventorydet ADD INDEX idx_inventorydet_fk_inventory (fk_inventory);
diff --git a/htdocs/install/mysql/tables/llx_inventorydet.sql b/htdocs/install/mysql/tables/llx_inventorydet.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ce40d03939c99de601f8e263d49063aba15aa0b3
--- /dev/null
+++ b/htdocs/install/mysql/tables/llx_inventorydet.sql
@@ -0,0 +1,36 @@
+-- ===================================================================
+-- Copyright (C) 2012      Laurent Destailleur  <eldy@users.sourceforge.net>
+-- Copyright (C) 2017	ATM Consulting		<support@atm-consulting.fr>
+--
+-- This program 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.
+--
+-- This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
+--
+-- ===================================================================
+
+CREATE TABLE llx_inventorydet 
+( 
+rowid integer NOT NULL AUTO_INCREMENT PRIMARY KEY, 
+datec datetime DEFAULT NULL,
+tms timestamp, 
+fk_inventory integer DEFAULT 0, 
+fk_warehouse integer DEFAULT 0,
+fk_product integer DEFAULT 0,  
+batch varchar(30) DEFAULT NULL,	 -- Lot or serial number
+qty_view double DEFAULT NULL, 	     -- must be filled once regulation is done
+qty_stock double DEFAULT NULL,   -- can be filled during draft edition
+qty_regulated double DEFAULT NULL,  -- must be filled once regulation is done
+pmp double DEFAULT 0, 
+pa double DEFAULT 0, 
+new_pmp double DEFAULT 0
+) 
+ENGINE=InnoDB;
diff --git a/htdocs/install/mysql/tables/llx_supplier_proposal.sql b/htdocs/install/mysql/tables/llx_supplier_proposal.sql
index 43f26ee0459eee695d398ee636817e4aff07adb2..13d9ba3a59a4408bfbb36d921512c79509dc55c3 100644
--- a/htdocs/install/mysql/tables/llx_supplier_proposal.sql
+++ b/htdocs/install/mysql/tables/llx_supplier_proposal.sql
@@ -18,7 +18,7 @@
 CREATE TABLE llx_supplier_proposal (
   rowid integer NOT NULL AUTO_INCREMENT PRIMARY KEY,
   ref varchar(30) NOT NULL,
-  entity integer NOT NULL DEFAULT '1',
+  entity integer NOT NULL DEFAULT 1,
   ref_ext varchar(255) DEFAULT NULL,
   ref_int varchar(255) DEFAULT NULL,
   fk_soc integer DEFAULT NULL,
@@ -31,11 +31,11 @@ CREATE TABLE llx_supplier_proposal (
   fk_user_modif integer DEFAULT NULL,
   fk_user_valid integer DEFAULT NULL,
   fk_user_cloture integer DEFAULT NULL,
-  fk_statut smallint NOT NULL DEFAULT '0',		-- 0=draft, 1=validated, 2=accepted, 3=refused, 4=closed
-  price double DEFAULT '0',
-  remise_percent double DEFAULT '0',
-  remise_absolue double DEFAULT '0',
-  remise double DEFAULT '0',
+  fk_statut	smallint DEFAULT 0 NOT NULL,	-- 0=draft, 1=validated, 2=accepted, 3=refused, 4=billed/closed
+  price double DEFAULT 0,
+  remise_percent double DEFAULT 0,
+  remise_absolue double DEFAULT 0,
+  remise double DEFAULT 0,
   total_ht double(24,8) DEFAULT 0,
   tva double(24,8) DEFAULT 0,
   localtax1 double(24,8) DEFAULT 0,
diff --git a/htdocs/langs/en_US/accountancy.lang b/htdocs/langs/en_US/accountancy.lang
index 57f220f943ca76627bf75b8f35137b67ddda907f..9eb4135397f8b4fd8be4789ce8410d593528bc01 100644
--- a/htdocs/langs/en_US/accountancy.lang
+++ b/htdocs/langs/en_US/accountancy.lang
@@ -32,23 +32,25 @@ ConfirmDeleteCptCategory=Are you sure you want to remove this accounting account
 AccountancyArea=Accountancy area
 AccountancyAreaDescIntro=Usage of the accountancy module is done in several step:
 AccountancyAreaDescActionOnce=The following actions are usually executed one time only, or once per year...
-AccountancyAreaDescActionOnceBis=Next steps should be done to save you time in future by suggesting you the correct default accounting account when making thee journalization (writing record in Journals and General ledger)
+AccountancyAreaDescActionOnceBis=Next steps should be done to save you time in future by suggesting you the correct default accounting account when making the journalization (writing record in Journals and General ledger)
 AccountancyAreaDescActionFreq=The following actions are usually executed every month, week or day for very large companies...
+
+AccountancyAreaDescJournalSetup=STEP %s: Create or check content of your journal list from menu %s
 AccountancyAreaDescChartModel=STEP %s: Create a model of chart of account from menu %s
 AccountancyAreaDescChart=STEP %s: Create or check content of your chart of account from menu %s
-AccountancyAreaDescVat=STEP %s: Define accounting accounts for each VAT Rates. For this you can use the menu entry %s.    
-AccountancyAreaDescExpenseReport=STEP %s: Define default accounting accounts for type of expense report. For this you can use the menu entry %s.
-AccountancyAreaDescSal=STEP %s: Define default accounting accounts for payment of salaries. For this you can use the menu entry %s.    
-AccountancyAreaDescContrib=STEP %s: Define default accounting accounts for special expences (miscellaneous taxes). For this you can use the menu entry %s.    
-AccountancyAreaDescDonation=STEP %s: Define default accounting accounts for donation. For this you can use the menu entry %s.
-AccountancyAreaDescMisc=STEP %s: Define default accounting accounts for miscellaneous transactions. For this you can use the menu entry %s.
-AccountancyAreaDescLoan=STEP %s: Define default accounting accounts for loans. For this you can use the menu entry %s. 
+
+AccountancyAreaDescVat=STEP %s: Define accounting accounts for each VAT Rates. For this, use the menu entry %s.    
+AccountancyAreaDescExpenseReport=STEP %s: Define default accounting accounts for each type of expense report. For this, use the menu entry %s.
+AccountancyAreaDescSal=STEP %s: Define default accounting accounts for payment of salaries. For this, use the menu entry %s.    
+AccountancyAreaDescContrib=STEP %s: Define default accounting accounts for special expences (miscellaneous taxes). For this, use the menu entry %s.    
+AccountancyAreaDescDonation=STEP %s: Define default accounting accounts for donation. For this, use the menu entry %s.
+AccountancyAreaDescMisc=STEP %s: Define default accounting accounts for miscellaneous transactions. For this, use the menu entry %s.
+AccountancyAreaDescLoan=STEP %s: Define default accounting accounts for loans. For this, use the menu entry %s. 
 AccountancyAreaDescBank=STEP %s: Define accounting accounts for each bank and financial accounts. For this, go on the card of each financial account. You can start from page %s.
-AccountancyAreaDescProd=STEP %s: Define accounting accounts on your products. For this you can use the menu entry %s.
+AccountancyAreaDescProd=STEP %s: Define accounting accounts on your products/services. For this, use the menu entry %s.
 
-AccountancyAreaDescCustomer=STEP %s: Check the binding between existing customer invoice lines and accounting account is done, so application will be able to journalize transactions in General Ledger in one click. Complete missing bindings. For this you can use the menu entry %s.
-AccountancyAreaDescSupplier=STEP %s: Check the binding between existing supplier invoice lines and accounting account is done, so application will be able to journalize transactions in General Ledger in one click. Complete missing bindings. For this you can use the menu entry %s.
-AccountancyAreaDescWriteRecords=STEP %s: Write transactions into the General Ledger. For this, go into each Journal, and click into button "Journalize transactions in General Ledger". 
+AccountancyAreaDescBind=STEP %s: Check the binding between existing %s lines and accounting account is done, so application will be able to journalize transactions in General Ledger in one click. Complete missing bindings. For this, use the menu entry %s.
+AccountancyAreaDescWriteRecords=STEP %s: Write transactions into the General Ledger. For this, go into menu <strong>%s</strong>, and click into button <strong>%s</strong>. 
 AccountancyAreaDescAnalyze=STEP %s: Add or edit existing transactions and generate reports and exports.
 
 AccountancyAreaDescClosePeriod=STEP %s: Close period so we can't make modification in a future.
@@ -59,6 +61,7 @@ ChangeAndLoad=Change and load
 Addanaccount=Add an accounting account
 AccountAccounting=Accounting account
 AccountAccountingShort=Account
+ShowAccoutingAccount=Show accounting account
 AccountAccountingSuggest=Accounting account suggested
 MenuDefaultAccounts=Default accounts
 MenuVatAccounts=Vat accounts
@@ -189,8 +192,8 @@ ErrorAccountancyCodeIsAlreadyUse=Error, you cannot delete this accounting accoun
 MvtNotCorrectlyBalanced=Mouvement not correctly balanced. Credit = %s. Debit = %s
 FicheVentilation=Binding card
 GeneralLedgerIsWritten=Transactions are written in the general ledger
-GeneralLedgerSomeRecordWasNotRecorded=Some of the transactions could not be recorded.
-NoNewRecordSaved=No new record saved
+GeneralLedgerSomeRecordWasNotRecorded=Some of the transactions could not be dispatched. If there is no other error message, this is probably because they were already dispatched.
+NoNewRecordSaved=No new record dispatched
 ListOfProductsWithoutAccountingAccount=List of products not bound to any accounting account
 ChangeBinding=Change the binding
 
@@ -204,11 +207,11 @@ NewAccountingJournal=New accounting journal
 ShowAccoutingJournal=Show accounting journal
 Code=Code
 Nature=Nature
-AccountingJournalTypeVariousOperation=Various operation
-AccountingJournalTypeSale=Sale
-AccountingJournalTypePurchase=Purchase
-AccountingJournalTypeBank=Bank
-AccountingJournalTypeHasNew=Has-new
+AccountingJournalType1=Various operation
+AccountingJournalType2=Sales
+AccountingJournalType3=Purchases
+AccountingJournalType4=Bank
+AccountingJournalType9=Has-new
 ErrorAccountingJournalIsAlreadyUse=This journal is already use
 
 ## Export
@@ -225,6 +228,7 @@ Modelcsv_ciel=Export towards Sage Ciel Compta or Compta Evolution
 Modelcsv_quadratus=Export towards Quadratus QuadraCompta
 Modelcsv_ebp=Export towards EBP
 Modelcsv_cogilog=Export towards Cogilog
+Modelcsv_agiris=Export towards Agiris (Test)
 ChartofaccountsId=Chart of accounts Id
 
 ## Tools - Init accounting account on product / service
diff --git a/htdocs/langs/en_US/admin.lang b/htdocs/langs/en_US/admin.lang
index 69c72fc7aad3b67fbe6a7ec44f348c50b5a06a31..5fd5cb57c8bbf72146494c7cd6c522d87e03ec21 100644
--- a/htdocs/langs/en_US/admin.lang
+++ b/htdocs/langs/en_US/admin.lang
@@ -302,6 +302,8 @@ CurrentVersion=Dolibarr current version
 CallUpdatePage=Go to the page that updates the database structure and data: %s.
 LastStableVersion=Latest stable version
 LastActivationDate=Latest activation date
+LastActivationAuthor=Latest activation author
+LastActivationIP=Latest activation IP
 UpdateServerOffline=Update server offline
 WithCounter=Manage a counter
 GenericMaskCodes=You may enter any numbering mask. In this mask, the following tags could be used:<br><b>{000000}</b> corresponds to a number which will be incremented on each %s. Enter as many zeros as the desired length of the counter. The counter will be completed by zeros from the left in order to have as many zeros as the mask. <br><b>{000000+000}</b> same as previous but an offset corresponding to the number to the right of the + sign is applied starting on first %s. <br><b>{000000@x}</b> same as previous but the counter is reset to zero when month x is reached (x between 1 and 12, or 0 to use the early months of fiscal year defined in your configuration, or 99 to reset to zero every month). If this option is used and x is 2 or higher, then sequence {yy}{mm} or {yyyy}{mm} is also required. <br><b>{dd}</b> day (01 to 31).<br><b>{mm}</b> month (01 to 12).<br><b>{yy}</b>, <b>{yyyy}</b> or <b>{y}</b> year over 2, 4 or 1 numbers. <br>
@@ -431,9 +433,13 @@ TheKeyIsTheNameOfHtmlField=This is the name of the HTML field. This need to have
 PageUrlForDefaultValues=You must enter here the relative url of the page. If you include parameters in URL, the default values will be effective if all parameters are set to same value. Examples:
 PageUrlForDefaultValuesCreate=<br>For form to create a new thirdparty, it is <strong>%s</strong>
 PageUrlForDefaultValuesList=<br>For page that list thirdparties, it is <strong>%s</strong>
+EnableDefaultValues=Enable usage of personalized default values
 GoIntoTranslationMenuToChangeThis=A translation has been found for the key with this code, so to change this value, you must edit it fom Home-Setup-translation.
-WarningSettingSortOrder=Warning, setting a default sort order may result in a technical error when going on the list page if field is an unknown field. If you experience such an error, come back to this page to remove the default sort order to retreive default behavior. 
+WarningSettingSortOrder=Warning, setting a default sort order may result in a technical error when going on the list page if field is an unknown field. If you experience such an error, come back to this page to remove the default sort order and restore default behavior. 
 Field=Field
+ProductDocumentTemplates=Document templates to generate product document
+FreeLegalTextOnExpenseReports=Free legal text on expense reports
+WatermarkOnDraftExpenseReports=Watermark on draft expense reports
 # Modules
 Module0Name=Users & groups
 Module0Desc=Users / Employees and Groups management
@@ -856,6 +862,7 @@ DictionaryOrderMethods=Ordering methods
 DictionarySource=Origin of proposals/orders
 DictionaryAccountancyCategory=Accounting account groups
 DictionaryAccountancysystem=Models for chart of accounts
+DictionaryAccountancyJournal=Accounting journals
 DictionaryEMailTemplates=Emails templates
 DictionaryUnits=Units
 DictionaryProspectStatus=Prospection status
@@ -1094,7 +1101,7 @@ WarningAtLeastKeyOrTranslationRequired=A search criteria is required at least fo
 NewTranslationStringToShow=New translation string to show
 OriginalValueWas=The original translation is overwritten. Original value was:<br><br>%s
 TransKeyWithoutOriginalValue=You forced a new translation for the translation key '<strong>%s</strong>' that does not exists in any language files
-TotalNumberOfActivatedModules=Total number of activated feature modules: <b>%s</b> / <b>%s</b>
+TotalNumberOfActivatedModules=Activated feature/modules: <b>%s</b> / <b>%s</b>
 YouMustEnableOneModule=You must at least enable 1 module
 ClassNotFoundIntoPathWarning=Class %s not found into PHP path
 YesInSummer=Yes in summer
@@ -1151,6 +1158,7 @@ WebCalUrlForVCalExport=An export link to <b>%s</b> format is available at follow
 BillsSetup=Invoices module setup
 BillsNumberingModule=Invoices and credit notes numbering model
 BillsPDFModules=Invoice documents models
+PaymentsPDFModules=Payment documents models
 CreditNote=Credit note
 CreditNotes=Credit notes
 ForceInvoiceDate=Force invoice date to validation date
@@ -1347,9 +1355,10 @@ CacheByClient=Cache by browser
 CompressionOfResources=Compression of HTTP responses
 TestNotPossibleWithCurrentBrowsers=Such an automatic detection is not possible with current browsers 
 DefaultValuesDesc=You can define/force here the default value you want to get when your create a new record, and/or defaut filters or sort order when your list record. 
-DefaultCreateForm=Create forms
-DefaultSearchFilters=Search filters
-DefaultSortOrder=Sort orders
+DefaultCreateForm=Default values for new objects
+DefaultSearchFilters=Default search filters
+DefaultSortOrder=Default sort orders
+DefaultFocus=Default focus fields
 ##### Products #####
 ProductSetup=Products module setup
 ServiceSetup=Services module setup
@@ -1501,7 +1510,7 @@ AGENDA_NOTIFICATION=Enable event notification on user browsers when event date i
 AGENDA_NOTIFICATION_SOUND=Enable sound notification
 ##### Clicktodial #####
 ClickToDialSetup=Click To Dial module setup
-ClickToDialUrlDesc=Url called when a click on phone picto is done.  In URL, you can use tags<br><b>__PHONETO__</b> that will be replaced with the phone number of person to call<br><b>__PHONEFROM__</b> that will be replaced with phone number of calling person (yours)<br><b>__LOGIN__</b> that will be replaced with your clicktodial login (defined on your user card)<br><b>__PASS__</b> that will be replaced with your clicktodial password (defined on your user card).
+ClickToDialUrlDesc=Url called when a click on phone picto is done.  In URL, you can use tags<br><b>__PHONETO__</b> that will be replaced with the phone number of person to call<br><b>__PHONEFROM__</b> that will be replaced with phone number of calling person (yours)<br><b>__LOGIN__</b> that will be replaced with clicktodial login (defined on user card)<br><b>__PASS__</b> that will be replaced with clicktodial password (defined on user card).
 ClickToDialDesc=This module allows to make phone numbers clickable. A click on this icon will call make your phone to call the phone number. This can be used to call a call center system from Dolibarr that can call the phone number on a SIP system for example.
 ClickToDialUseTelLink=Use just a link "tel:" on phone numbers
 ClickToDialUseTelLinkDesc=Use this method if your users have a softphone or a software interface installed on same computer than the browser, and called when you click on a link in your browser that start with "tel:". If you need a full server solution (no need of local software installation), you must set this to "No" and fill next field.
diff --git a/htdocs/langs/en_US/bills.lang b/htdocs/langs/en_US/bills.lang
index 7432f0e2412302030d8c6da3c720562b4f370941..189ef5c1fe2ae2f07152683500cbb323049561f6 100644
--- a/htdocs/langs/en_US/bills.lang
+++ b/htdocs/langs/en_US/bills.lang
@@ -447,7 +447,7 @@ CantRemovePaymentWithOneInvoicePaid=Can't remove payment since there is at least
 ExpectedToPay=Expected payment
 CantRemoveConciliatedPayment=Can't remove conciliated payment
 PayedByThisPayment=Paid by this payment
-ClosePaidInvoicesAutomatically=Classify "Paid" all standard, situation or replacement invoices entirely paid.
+ClosePaidInvoicesAutomatically=Classify "Paid" all standard, down payment or replacement invoices entirely paid.
 ClosePaidCreditNotesAutomatically=Classify "Paid" all credit notes entirely paid back.
 ClosePaidContributionsAutomatically=Classify "Paid" all social or fiscal contributions entirely paid.
 AllCompletelyPayedInvoiceWillBeClosed=All invoice with no remain to pay will be automatically closed to status "Paid".
diff --git a/htdocs/langs/en_US/cron.lang b/htdocs/langs/en_US/cron.lang
index 01b69b3b83916c061298a27149e5e79287b6ce83..76b1a92a3652354638db064e8cbe31d4636c20bc 100644
--- a/htdocs/langs/en_US/cron.lang
+++ b/htdocs/langs/en_US/cron.lang
@@ -58,11 +58,11 @@ CronStatusInactiveBtn=Disable
 CronTaskInactive=This job is disabled
 CronId=Id
 CronClassFile=Classes (filename.class.php)
-CronModuleHelp=Name of Dolibarr module directory (also work with external Dolibarr module). <BR> For exemple to call the fetch method of Dolibarr Product object /htdocs/<u>product</u>/class/product.class.php, the value of module is <i>product</i>
-CronClassFileHelp=The file name to load. <BR> For exemple to call the fetch method of Dolibarr Product object /htdocs/product/class/<u>product.class.php</u>, the value of class file name is <i>product.class.php</i>
-CronObjectHelp=The object name to load. <BR> For exemple to call the fetch method of Dolibarr Product object /htdocs/product/class/product.class.php, the value of class file name is <i>Product</i>
-CronMethodHelp=The object method to launch. <BR> For exemple to call the fetch method of Dolibarr Product object /htdocs/product/class/product.class.php, the value of method is  is <i>fecth</i>
-CronArgsHelp=The method arguments. <BR> For exemple to call the fetch method of Dolibarr Product object /htdocs/product/class/product.class.php, the value of paramters can be <i>0, ProductRef</i>
+CronModuleHelp=Name of Dolibarr module directory (also work with external Dolibarr module). <BR> For exemple to call the fetch method of Dolibarr Product object /htdocs/<u>product</u>/class/product.class.php, the value for module is <i>product</i>
+CronClassFileHelp=The file name to load. <BR> For exemple to call the fetch method of Dolibarr Product object /htdocs/product/class/<u>product.class.php</u>, the value for class file name is <i>product.class.php</i>
+CronObjectHelp=The object name to load. <BR> For exemple to call the fetch method of Dolibarr Product object /htdocs/product/class/product.class.php, the value for class file name is <i>Product</i>
+CronMethodHelp=The object method to launch. <BR> For exemple to call the fetch method of Dolibarr Product object /htdocs/product/class/product.class.php, the value for method is <i>fecth</i>
+CronArgsHelp=The method arguments. <BR> For exemple to call the fetch method of Dolibarr Product object /htdocs/product/class/product.class.php, the value for paramters can be <i>0, ProductRef</i>
 CronCommandHelp=The system command line to execute.
 CronCreateJob=Create new Scheduled Job
 CronFrom=From
diff --git a/htdocs/langs/en_US/errors.lang b/htdocs/langs/en_US/errors.lang
index 8aeb8dab65cd8bb981026c51fe95948d9dd92344..4f700109c3346d7a587710801489a33d9434de92 100644
--- a/htdocs/langs/en_US/errors.lang
+++ b/htdocs/langs/en_US/errors.lang
@@ -177,7 +177,8 @@ ErrorStockIsNotEnoughToAddProductOnShipment=Stock is not enough for product %s t
 ErrorStockIsNotEnoughToAddProductOnProposal=Stock is not enough for product %s to add it into a new proposal.
 ErrorFailedToLoadLoginFileForMode=Failed to get the login key for mode '%s'.
 ErrorModuleNotFound=File of module was not found.
-ErrorFieldAccountNotDefinedForBankLine=Value for Accounting account not defined for source bank line %s
+ErrorFieldAccountNotDefinedForBankLine=Value for Accounting account not defined for source line id %s (%s)
+ErrorFieldAccountNotDefinedForInvoiceLine=Value for Accounting account not defined for invoice id %s (%s)
 ErrorBankStatementNameMustFollowRegex=Error, bank statement name must follow the following syntax rule %s
 ErrorPhpMailDelivery=Check that you don't use a too high number of recipients and that your email content is not similar to a Spam. Ask also your administrator to check firewall and server logs files for a more complete information.
 ErrorUserNotAssignedToTask=User must be assigned to task to be able to enter time consumed.
diff --git a/htdocs/langs/en_US/main.lang b/htdocs/langs/en_US/main.lang
index 1a3eea413df99cc13fd7cacef1e0e99601a6db96..79927cc888ccfdb47859bf66e101bbc1914a2dc4 100644
--- a/htdocs/langs/en_US/main.lang
+++ b/htdocs/langs/en_US/main.lang
@@ -172,7 +172,7 @@ SearchOf=Search
 Valid=Valid
 Approve=Approve
 Disapprove=Disapprove
-ReOpen=Re-Opened
+ReOpen=Re-Open
 Upload=Send file
 ToLink=Link
 Select=Select
@@ -611,7 +611,8 @@ PartialWoman=Partial
 TotalWoman=Total
 NeverReceived=Never received
 Canceled=Canceled
-YouCanChangeValuesForThisListFromDictionarySetup=You can change values for this list from menu setup - dictionary
+YouCanChangeValuesForThisListFromDictionarySetup=You can change values for this list from menu Setup - Dictionaries
+YouCanChangeValuesForThisListFrom=You can change values for this list from menu %s
 YouCanSetDefaultValueInModuleSetup=You can set the default value used when creating a new record into module setup
 Color=Color
 Documents=Linked files
@@ -647,6 +648,7 @@ FreeLineOfType=Free entry of type
 CloneMainAttributes=Clone object with its main attributes
 PDFMerge=PDF Merge
 Merge=Merge
+DocumentModelStandardPDF=Standard PDF template
 PrintContentArea=Show page to print main content area
 MenuManager=Menu manager
 WarningYouAreInMaintenanceMode=Warning, you are in a maintenance mode, so only login <b>%s</b> is allowed to use application at the moment.
@@ -766,6 +768,9 @@ Download=Download
 ActualizeCurrency=Update currency rate
 Fiscalyear=Fiscal year
 ModuleBuilder=Module Builder
+SetMultiCurrencyCode=Set currency
+BulkActions=Bulk actions
+ClickToShowHelp=Click to show tooltip help
 # Week day
 Monday=Monday
 Tuesday=Tuesday
@@ -822,6 +827,4 @@ SearchIntoInterventions=Interventions
 SearchIntoContracts=Contracts
 SearchIntoCustomerShipments=Customer shipments
 SearchIntoExpenseReports=Expense reports
-SearchIntoLeaves=Leaves
-SetMultiCurrencyCode=Set currency
-BulkActions=Bulk actions
\ No newline at end of file
+SearchIntoLeaves=Leaves
\ No newline at end of file
diff --git a/htdocs/langs/en_US/other.lang b/htdocs/langs/en_US/other.lang
index ab937ff3bab97a2c0c1dec457a938677bae17547..a37927566e32aa7b59c6792dc41b37bea478e13f 100644
--- a/htdocs/langs/en_US/other.lang
+++ b/htdocs/langs/en_US/other.lang
@@ -61,7 +61,7 @@ PredefinedMailTestHtml=This is a <b>test</b> mail (the word test must be in bold
 PredefinedMailContentSendInvoice=__CONTACTCIVNAME__\n\nYou will find here the invoice __REF__\n\n__PERSONALIZED__Sincerely\n\n__SIGNATURE__
 PredefinedMailContentSendInvoiceReminder=__CONTACTCIVNAME__\n\nWe would like to warn you that the invoice  __REF__ seems to not being payed. So this is the invoice in attachment again, as a reminder.\n\n__PERSONALIZED__Sincerely\n\n__SIGNATURE__
 PredefinedMailContentSendProposal=__CONTACTCIVNAME__\n\nYou will find here the commercial proposal __PROPREF__\n\n__PERSONALIZED__Sincerely\n\n__SIGNATURE__
-PredefinedMailContentSendSupplierProposal=__CONTACTCIVNAME__\n\nYou will find here the price request __ASKREF__\n\n__PERSONALIZED__Sincerely\n\n__SIGNATURE__
+PredefinedMailContentSendSupplierProposal=__CONTACTCIVNAME__\n\nYou will find here the price request __REF__\n\n__PERSONALIZED__Sincerely\n\n__SIGNATURE__
 PredefinedMailContentSendOrder=__CONTACTCIVNAME__\n\nYou will find here the order __ORDERREF__\n\n__PERSONALIZED__Sincerely\n\n__SIGNATURE__
 PredefinedMailContentSendSupplierOrder=__CONTACTCIVNAME__\n\nYou will find here our order __ORDERREF__\n\n__PERSONALIZED__Sincerely\n\n__SIGNATURE__
 PredefinedMailContentSendSupplierInvoice=__CONTACTCIVNAME__\n\nYou will find here the invoice __REF__\n\n__PERSONALIZED__Sincerely\n\n__SIGNATURE__
diff --git a/htdocs/langs/en_US/resource.lang b/htdocs/langs/en_US/resource.lang
index f95121db351995a219e53c37cf11cb5547b35398..5a907f6ba23d1f9ddfda650133ea871b2fcfb9e1 100644
--- a/htdocs/langs/en_US/resource.lang
+++ b/htdocs/langs/en_US/resource.lang
@@ -29,3 +29,8 @@ RessourceSuccessfullyDeleted=Resource successfully deleted
 DictionaryResourceType=Type of resources
 
 SelectResource=Select resource
+
+IdResource=Id resource
+AssetNumber=Serial number
+ResourceTypeCode=Resource type code
+ImportDataset_resource_1=Resources
diff --git a/htdocs/langs/en_US/sendings.lang b/htdocs/langs/en_US/sendings.lang
index ac180cb5fe6357b6afdd3b473015ae70b236107b..fcd28cc9f568302810ceb17aa89636ee48aaf686 100644
--- a/htdocs/langs/en_US/sendings.lang
+++ b/htdocs/langs/en_US/sendings.lang
@@ -37,7 +37,6 @@ SendingSheet=Shipment sheet
 ConfirmDeleteSending=Are you sure you want to delete this shipment?
 ConfirmValidateSending=Are you sure you want to validate this shipment with reference <b>%s</b>?
 ConfirmCancelSending=Are you sure you want to cancel this shipment?
-DocumentModelSimple=Simple document model
 DocumentModelMerou=Merou A5 model
 WarningNoQtyLeftToSend=Warning, no products waiting to be shipped.
 StatsOnShipmentsOnlyValidated=Statistics conducted on shipments only validated. Date used is date of validation of shipment (planed delivery date is not always known).
diff --git a/htdocs/langs/en_US/stocks.lang b/htdocs/langs/en_US/stocks.lang
index aeb83b925bde7c3a67529c1d8362eb8e52bf223d..9c9f82f6efb12abc247aed180d93dc251b3e4c06 100644
--- a/htdocs/langs/en_US/stocks.lang
+++ b/htdocs/langs/en_US/stocks.lang
@@ -146,3 +146,50 @@ ProductStockWarehouseUpdated=Stock limit for alert and desired optimal stock cor
 ProductStockWarehouseDeleted=Stock limit for alert and desired optimal stock correctly deleted
 AddNewProductStockWarehouse=Set new limit for alert and desired optimal stock
 AddStockLocationLine=Decrease quantity then click to add another warehouse for this product
+InventoryDate=Inventory date
+NewInventory=New inventory
+inventorySetup = Inventory Setup
+inventoryCreatePermission=Create new inventory
+inventoryReadPermission=View inventories
+inventoryWritePermission=Update inventories
+inventoryValidatePermission=Validate inventory
+inventoryTitle=Inventory
+inventoryListTitle=Inventories
+inventoryListEmpty=No inventory in progress
+inventoryCreateDelete=Create/Delete inventory
+inventoryCreate=Create new
+inventoryEdit=Edit
+inventoryValidate=Validated
+inventoryDraft=Running
+inventorySelectWarehouse=Warehouse choice
+inventoryConfirmCreate=Create
+inventoryOfWarehouse=Inventory for warehouse : %s
+inventoryErrorQtyAdd=Error : one quantity is leaser than zero
+inventoryMvtStock=By inventory
+inventoryWarningProductAlreadyExists=This product is already into list
+SelectCategory=Category filter
+SelectFournisseur=Supplier filter
+inventoryOnDate=Inventory 
+INVENTORY_DISABLE_VIRTUAL=Allow to not destock child product from a kit on inventory
+INVENTORY_USE_MIN_PA_IF_NO_LAST_PA=Use the buy price if no last buy price can be found
+INVENTORY_USE_INVENTORY_DATE_FROM_DATEMVT=Stock mouvment have date of inventory
+inventoryChangePMPPermission=Allow to change PMP value for a product
+ColumnNewPMP=New unit PMP
+OnlyProdsInStock=Do not add product without stock
+TheoricalQty=Theorique qty
+TheoricalValue=Theorique qty
+LastPA=Last BP
+CurrentPA=Curent BP
+RealQty=Real Qty
+RealValue=Real Value
+RegulatedQty=Regulated Qty
+AddInventoryProduct=Add product to inventory
+AddProduct=Add
+ApplyPMP=Apply PMP
+FlushInventory=Flush inventory
+ConfirmFlushInventory=Do you confirm this action ?
+InventoryFlushed=Inventory flushed
+ExitEditMode=Exit edition
+inventoryDeleteLine=Delete line
+RegulateStock=Regulate Stock
+ListInventory=List
diff --git a/htdocs/main.inc.php b/htdocs/main.inc.php
index 72a5f39e02c9e79096d99c07eb8660ca764b43b9..ab92df9ca12a671b85e03ed209b34ca2f15ceaef 100644
--- a/htdocs/main.inc.php
+++ b/htdocs/main.inc.php
@@ -1271,9 +1271,10 @@ function top_htmlhead($head, $title='', $disablejs=0, $disablehead=0, $arrayofjs
             {
                 $enablebrowsernotif=false;
                 if (! empty($conf->agenda->enabled) && ! empty($conf->global->AGENDA_NOTIFICATION)) $enablebrowsernotif=true;
+                if ($conf->browser->layout == 'phone') $enablebrowsernotif=false;
                 if ($enablebrowsernotif)
                 {
-                    print '<!-- Includes JS of Dolibarr -->'."\n";
+                    print '<!-- Includes JS of Dolibarr (brwoser layout = '.$conf->browser->layout.')-->'."\n";
                     print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/lib_notification.js.php?version='.urlencode(DOL_VERSION).($ext?'&amp;'.$ext:'').'"></script>'."\n";
                 }
             }
@@ -1865,7 +1866,7 @@ if (! function_exists("llxFooter"))
         dol_htmloutput_events();
 
         // Core error message
-        if (defined("MAIN_CORE_ERROR") && constant("MAIN_CORE_ERROR") == 1)
+        if (! empty($conf->global->MAIN_CORE_ERROR))
         {
             // Ajax version
             if ($conf->use_javascript_ajax)
diff --git a/htdocs/margin/productMargins.php b/htdocs/margin/productMargins.php
index efcb35b802f8fca3f21546991acaf1bd689df45e..f5e84dd5c04c5b5ff1ad1cb52c1dcf2d569830a2 100644
--- a/htdocs/margin/productMargins.php
+++ b/htdocs/margin/productMargins.php
@@ -204,6 +204,7 @@ if ($result)
 	print '<br>';
 	print_barre_liste($langs->trans("MarginDetails"),$page,$_SERVER["PHP_SELF"],"&amp;id=".$id,$sortfield,$sortorder,'',$num,$num,'');
 
+	//var_dump($conf->global->MARGIN_TYPE);
 	if ($conf->global->MARGIN_TYPE == "1")
 	    $labelcostprice=$langs->trans('BuyingPrice');
 	else   // value is 'costprice' or 'pmp'
@@ -285,7 +286,7 @@ if ($result)
 				}
 				else
 				{
-				    print $langs->trans("NotPredefinedProducts");
+				    print img_object('', 'product').' '.$langs->trans("NotPredefinedProducts");
 				}
 				print "</td>\n";
 				//print "<td>".$product_static->getNomUrl(1)."</td>\n";
diff --git a/htdocs/modulebuilder/skeletons/skeleton_card.php b/htdocs/modulebuilder/skeletons/skeleton_card.php
index f0a9dd23c2641b74c7be73e55cbc6b3bcf5b2663..42fce48e2cbc3a5a4deded58e829ba0a256ac2bf 100644
--- a/htdocs/modulebuilder/skeletons/skeleton_card.php
+++ b/htdocs/modulebuilder/skeletons/skeleton_card.php
@@ -109,9 +109,9 @@ if (empty($reshook))
 	}
 	
 	// Action to add record
-	if ($action == 'add')
+	if ($action == 'add' && ! empty($user->rights->mymodule->create))
 	{
-		if (GETPOST('cancel'))
+		if ($cancel)
 		{
 			$urltogo=$backtopage?$backtopage:dol_buildpath('/mymodule/list.php',1);
 			header("Location: ".$urltogo);
@@ -154,7 +154,7 @@ if (empty($reshook))
 	}
 
 	// Action to update record
-	if ($action == 'update')
+	if ($action == 'update' && ! empty($user->rights->mymodule->create))
 	{
 		$error=0;
 
@@ -189,7 +189,7 @@ if (empty($reshook))
 	}
 
 	// Action to delete
-	if ($action == 'confirm_delete')
+	if ($action == 'confirm_delete' && ! empty($user->rights->mymodule->delete))
 	{
 		$result=$object->delete($user);
 		if ($result > 0)
@@ -216,10 +216,10 @@ if (empty($reshook))
 * Put here all code to build page
 ****************************************************/
 
-llxHeader('','MyPageName','');
-
 $form=new Form($db);
 
+llxHeader('','MyPageName','');
+
 
 // Put here content of your page
 
diff --git a/htdocs/modulebuilder/skeletons/skeleton_class.class.php b/htdocs/modulebuilder/skeletons/skeleton_class.class.php
index 01b48c35f75d2c41a535adb49270372218c50e4a..6805a6970436546eef1cf84f72aa94cde9b64d79 100644
--- a/htdocs/modulebuilder/skeletons/skeleton_class.class.php
+++ b/htdocs/modulebuilder/skeletons/skeleton_class.class.php
@@ -1,5 +1,5 @@
 <?php
-/* Copyright (C) 2007-2012  Laurent Destailleur <eldy@users.sourceforge.net>
+/* Copyright (C) 2007-2017  Laurent Destailleur <eldy@users.sourceforge.net>
  * Copyright (C) 2014-2016  Juanjo Menent       <jmenent@2byte.es>
  * Copyright (C) 2015       Florian Henry       <florian.henry@open-concept.pro>
  * Copyright (C) 2015       Raphaël Doursenaud  <rdoursenaud@gpcsolutions.fr>
@@ -20,10 +20,9 @@
  */
 
 /**
- * \file    dev/skeletons/skeleton_class.class.php
- * \ingroup mymodule othermodule1 othermodule2
- * \brief   This file is an example for a CRUD class file (Create/Read/Update/Delete)
- *          Put some comments here
+ * \file        modulebuilder/skeletons/skeleton_class.class.php
+ * \ingroup     mymodule othermodule1 othermodule2
+ * \brief       This file is an example for a CRUD class file (Create/Read/Update/Delete)
  */
 
 // Put here all includes required by your class file
@@ -34,26 +33,27 @@ require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php';
 /**
  * Class Skeleton_Class
  *
- * Put here description of your class
- *
- * @see CommonObject
+ * Put here description of your class.
  */
 class Skeleton_Class extends CommonObject
 {
 	/**
-	 * @var string Id to identify managed objects
+	 * @var string Id to identify managed object
 	 */
 	public $element = 'skeleton';
 	/**
 	 * @var string Name of table without prefix where object is stored
 	 */
 	public $table_element = 'skeleton';
-
-	/**
-	 * @var Skeleton_ClassLine[] Lines
-	 */
-	public $lines = array();
-
+    /**
+     * @var array Array with all fields and their property
+     */
+	public $picto = 'generic';
+    /**
+     * @var array Array with all fields and their property
+     */
+	public $fields;
+	
 	/**
 	 * @var mixed Sample property 1
 	 */
@@ -62,8 +62,21 @@ class Skeleton_Class extends CommonObject
 	 * @var mixed Sample property 2
 	 */
 	public $prop2;
+	
 	//...
-
+	
+	protected $ismultientitymanaged = 1;	// 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
+	
+	public $table_element_line = 'skeletondet';
+    public $class_element_line = 'SkeletonLine';
+    public $fk_element = 'fk_skeleton';
+    /**
+	 * @var Skeleton_ClassLine[] Lines
+	 */
+	public $lines = array();
+	
+	
+	
 	/**
 	 * Constructor
 	 *
@@ -289,10 +302,10 @@ class Skeleton_Class extends CommonObject
 	 */
 	public function update(User $user, $notrigger = false)
 	{
-		$error = 0;
-
 		dol_syslog(__METHOD__, LOG_DEBUG);
 
+		$error = 0;
+		
 		// Clean parameters
 		if (isset($this->prop1)) {
 			$this->prop1 = trim($this->prop1);
diff --git a/htdocs/product/admin/product.php b/htdocs/product/admin/product.php
index 3582f8b25b67d79bc282b9b8eedae1834ed1be61..5183eeb338282ddae61219880fc9184db5d34248 100644
--- a/htdocs/product/admin/product.php
+++ b/htdocs/product/admin/product.php
@@ -512,10 +512,7 @@ foreach ($dirmodels as $reldir)
 			                    }
 					    		$htmltooltip.='<br><br><u>'.$langs->trans("FeaturesSupported").':</u>';
 					    		$htmltooltip.='<br>'.$langs->trans("Logo").': '.yn($module->option_logo,1,1);
-					    		$htmltooltip.='<br>'.$langs->trans("PaymentMode").': '.yn($module->option_modereg,1,1);
-					    		$htmltooltip.='<br>'.$langs->trans("PaymentConditions").': '.yn($module->option_condreg,1,1);
 					    		$htmltooltip.='<br>'.$langs->trans("MultiLanguage").': '.yn($module->option_multilang,1,1);
-					    		$htmltooltip.='<br>'.$langs->trans("WatermarkOnDraftOrders").': '.yn($module->option_draft_watermark,1,1);
 
 
 	                            print '<td align="center">';
diff --git a/htdocs/product/admin/product_tools.php b/htdocs/product/admin/product_tools.php
index 671bb9779a7652db5227a5df7664fd31fd767db2..58d66f3a2c5d416c4d537ea7efbbf2f599c96906 100644
--- a/htdocs/product/admin/product_tools.php
+++ b/htdocs/product/admin/product_tools.php
@@ -42,8 +42,6 @@ $oldvatrate=GETPOST('oldvatrate');
 $newvatrate=GETPOST('newvatrate');
 //$price_base_type=GETPOST('price_base_type');
 
-$objectstatic = new Product($db);
-$objectstatic2 = new ProductFournisseur($db);
 
 
 /*
@@ -87,6 +85,7 @@ if ($action == 'convert')
 				{
 					$obj = $db->fetch_object($resql);
 
+					$objectstatic = new Product($db);          // Object init must be into loop to avoid to get value of previous step
 					$ret=$objectstatic->fetch($obj->rowid);
 					if ($ret > 0)
 					{
@@ -150,7 +149,8 @@ if ($action == 'convert')
 						if ($ret < 0 || $retm < 0) $error++;
 						else $nbrecordsmodified++;
 					}
-
+                    unset($objectstatic);
+                    
 					$i++;
 				}
 			}
@@ -176,6 +176,7 @@ if ($action == 'convert')
 			{
 				$obj = $db->fetch_object($resql);
 
+                $objectstatic2 = new ProductFournisseur($db);          // Object init must be into loop to avoid to get value of previous step
 				$ret=$objectstatic2->fetch_product_fournisseur_price($obj->rowid);
 				if ($ret > 0)
 				{
@@ -207,6 +208,8 @@ if ($action == 'convert')
 					if ($ret < 0 || $retm < 0) $error++;
 					else $nbrecordsmodified++;
 				}
+				unset($objectstatic2);
+				
 				$i++;
 			}
 		}
diff --git a/htdocs/product/card.php b/htdocs/product/card.php
index 536bcece10fadb2723c37eb17ae5a307d2ed44a5..71f7cd8e7f631a0bfee1447c3975eb91bad92cb9 100644
--- a/htdocs/product/card.php
+++ b/htdocs/product/card.php
@@ -1801,60 +1801,61 @@ if (($action == 'clone' && (empty($conf->use_javascript_ajax) || ! empty($conf->
 /* Barre d'action                                                             */
 /*                                                                            */
 /* ************************************************************************** */
-
-print "\n".'<div class="tabsAction">'."\n";
-
-$parameters=array();
-$reshook=$hookmanager->executeHooks('addMoreActionsButtons',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
-if (empty($reshook))
+if ($action != 'create' && $action != 'edit')
 {
-    if (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->creer ) || 
-       ($object->type == Product::TYPE_SERVICE && $user->rights->service->creer))
+    print "\n".'<div class="tabsAction">'."\n";
+    
+    $parameters=array();
+    $reshook=$hookmanager->executeHooks('addMoreActionsButtons',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
+    if (empty($reshook))
     {
-        if (! isset($object->no_button_edit) || $object->no_button_edit <> 1) print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=edit&amp;id='.$object->id.'">'.$langs->trans("Modify").'</a></div>';
-
-        if (! isset($object->no_button_copy) || $object->no_button_copy <> 1)
+        if (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->creer ) || 
+           ($object->type == Product::TYPE_SERVICE && $user->rights->service->creer))
         {
-            if (! empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile))
+            if (! isset($object->no_button_edit) || $object->no_button_edit <> 1) print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=edit&amp;id='.$object->id.'">'.$langs->trans("Modify").'</a></div>';
+    
+            if (! isset($object->no_button_copy) || $object->no_button_copy <> 1)
             {
-                print '<div class="inline-block divButAction"><span id="action-clone" class="butAction">'.$langs->trans('ToClone').'</span></div>'."\n";
-            }
-            else
-			{
-                print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=clone&amp;id='.$object->id.'">'.$langs->trans("ToClone").'</a></div>';
+                if (! empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile))
+                {
+                    print '<div class="inline-block divButAction"><span id="action-clone" class="butAction">'.$langs->trans('ToClone').'</span></div>'."\n";
+                }
+                else
+    			{
+                    print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=clone&amp;id='.$object->id.'">'.$langs->trans("ToClone").'</a></div>';
+                }
             }
         }
-    }
-    $object_is_used = $object->isObjectUsed($object->id);
-
-    if (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->supprimer)
-    || ($object->type == Product::TYPE_SERVICE && $user->rights->service->supprimer))
-    {
-        if (empty($object_is_used) && (! isset($object->no_button_delete) || $object->no_button_delete <> 1))
+        $object_is_used = $object->isObjectUsed($object->id);
+    
+        if (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->supprimer)
+        || ($object->type == Product::TYPE_SERVICE && $user->rights->service->supprimer))
         {
-            if (! empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile))
+            if (empty($object_is_used) && (! isset($object->no_button_delete) || $object->no_button_delete <> 1))
             {
-                print '<div class="inline-block divButAction"><span id="action-delete" class="butActionDelete">'.$langs->trans('Delete').'</span></div>'."\n";
+                if (! empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile))
+                {
+                    print '<div class="inline-block divButAction"><span id="action-delete" class="butActionDelete">'.$langs->trans('Delete').'</span></div>'."\n";
+                }
+                else
+    			{
+                    print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?action=delete&amp;id='.$object->id.'">'.$langs->trans("Delete").'</a></div>';
+                }
             }
             else
-			{
-                print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?action=delete&amp;id='.$object->id.'">'.$langs->trans("Delete").'</a></div>';
+    		{
+                print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="'.$langs->trans("ProductIsUsed").'">'.$langs->trans("Delete").'</a></div>';
             }
         }
         else
-		{
-            print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="'.$langs->trans("ProductIsUsed").'">'.$langs->trans("Delete").'</a></div>';
+    	{
+            print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("Delete").'</a></div>';
         }
     }
-    else
-	{
-        print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("Delete").'</a></div>';
-    }
+    
+    print "\n</div>\n";
 }
 
-print "\n</div>\n";
-
-
 /*
  * All the "Add to" areas
  */
@@ -1974,7 +1975,7 @@ if (! empty($conf->global->PRODUCT_ADD_FORM_ADD_TO) && $object->id && ($action =
  * Documents generes
  */
 
-if ($action != 'edit' && $action != 'delete')
+if ($action != 'create' && $action != 'edit' && $action != 'delete')
 {
     print '<div class="fichecenter"><div class="fichehalfleft">';
     print '<a name="builddoc"></a>'; // ancre
diff --git a/htdocs/product/class/product.class.php b/htdocs/product/class/product.class.php
index e25ad18636901c0e1a12f15cc8fb8920afab46d6..76a609e0a44d8eebbdc69c23fba640ac26cf4232 100644
--- a/htdocs/product/class/product.class.php
+++ b/htdocs/product/class/product.class.php
@@ -4367,14 +4367,31 @@ class Product extends CommonObject
         $this->id=0;
         $this->ref = 'PRODUCT_SPEC';
         $this->label = 'PRODUCT SPECIMEN';
-        $this->description = 'PRODUCT SPECIMEN '.dol_print_date($now,'dayhourlog');
+        $this->description = 'This is description of this product specimen that was created the '.dol_print_date($now,'dayhourlog').'.';
         $this->specimen=1;
         $this->country_id=1;
         $this->tosell=1;
         $this->tobuy=1;
 		$this->tobatch=0;
         $this->note='This is a comment (private)';
-
+        $this->date_creation = $now;
+        $this->date_modification = $now;
+        
+        $this->weight = 4;
+        $this->weight_unit = 1;
+
+        $this->length = 5;
+        $this->length_unit = 1;
+        $this->width = 6;
+        $this->width_unit = 0;
+        $this->height = null;
+        $this->height_unit = null;
+        
+        $this->surface = 30;
+        $this->surface_unit = 0;
+        $this->volume = 300;
+        $this->volume_unit = 0;
+        
         $this->barcode=-1;	// Create barcode automatically
     }
 
diff --git a/htdocs/product/inventory/ajax/ajax.inventory.php b/htdocs/product/inventory/ajax/ajax.inventory.php
new file mode 100644
index 0000000000000000000000000000000000000000..4884d7ab06599ae8d995848ab60ebb0235e01ed1
--- /dev/null
+++ b/htdocs/product/inventory/ajax/ajax.inventory.php
@@ -0,0 +1,51 @@
+<?php
+
+    require '../../../main.inc.php';
+    require_once DOL_DOCUMENT_ROOT.'/product/inventory/class/inventory.class.php';
+  
+    $get = GETPOST('get');
+    $put = GETPOST('put');
+    
+    switch ($put)
+    {
+        case 'qty':
+        	if (empty($user->rights->stock->creer)) { echo -1; exit; }
+            
+            $fk_det_inventory = GETPOST('fk_det_inventory');
+            
+            $det = new Inventorydet($db);
+            if( $det->fetch( $fk_det_inventory))
+            {
+                $det->qty_view+=GETPOST('qty');
+                $res = $det->update($user);
+                
+                echo $det->qty_view;
+            }
+            else
+            {
+                echo -2;
+            }            
+           
+            break;
+			
+        case 'pmp':
+        	if (empty($user->rights->stock->creer) || empty($user->rights->stock->changePMP)) { echo -1; exit; }
+            
+            $fk_det_inventory = GETPOST('fk_det_inventory');
+            
+            $det = new Inventorydet($db);
+            if( $det->fetch( $fk_det_inventory))
+            {
+                $det->new_pmp=price2num(GETPOST('pmp'));
+                $det->update($user);
+                
+                echo $det->new_pmp;
+            }
+            else
+            {
+                echo -2;
+            }            
+            
+            break;
+    }
+ 
diff --git a/htdocs/product/inventory/card.php b/htdocs/product/inventory/card.php
new file mode 100644
index 0000000000000000000000000000000000000000..e47891a6d089fd0f8557247b08d5fa5f87d2f7a7
--- /dev/null
+++ b/htdocs/product/inventory/card.php
@@ -0,0 +1,687 @@
+<?php
+/* Copyright (C) 2016		ATM Consulting			<support@atm-consulting.fr>
+ *
+ * This program 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.
+ *
+ * This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/**
+ *	\file       htdocs/inventory/card.php
+ *	\ingroup    product
+ *	\brief      File of class to manage inventory
+ */
+ 
+require_once '../../main.inc.php';
+
+require_once DOL_DOCUMENT_ROOT.'/product/inventory/listview.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
+include_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
+require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
+require_once DOL_DOCUMENT_ROOT.'/product/inventory/class/inventory.class.php';
+require_once DOL_DOCUMENT_ROOT.'/product/inventory/lib/inventory.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
+
+
+$langs->load('stock');
+$langs->load('inventory');
+
+$id=GETPOST('id', 'int');
+$ref=GETPOST('ref', 'alpha');
+$action=(GETPOST('action','alpha') ? GETPOST('action','alpha') : 'view');
+$cancel=GETPOST('cancel');
+$confirm=GETPOST('confirm','alpha');
+$socid=GETPOST('socid','int');
+if (! empty($user->societe_id)) $socid=$user->societe_id;
+
+if (empty($action) && empty($id) && empty($ref)) $action='view';
+
+// Protection if external user
+if ($user->societe_id > 0)
+{
+    //accessforbidden();
+}
+$result = restrictedArea($user, 'stock', $id);
+
+
+$object = new Inventory($db);
+$extrafields = new ExtraFields($db);
+
+// fetch optionals attributes and labels
+$extralabels = $extrafields->fetch_name_optionals_label($object->table_element);
+
+// Load object
+include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php';  // Must be include, not include_once  // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals
+
+// Initialize technical object to manage hooks of modules. Note that conf->hooks_modules contains array array
+$hookmanager->initHooks(array('inventorycard'));
+
+
+
+/*
+ * Actions
+ */
+
+$parameters=array('id'=>$id, 'ref'=>$ref, 'objcanvas'=>$objcanvas);
+$reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
+if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+
+if (empty($reshook))
+{
+    if ($cancel)
+    {
+        if ($action != 'addlink')
+        {
+            $urltogo=$backtopage?$backtopage:dol_buildpath('/product/inventory/list.php',1);
+            header("Location: ".$urltogo);
+            exit;
+        }
+        if ($id > 0 || ! empty($ref)) $ret = $object->fetch($id,$ref);
+        $action='';
+    }
+    
+    if ($action == 'confirmCreate')
+    {
+		if (empty($user->rights->stock->creer)) accessforbidden();
+	
+		if ($cancel)
+		{
+		    $urltogo=$backtopage?$backtopage:dol_buildpath('/product/inventory/list.php',1);
+		    header("Location: ".$urltogo);
+		    exit;
+		}
+		
+		$error=0;
+		
+		$object->setValues($_POST);
+		
+        $fk_inventory = $object->create($user);
+		if ($fk_inventory>0)
+		{
+        	$fk_category = (int) GETPOST('fk_category');
+        	$fk_supplier = (int) GETPOST('fk_supplier');
+        	$fk_warehouse = (int) GETPOST('fk_warehouse');
+        	$only_prods_in_stock = (int) GETPOST('OnlyProdsInStock');
+        	
+        	$object->addProductsFor($fk_warehouse,$fk_category,$fk_supplier,$only_prods_in_stock);
+        	$object->update($user);
+        	
+        	header('Location: '.dol_buildpath('/product/inventory/card.php?id='.$object->id.'&action=edit', 1));
+            exit;        	
+        }
+        else
+        {
+        	setEventMessage($object->error,'errors');
+        	header('Location: '.dol_buildpath('/product/inventory/card.php?action=create', 1));
+        	exit;
+        }
+    }
+    
+    switch($action) {
+    	case 'save':
+    		if (!$user->rights->stock->creer) accessforbidden();
+    		
+    		
+    		$id = GETPOST('id');
+    		
+    		$object = new Inventory($db);
+    		$object->fetch($id);
+    		
+    		$object->setValues($_REQUEST);
+    		
+    		if ($object->errors)
+    		{
+    			setEventMessage($object->errors, 'errors');
+    			$action = 'edit';
+    		}
+    		else 
+    		{
+    			$object->udpate($user);
+    			header('Location: '.dol_buildpath('/product/inventory/card.php?id='.$object->getId().'&action=view', 1));
+    			exit;
+    		}
+    		
+    		break;
+    		
+    	case 'confirm_regulate':
+    		if (!$user->rights->stock->creer) accessforbidden();
+    		$id = GETPOST('id');
+    		
+    		$object = new Inventory($db);
+    		$object->fetch($id);
+            
+            if($object->status == 0) {
+                $object->status = 1;
+                $object->update($user);
+                
+                $action='view';
+            }
+            else {
+               $action='view';
+            }
+            
+    		break;
+    		
+    	case 'confirm_changePMP':
+    		
+    		$id = GETPOST('id');
+    		
+    		$object = new Inventory($db);
+    		$object->fetch( $id );
+    		
+    		$object->changePMP($user);
+    		
+    		$action='view';
+    		
+    		break;
+    		
+    	case 'add_line':
+    		if (!$user->rights->stock->creer) accessforbidden();
+    		
+    		$id = GETPOST('id');
+    		$fk_warehouse = GETPOST('fk_warehouse');
+    		
+    		$object = new Inventory($db);
+    		$object->fetch( $id );
+    		
+    		$fk_product = GETPOST('fk_product');
+    		if ($fk_product>0)
+    		{
+    			$product = new Product($db);
+    			if($product->fetch($fk_product)<=0 || $product->type != 0) {
+    				setEventMessage($langs->trans('ThisIsNotAProduct'),'errors');
+    			}
+    			else{
+    				
+    				//Check product not already exists
+    				$alreadyExists = false;
+    				if(!empty($object->Inventorydet)) {
+    					foreach ($object->Inventorydet as $invdet)
+    					{
+    						if ($invdet->fk_product == $product->id
+    							&& $invdet->fk_warehouse == $fk_warehouse)
+    						{
+    							$alreadyExists = true;
+    							break;
+    						}
+    					}
+    				}
+    				if (!$alreadyExists)
+    				{
+    				    if($object->addProduct($product->id, $fk_warehouse)) {
+    				    	setEventMessage($langs->trans('ProductAdded'));
+    				    }
+    				}
+    				else
+    				{
+    					setEventMessage($langs->trans('inventoryWarningProductAlreadyExists'), 'warnings');
+    				}
+    				
+    			}
+    			
+    			$object->update($user);
+    			$object->sortDet();
+    		}
+    		
+    		$action='edit';
+    		
+    		break;
+    		
+    	case 'confirm_delete_line':
+    		if (!$user->rights->stock->creer) accessforbidden();
+    		
+    		
+    		//Cette action devrais se faire uniquement si le status de l'inventaire est à 0 mais aucune vérif
+    		$rowid = GETPOST('rowid');
+    		$objectdet = new Inventorydet($db);
+    		if($objectdet->fetch($rowid)>0) {
+    			$objectdet->delete($user);
+    			setEventMessage("ProductDeletedFromInventory");
+    		}
+    		$id = GETPOST('id');
+    		$object = new Inventory($db);
+    		$object->fetch( $id);
+    		
+    		$action='edit';
+    		
+    		break;
+        case 'confirm_flush':
+            if (!$user->rights->stock->creer) accessforbidden();
+            
+            
+            $id = GETPOST('id');
+            
+            $object = new Inventory($db);
+            $object->fetch($id);
+            
+            $object->deleteAllLine($user);
+            
+            setEventMessage($langs->trans('InventoryFlushed'));
+            
+            $action='edit';
+            
+            break;
+    	case 'confirm_delete':
+    		if (!$user->rights->stock->supprimer) accessforbidden();
+            
+    		$id = GETPOST('id');
+    		
+    		$object = new Inventory($db);
+    		$object->fetch($id);
+    		
+    		$object->delete($user);
+    		
+    		setEventMessage($langs->trans('InventoryDeleted'));
+    		
+    		header('Location: '.dol_buildpath('/inventory/list.php', 1));
+    		exit;
+    		
+    		break;
+    	/*case 'exportCSV':
+    		
+    		$id = GETPOST('id');
+    		
+    		$object = new Inventory($db);
+    		$object->fetch($id);
+    		
+    		_exportCSV($object);
+    		
+    		exit;
+    		break;
+    		*/
+    }
+}
+
+
+/*
+ * Views
+ */
+
+$form=new Form($db);
+
+llxHeader('',$langs->trans('Inventory'),'','');
+	
+if ($action == 'create')
+{
+    if (empty($user->rights->stock->creer)) accessforbidden();
+
+    print load_fiche_titre($langs->trans("NewInventory"));
+	
+    echo '<form name="confirmCreate" action="'.$_SERVER['PHP_SELF'].'" method="post" />';
+	echo '<input type="hidden" name="action" value="confirmCreate" />';
+	
+	dol_fiche_head();
+	
+    $formproduct = new FormProduct($db);
+    
+    ?>
+    <table class="border" width="100%" >
+        <tr>
+            <td><?php echo $langs->trans('Title') ?></td>
+            <td><input type="text" name="title" value="" size="50" /></td> 
+        </tr>
+        <tr>
+            <td><?php echo $langs->trans('Date') ?></td>
+            <td><?php echo $form->select_date(time(),'date_inventory'); ?></td> 
+        </tr>
+        
+        <tr>
+            <td><?php echo $langs->trans('inventorySelectWarehouse') ?></td>
+            <td><?php echo $formproduct->selectWarehouses('', 'fk_warehouse') ?></td> 
+        </tr>
+        
+        <tr>
+            <td><?php echo $langs->trans('SelectCategory') ?></td>
+            <td><?php echo $form->select_all_categories(0,'', 'fk_category') ?></td> 
+        </tr>
+        <tr>
+            <td><?php echo $langs->trans('SelectFournisseur') ?></td>
+            <td><?php echo $form->select_thirdparty('','fk_supplier','s.fournisseur = 1') ?></td> 
+        </tr>
+        <tr>
+            <td><?php echo $langs->trans('OnlyProdsInStock') ?></td>
+            <td><input type="checkbox" name="OnlyProdsInStock" value="1"></td> 
+        </tr>
+        
+    </table>
+    <?php
+    
+    dol_fiche_end();
+    
+    print '<div class="center">';
+    print '<input type="submit" class="button" name="create" value="'.$langs->trans('inventoryConfirmCreate').'" />';
+    print ' &nbsp; &nbsp; ';
+    print '<input type="submit" class="button" name="cancel" value="'.$langs->trans('Cancel').'" />';
+    print '</div>';
+    
+	echo '</form>';
+	
+}
+
+if ($action == 'view' || $action == 'edit' ||  empty($action))
+{
+    $object = new Inventory($db);
+    $result = $object->fetch($id);
+    if ($result < 0) dol_print_error($db, $object->error, $object->errors);
+    
+    $warehouse = new Entrepot($db);
+    $warehouse->fetch($object->fk_warehouse);
+    
+    
+    
+	if($action == 'changePMP')
+	{
+		print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ApplyNewPMP'), $langs->trans('ConfirmApplyNewPMP', $object->getTitle()), 'confirm_changePMP', array(),'no',1);
+	}
+	else if($action == 'flush')
+	{
+		print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id,$langs->trans('FlushInventory'),$langs->trans('ConfirmFlushInventory',$object->getTitle()),'confirm_flush',array(),'no',1);
+	}
+	else if($action == 'delete')
+	{
+		print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id,$langs->trans('Delete'),$langs->trans('ConfirmDelete',$object->getTitle()),'confirm_delete',array(),'no',1);
+	}
+	else if($action == 'delete_line')
+	{
+		print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&rowid='.GETPOST('rowid'),$langs->trans('DeleteLine'),$langs->trans('ConfirmDeleteLine',$object->getTitle()),'confirm_delete_line',array(),'no',1);
+	}
+	else if($action == 'regulate')
+	{
+		print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id,$langs->trans('RegulateStock'),$langs->trans('ConfirmRegulateStock',$object->getTitle()),'confirm_regulate',array(),'no',1);
+	}
+	
+	print dol_get_fiche_head(inventoryPrepareHead($object, $langs->trans('inventoryOfWarehouse', $warehouse->libelle), empty($action) ? '': '&action='.$action));
+	
+	$lines = array();
+	card_line($object, $lines, $action);
+	
+	print $langs->trans('Ref')." ".$object->ref.'<br>';
+	print $langs->trans('Date')." ".$object->getDate('date_inventory').'<br><br>';
+	
+	$objectTPL = array(
+	    'id'=> $object->id
+	    ,'ref'=> $object->ref
+		,'date_cre' => $object->getDate('date_cre', 'd/m/Y')
+		,'date_maj' => $object->getDate('date_maj', 'd/m/Y H:i')
+		,'fk_warehouse' => $object->fk_warehouse
+		,'status' => $object->status
+		,'entity' => $object->entity
+		,'amount' => price( round($object->amount,2) )
+		,'amount_actual'=>price (round($object->amount_actual,2))
+		
+	);
+	
+	$can_validate = !empty($user->rights->stock->validate);
+	$view_url = dol_buildpath('/product/inventory/card.php', 1);
+	
+	$view = array(
+		'mode' => $action
+		,'url' => dol_buildpath('/product/inventory/card.php', 1)
+		,'can_validate' => (int) $user->rights->stock->validate
+		,'is_already_validate' => (int) $object->status
+		,'token'=>$_SESSION['newtoken']
+	);
+	
+	include './tpl/inventory.tpl.php';
+}
+
+// End of page
+llxFooter();
+$db->close();
+
+
+
+function card_line(&$inventory, &$lines, $mode)
+{
+	global $db,$langs,$user,$conf;
+	$inventory->amount_actual = 0;
+	
+	$TCacheEntrepot = array();
+
+	foreach ($inventory->Inventorydet as $k => $Inventorydet)
+	{
+        $product = & $Inventorydet->product;
+		$stock = $Inventorydet->qty_stock;
+	
+        $pmp = $Inventorydet->pmp;
+		$pmp_actual = $pmp * $stock;
+		$inventory->amount_actual+=$pmp_actual;
+
+        $last_pa = $Inventorydet->pa;
+		$current_pa = $Inventorydet->current_pa;
+        
+		$e = new Entrepot($db);
+		if(!empty($TCacheEntrepot[$Inventorydet->fk_warehouse])) $e = $TCacheEntrepot[$Inventorydet->fk_warehouse];
+		elseif($e->fetch($Inventorydet->fk_warehouse) > 0) $TCacheEntrepot[$e->id] = $e;
+		
+		$qtytoadd = GETPOST('qty_to_add', 'array');
+		$qty = (float) $qtytoadd[$k];
+		
+		$lines[]=array(
+			'produit' => $product->getNomUrl(1).'&nbsp;-&nbsp;'.$product->label,
+			'entrepot'=>$e->getNomUrl(1),
+			'barcode' => $product->barcode,
+			'qty' =>($mode == 'edit' ? '<input type="text" name="qty_to_add['.$k.']" value="'.$qty.'" size="8" style="text-align:center;" /> <a id="a_save_qty_'.$k.'" href="javascript:save_qty('.$k.')">'.img_picto($langs->trans('Add'), 'edit_add').'</a>' : '' ),
+			'qty_view' => ($Inventorydet->qty_view ? $Inventorydet->qty_view : 0),
+			'qty_stock' => $stock,
+			'qty_regulated' => ($Inventorydet->qty_regulated ? $Inventorydet->qty_regulated : 0),
+			'action' => ($user->rights->stock->write && $mode=='edit' ? '<a href="'.dol_buildpath('/product/inventory/card.php?id='.$inventory->id.'&action=delete_line&rowid='.$Inventorydet->id, 1).'">'.img_picto($langs->trans('inventoryDeleteLine'), 'delete').'</a>' : ''),
+			'pmp_stock'=>round($pmp_actual,2),
+            'pmp_actual'=> round($pmp * $Inventorydet->qty_view,2),
+			'pmp_new'=>(!empty($user->rights->stock->changePMP) && $mode == 'edit' ? '<input type="text" name="new_pmp['.$k.']" value="'.$Inventorydet->new_pmp.'" size="8" style="text-align:right;" /> <a id="a_save_new_pmp_'.$k.'" href="javascript:save_pmp('.$k.')">'.img_picto($langs->trans('Save'), 'bt-save.png@inventory').'</a>' :  price($Inventorydet->new_pmp)),
+            'pa_stock'=>round($last_pa * $stock,2),
+            'pa_actual'=>round($last_pa * $Inventorydet->qty_view,2),
+			'current_pa_stock'=>round($current_pa * $stock,2),
+			'current_pa_actual'=>round($current_pa * $Inventorydet->qty_view,2),
+            'k'=>$k,
+            'id'=>$Inventorydet->id
+		);
+	}
+
+}
+
+
+/*
+function _exportCSV(&$inventory) 
+{
+	global $conf;
+	
+	header('Content-Type: application/octet-stream');
+    header('Content-disposition: attachment; filename=inventory-'. $inventory->getId().'-'.date('Ymd-His').'.csv');
+    header('Pragma: no-cache');
+    header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
+    header('Expires: 0');
+	
+	echo 'Ref;Label;barcode;qty theorique;PMP;dernier PA;';
+	if(!empty($conf->global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)) echo 'PA courant;';
+	echo 'qty réelle;PMP;dernier PA;';
+	if(!empty($conf->global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)) echo 'PA courant;';
+	echo 'qty regulée;'."\r\n";
+	
+	foreach ($inventory->Inventorydet as $k => $Inventorydet)
+	{
+		$product = & $Inventorydet->product;
+		$stock = $Inventorydet->qty_stock;
+	
+        $pmp = $Inventorydet->pmp;
+		$pmp_actual = $pmp * $stock;
+		$inventory->amount_actual+=$pmp_actual;
+
+        $last_pa = $Inventorydet->pa;
+        $current_pa = $Inventorydet->current_pa;
+		
+		if(!empty($conf->global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)) {
+			$row=array(
+				'produit' => $product->ref
+				,'label'=>$product->label
+				,'barcode' => $product->barcode
+				,'qty_stock' => $stock
+				,'pmp_stock'=>round($pmp_actual,2)
+	            ,'pa_stock'=>round($last_pa * $stock,2)
+				,'current_pa_stock'=>round($current_pa * $stock,2)
+			    ,'qty_view' => $Inventorydet->qty_view ? $Inventorydet->qty_view : 0
+				,'pmp_actual'=>round($pmp * $Inventorydet->qty_view,2)
+	            ,'pa_actual'=>round($last_pa * $Inventorydet->qty_view,2)
+	        	,'current_pa_actual'=>round($current_pa * $Inventorydet->qty_view,2)    
+				,'qty_regulated' => $Inventorydet->qty_regulated ? $Inventorydet->qty_regulated : 0
+				
+			);
+			
+		}
+		else{
+			$row=array(
+				'produit' => $product->ref
+				,'label'=>$product->label
+				,'barcode' => $product->barcode
+				,'qty_stock' => $stock
+				,'pmp_stock'=>round($pmp_actual,2)
+	            ,'pa_stock'=>round($last_pa * $stock,2)
+	            ,'qty_view' => $Inventorydet->qty_view ? $Inventorydet->qty_view : 0
+				,'pmp_actual'=>round($pmp * $Inventorydet->qty_view,2)
+	            ,'pa_actual'=>round($last_pa * $Inventorydet->qty_view,2)
+	            
+				,'qty_regulated' => $Inventorydet->qty_regulated ? $Inventorydet->qty_regulated : 0
+				
+		);
+			
+		}
+		
+		
+		echo '"'.implode('";"', $row).'"'."\r\n";
+		
+	}
+	
+	exit;
+}
+*/
+
+function _footerList($view,$total_pmp,$total_pmp_actual,$total_pa,$total_pa_actual, $total_current_pa,$total_current_pa_actual) 
+{
+	global $conf,$user,$langs;
+	
+	    if ($view['can_validate'] == 1) { ?>
+        <tr style="background-color:#dedede;">
+            <th colspan="3">&nbsp;</th>
+            <?php if (! empty($conf->barcode->enabled)) { ?>
+					<th align="center">&nbsp;</td>
+			<?php } ?>
+            <th align="right"><?php echo price($total_pmp) ?></th>
+            <th align="right"><?php echo price($total_pa) ?></th>
+            <?php
+	                 if(!empty($conf->global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)){
+	              		echo '<th align="right">'.price($total_current_pa).'</th>';   	
+					 }
+			?>
+            <th>&nbsp;</th>
+            <th align="right"><?php echo price($total_pmp_actual) ?></th>
+            <?php
+            if(!empty($user->rights->stock->changePMP)) {
+               	echo '<th>&nbsp;</th>';	
+			}
+			?>
+            <th align="right"><?php echo price($total_pa_actual) ?></th>
+            <?php
+	                 if(!empty($conf->global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)){
+	              		echo '<th align="right">'.price($total_current_pa_actual).'</th>';   	
+					 }
+			?>
+
+            <th>&nbsp;</th>
+            <?php if ($view['is_already_validate'] != 1) { ?>
+            <th>&nbsp;</th>
+            <?php } ?>
+        </tr>
+        <?php } 
+}
+
+
+function _headerList($view) 
+{
+	global $conf,$user,$langs;
+	
+	?>
+			<tr style="background-color:#dedede;">
+				<th class="titlefield"><?php echo $langs->trans('Product'); ?></th>
+				<th><?php echo $langs->trans('Warehouse'); ?></th>
+				<?php if (! empty($conf->barcode->enabled)) { ?>
+					<th align="center"><?php echo $langs->trans('Barcode'); ?></th>
+				<?php } ?>
+				<?php if ($view['can_validate'] == 1) { ?>
+					<th align="center" width="20%"><?php echo $langs->trans('TheoricalQty'); ?></th>
+					<?php
+	                 if(!empty($conf->global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)){
+	              		echo '<th align="center" width="20%" colspan="3">'.$langs->trans('TheoricalValue').'</th>';   	
+					 }
+					 else {
+					 	echo '<th align="center" width="20%" colspan="2">'.$langs->trans('TheoricalValue').'</th>';
+					 }
+					 
+					?>
+					
+				<?php } ?>
+				    <th align="center" width="20%"><?php echo $langs->trans('RealQty'); ?></th>
+				<?php if ($view['can_validate'] == 1) { ?>
+				    
+				    <?php
+				    
+				     $colspan = 2;
+					 if(!empty($conf->global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)) $colspan++;
+				     if(!empty($conf->global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)) $colspan++;
+					
+	                 echo '<th align="center" width="20%" colspan="'.$colspan.'">'.$langs->trans('RealValue').'</th>';
+					 
+					?>
+						
+					<th align="center" width="15%"><?php echo $langs->trans('RegulatedQty'); ?></th>
+				<?php } ?>
+				<?php if ($view['is_already_validate'] != 1) { ?>
+					<th align="center" width="5%">#</th>
+				<?php } ?>
+				
+			</tr>
+			<?php if ($view['can_validate'] == 1) { ?>
+	    	<tr style="background-color:#dedede;">
+	    	    <th colspan="<?php echo empty($conf->barcode->enabled) ? 3 : 4;  ?>">&nbsp;</th>
+	    	    <th><?php echo $langs->trans('PMP'); ?></th>
+	    	    <th><?php echo $langs->trans('LastPA'); ?></th>
+	    	    <?php
+	                 if(!empty($conf->global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)){
+	              		echo '<th>'.$langs->trans('CurrentPA').'</th>';   	
+					 }
+					 
+				?>
+	    	    <th>&nbsp;</th>
+	    	    <th><?php echo $langs->trans('PMP'); ?></th>
+	    	    <?php
+	    	    if(!empty($user->rights->stock->changePMP)) {
+	    	    	echo '<th rel="newPMP">'.$langs->trans('ColumnNewPMP').'</th>';
+	    	    }
+	    	    ?>
+	            <th><?php echo $langs->trans('LastPA'); ?></th>
+	            <?php
+	                 if(!empty($conf->global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)){
+	              		echo '<th>'.$langs->trans('CurrentPA').'</th>';   	
+					 }
+					 
+				?>
+	            <th>&nbsp;</th>
+	            <?php if ($view['is_already_validate'] != 1) { ?>
+	            <th>&nbsp;</th>
+	            <?php } ?>
+	    	</tr>
+	    	<?php 
+	} 
+	
+}
diff --git a/htdocs/product/inventory/class/inventory.class.php b/htdocs/product/inventory/class/inventory.class.php
new file mode 100644
index 0000000000000000000000000000000000000000..8cb1f56eb9d2f4f7c93f12fb424822c11ce043fb
--- /dev/null
+++ b/htdocs/product/inventory/class/inventory.class.php
@@ -0,0 +1,713 @@
+<?php
+/* Copyright (C) 2016		ATM Consulting			<support@atm-consulting.fr>
+ *
+ * This program 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.
+ *
+ * This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/**
+ *	\file       htdocs/inventory/class/product.class.php
+ *	\ingroup    product
+ *	\brief      File of class to manage predefined products stock
+ */
+ 
+require_once DOL_DOCUMENT_ROOT.'/core/class/coreobject.class.php';
+require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
+
+/**
+ *	Class to manage inventories
+ */
+class Inventory extends CoreObject
+{
+	public $element='inventory';
+	public $table_element='inventory';
+	public $fk_element='fk_inventory';
+	protected $childtables=array('inventorydet');    // To test if we can delete object
+	protected $isnolinkedbythird = 1;     // No field fk_soc
+	protected $ismultientitymanaged = 1;	// 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
+	
+	/**
+	 * Warehouse Id
+	 * @var int
+	 */
+	public $fk_warehouse;
+	/**
+	 * Entity Id
+	 * @var int
+	 */
+	public $entity;
+	
+	/**
+	 * Status
+	 * @var int
+	 */
+	public $status;
+	/**
+	 * Inventory Date
+	 * @var date
+	 */
+	public $date_inventory;
+	/**
+	 * Inventory Title
+	 * @var string
+	 */
+	public $title;
+
+    /**
+     * Attribute object linked with database
+     * @var array
+     */
+	protected $fields=array(
+		'fk_warehouse'=>array('type'=>'integer','index'=>true)
+	    ,'ref'=>array('type'=>'string','index'=>true)
+		,'entity'=>array('type'=>'integer','index'=>true)
+		,'status'=>array('type'=>'integer','index'=>true)
+		,'date_inventory'=>array('type'=>'date')
+		,'title'=>array('type'=>'string')
+	);
+
+    /**
+     *  Constructor
+     *
+     *  @param      DoliDB		$db      Database handler
+     */
+	public function __construct(DoliDB &$db) 
+	{
+		global $conf;
+
+        parent::__construct($db);
+		parent::init();
+		
+       	$this->status = 0;
+		$this->entity = $conf->entity;
+		$this->errors = array();
+		$this->amount = 0;
+	}
+
+    /**
+     * Function to sort children object
+     */
+	public function sortDet()
+	{
+		if(!empty($this->Inventorydet))	usort($this->Inventorydet, array('Inventory', 'customSort'));
+	}
+
+    /**
+     *	Get object and children from database
+     *
+     *	@param      int			$id       		Id of object to load
+     * 	@param		bool		$loadChild		used to load children from database
+     *	@return     int         				>0 if OK, <0 if KO, 0 if not found
+     */
+	public function fetch($id, $loadChild = true)
+	{
+        if(!$loadChild) $this->withChild = false;
+        
+		$res = parent::fetch($id, $loadChild);
+
+		if ($res > 0)
+		{
+			$this->sortDet();
+			$this->amount = 0;
+			if(!empty($this->Inventorydet ))
+			{
+				foreach($this->Inventorydet as &$det)
+				{
+					$this->amount += $det->qty_view * $det->pmp;
+				}
+			}
+		}
+				
+		return $res;
+	}
+
+    /**
+     * Custom function call by usort
+     *
+     * @param   Inventorydet    $objA   first Inventorydet object
+     * @param   Inventorydet    $objB   second Inventorydet object
+     * @return                          int
+     */
+	private function customSort(&$objA, &$objB)
+	{
+		$r = strcmp(strtoupper(trim($objA->product->ref)), strtoupper(trim($objB->product->ref)));
+		
+		if ($r < 0) $r = -1;
+		elseif ($r > 0) $r = 1;
+		else $r = 0;
+		
+		return $r;
+	}
+
+    /**
+     * @param   User    $user   user object
+     * @return                  int
+     */
+    public function changePMP(User &$user)
+    {
+        $error = 0;
+        $this->db->begin();
+
+		if(!empty($this->Inventorydet))
+		{
+			foreach ($this->Inventorydet as $k => &$Inventorydet)
+			{
+				if($Inventorydet->new_pmp>0)
+				{
+					$Inventorydet->pmp = $Inventorydet->new_pmp; 
+					$Inventorydet->new_pmp = 0;
+				
+					$res = $this->db->query('UPDATE '.MAIN_DB_PREFIX.'product as p SET pmp = '.$Inventorydet->pmp.' WHERE rowid = '.$Inventorydet->fk_product );
+					if (!$res)
+                    {
+                        $error++;
+                        $this->error = $this->db->lasterror();
+                        $this->errors[] = $this->db->lasterror();
+                    }
+				}
+			}
+		}
+		
+		$res = parent::update($user);
+        if (!$res)
+        {
+            $error++;
+            $this->error = $this->db->lasterror();
+            $this->errors[] = $this->db->lasterror();
+        }
+
+
+        if (!$error)
+        {
+            $this->db->commit();
+            return 1;
+        }
+        else
+        {
+            $this->db->rollback();
+            return -1;
+        }
+	}
+
+    /**
+     * Function to update object or create or delete if needed
+     *
+     * @param   User    $user   user object
+     * @return                  < 0 if ko, > 0 if ok
+     */
+	public function update(User &$user)
+	{
+		$error = 0;
+		$this->db->begin();
+
+        // if we valid the inventory we save the stock at the same time
+		if ($this->status)
+		{
+		    $res = $this->regulate();
+            if ($res < 0)
+            {
+                $error++;
+                $this->error = $this->db->lasterror();
+                $this->errors[] = $this->db->lasterror();
+            }
+		}
+
+        $res = parent::update($user);
+        if (!$res)
+        {
+            $error++;
+            $this->error = $this->db->lasterror();
+            $this->errors[] = $this->db->lasterror();
+        }
+
+		if (!$error)
+        {
+            $this->db->commit();
+            return $this->id;
+        }
+        else
+        {
+            $this->db->rollback();
+            return -1;
+        }
+	}
+
+    /**
+     * Function to update current object
+     *
+     * @param   array   $Tab    Array of values
+     * @return                  int
+     */
+	public function setValues(&$Tab)
+	{
+		global $langs;
+		
+		if (isset($Tab['qty_to_add']))
+		{
+			foreach ($Tab['qty_to_add'] as $k => $qty)
+			{
+				$qty = (float) price2num($qty);
+				
+				if ($qty < 0) 
+				{
+					$this->errors[] = $langs->trans('inventoryErrorQtyAdd');
+					return -1;
+				} 
+				
+				$product = new Product($this->db);
+				$product->fetch($this->Inventorydet[$k]->fk_product);
+				
+				$this->Inventorydet[$k]->pmp = $product->pmp;
+				$this->Inventorydet[$k]->qty_view += $qty;
+			}	
+		}
+		
+		return parent::setValues($Tab);
+	}
+
+    /**
+     * Function to delete all Inventorydet
+     *
+     * @param   User    $user   user object
+     * @return                  < 0 if ko, > 0 if ok
+     */
+    public function deleteAllLine(User &$user)
+    {
+        foreach($this->Inventorydet as &$det)
+        {
+            $det->to_delete = true;
+        }
+        
+        $res = $this->update($user);
+
+        if ($res > 0) $this->Inventorydet = array();
+        else return -1;
+    }
+
+    /**
+     * Function to add Inventorydet
+     *
+     * @param   int     $fk_product     fk_product of Inventorydet
+     * @param   int     $fk_warehouse   fk_warehouse target
+     * @return                          bool
+     */
+    public function addProduct($fk_product, $fk_warehouse=0)
+    {
+        $k = $this->addChild('Inventorydet');
+        $det =  &$this->Inventorydet[$k];
+        
+        $det->fk_inventory = $this->id;
+        $det->fk_product = $fk_product;
+		$det->fk_warehouse = empty($fk_warehouse) ? $this->fk_warehouse : $fk_warehouse;
+        
+        $det->load_product();
+                
+        $date = $this->getDate('date_inventory', 'Y-m-d');
+        if(empty($date)) $date = $this->getDate('datec', 'Y-m-d');
+        $det->setStockDate($date, $fk_warehouse);
+        
+        return true;
+    }
+
+    /**
+     *  Duplication method product to add datem
+     *  Adjust stock in a warehouse for product
+     *
+     *  @param  	int     $fk_product     id of product
+     *  @param  	int		$fk_warehouse   id of warehouse
+     *  @param  	double	$nbpiece        nb of units
+     *  @param  	int		$movement       0 = add, 1 = remove
+     * 	@param		string	$label			Label of stock movement
+     * 	@param		double	$price			Unit price HT of product, used to calculate average weighted price (PMP in french). If 0, average weighted price is not changed.
+     *  @param		string	$inventorycode	Inventory code
+     * 	@return     int     				<0 if KO, >0 if OK
+     */
+    public function correctStock($fk_product, $fk_warehouse, $nbpiece, $movement, $label='', $price=0, $inventorycode='')
+	{
+		global $conf, $user;
+
+		if ($fk_warehouse)
+		{
+			$this->db->begin();
+
+			require_once DOL_DOCUMENT_ROOT .'/product/stock/class/mouvementstock.class.php';
+
+			$op[0] = "+".trim($nbpiece);
+			$op[1] = "-".trim($nbpiece);
+
+			$datem = empty($conf->global->INVENTORY_USE_INVENTORY_DATE_FROM_DATEMVT) ? dol_now() : $this->date_inventory;
+
+			$movementstock=new MouvementStock($this->db);
+			$movementstock->origin = new stdClass();
+			$movementstock->origin->element = 'inventory';
+			$movementstock->origin->id = $this->id;
+			$result=$movementstock->_create($user,$fk_product,$fk_warehouse,$op[$movement],$movement,$price,$label,$inventorycode, $datem);
+			
+			if ($result >= 0)
+			{
+				$this->db->commit();
+				return 1;
+			}
+			else
+			{
+			    $this->error=$movementstock->error;
+			    $this->errors=$movementstock->errors;
+
+				$this->db->rollback();
+				return -1;
+			}
+		}
+	}
+
+    /**
+     * Function to regulate stock
+     *
+     * @return      int
+     */
+	public function regulate()
+	{
+		global $langs,$conf;
+		
+		if($conf->global->INVENTORY_DISABLE_VIRTUAL)
+		{
+			$pdt_virtuel = false;
+			// Test if virtual product is enabled
+			if($conf->global->PRODUIT_SOUSPRODUITS)
+			{
+				$pdt_virtuel = true;
+				$conf->global->PRODUIT_SOUSPRODUITS = 0;
+			}
+		}
+		
+		foreach ($this->Inventorydet as $k => $Inventorydet)
+		{
+			$product = new Product($this->db);
+			$product->fetch($Inventorydet->fk_product);
+
+			if ($Inventorydet->qty_view != $Inventorydet->qty_stock)
+			{
+				$Inventorydet->qty_regulated = $Inventorydet->qty_view - $Inventorydet->qty_stock;
+				$nbpiece = abs($Inventorydet->qty_regulated);
+				$movement = (int) ($Inventorydet->qty_view < $Inventorydet->qty_stock); // 0 = add ; 1 = remove
+						
+				//$href = dol_buildpath('/inventory/inventory.php?id='.$this->id.'&action=view', 1);
+				
+				$res = $this->correctStock($product->id, $Inventorydet->fk_warehouse, $nbpiece, $movement, $langs->trans('inventoryMvtStock'));
+				if ($res < 0) return -1;
+			}
+		}
+
+		if($conf->global->INVENTORY_DISABLE_VIRTUAL)
+		{
+            // Test if virtual product was enabled before regulate
+			if($pdt_virtuel) $conf->global->PRODUIT_SOUSPRODUITS = 1;
+		}
+		
+		return 1;
+	}
+
+    /**
+     * Get the title
+     * @return  string
+     */
+	public function getTitle()
+    {
+		global $langs;
+		
+		return !empty($this->title) ? $this->title : $langs->trans('inventoryTitle').' '.$this->id;
+	}
+
+
+    /**
+     * Return clicable link of object (with eventually picto)
+     *
+     * @param   int     $withpicto  Add picto into link
+     * @return                      string
+     */
+	public function getNomUrl($withpicto = 1)
+    {
+        return '<a href="'.DOL_URL_ROOT.'/product/inventory/card.php?id='.$this->id.'">'.($withpicto ? img_picto('','object_list.png','',0).' ' : '').$this->getTitle().'</a>';
+	}
+
+    /**
+     * Function to add products by default from warehouse and children
+     *
+     * @param int $fk_warehouse         id of warehouse
+     * @param int $fk_category          id of category
+     * @param int $fk_supplier          id of supplier
+     * @param int $only_prods_in_stock  only product with stock
+     *
+     * @return int
+     */
+	public function addProductsFor($fk_warehouse,$fk_category=0,$fk_supplier=0,$only_prods_in_stock=0)
+    {
+        $warehouse = new Entrepot($this->db);
+        $warehouse->fetch($fk_warehouse);
+		$TChildWarehouses = array($fk_warehouse);
+        $warehouse->get_children_warehouses($fk_warehouse, $TChildWarehouses);
+			
+		$sql = 'SELECT ps.fk_product, ps.fk_entrepot';
+		$sql.= ' FROM '.MAIN_DB_PREFIX.'product_stock ps';
+        $sql.= ' INNER JOIN '.MAIN_DB_PREFIX.'product p ON (p.rowid = ps.fk_product)';
+        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product cp ON (cp.fk_product = p.rowid)';
+        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_fournisseur_price pfp ON (pfp.fk_product = p.rowid)';
+        $sql.= ' WHERE ps.fk_entrepot IN ('.implode(', ', $TChildWarehouses).')';
+			
+		if ($fk_category>0) $sql.= ' AND cp.fk_categorie='.$fk_category;
+		if ($fk_supplier>0) $sql.= ' AND pfp.fk_soc = '.$fk_supplier;
+		if (!empty($only_prods_in_stock)) $sql.= ' AND ps.reel > 0';
+			
+		$sql.=' GROUP BY ps.fk_product, ps.fk_entrepot ORDER BY p.ref ASC,p.label ASC';
+		 
+		$res = $this->db->query($sql);
+		if($res)
+		{
+			while($obj = $this->db->fetch_object($res))
+            {
+				$this->addProduct($obj->fk_product, $obj->fk_entrepot);
+			}
+
+			return 1;
+		}
+		else
+        {
+            $this->error = $this->db->lasterror();
+            $this->errors[] = $this->db->lasterror();
+            return -1;
+        }
+	}
+
+    /**
+     * Return clicable link of inventory object
+     *
+     * @param   int     $id         id of inventory
+     * @param   int     $withpicto  Add picto into link
+     * @return  string
+     */
+    static function getLink($id, $withpicto=1)
+    {
+        global $langs,$db;
+        
+        $inventory = new Inventory($db);
+        if($inventory->fetch($id, false) > 0) return $inventory->getNomUrl($withpicto);
+        else return $langs->trans('InventoryUnableToFetchObject');
+    }
+
+    /**
+     * Function to get the sql select of inventory
+     * 
+     * @param   string  $type   'All' to get all data
+     * @return  string
+     */
+	static function getSQL($type)
+    {
+		global $conf;
+
+        $sql = '';
+		if($type == 'All')
+		{
+			$sql = 'SELECT i.rowid,i.title, e.label, i.date_inventory, i.fk_warehouse, i.datec, i.tms, i.status';
+            $sql.= ' FROM '.MAIN_DB_PREFIX.'inventory i';
+            $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'entrepot e ON (e.rowid = i.fk_warehouse)';
+            $sql.= ' WHERE i.entity IN ('.getEntity('inventory', 1).')';
+		}
+	
+		return $sql;	
+	}
+}
+
+class Inventorydet extends CoreObject
+{
+	public $element='inventorydet';
+	public $table_element='inventorydet';
+	protected $isnolinkedbythird = 1;     // No field fk_soc
+	protected $ismultientitymanaged = 0;	// 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
+	
+	public $fk_inventory;
+	public $fk_warehouse;
+	public $fk_product;
+	public $entity;
+	public $qty_view;
+	public $qty_stock;
+	public $qty_regulated;
+	public $pmp;
+	public $pa;
+	public $new_pmp;
+	
+	protected $fields=array(
+		'fk_inventory'=>array('type'=>'int')
+		,'fk_warehouse'=>array('type'=>'int')
+		,'fk_product'=>array('type'=>'int')
+		,'entity'=>array('type'=>'int')
+		,'qty_view'=>array('type'=>'float')
+		,'qty_stock'=>array('type'=>'float')
+		,'qty_regulated'=>array('type'=>'float')
+		,'pmp'=>array('type'=>'float')
+		,'pa'=>array('type'=>'float')
+		,'new_pmp'=>array('type'=>'float')
+	);
+
+    /**
+     *  Constructor
+     *
+     *  @param      DoliDB		$db      Database handler
+     */
+	function __construct(DoliDB &$db)
+	{
+		global $conf;
+
+		parent::__construct($db);
+		parent::init();
+				
+		$this->entity = $conf->entity;
+		$this->errors = array();
+		
+		$this->product = null;
+		$this->current_pa = 0;
+	}
+
+    /**
+     * Get object and children from database
+     *
+     * @param   int   $id           id of inventorydet object
+     * @param   bool  $loadChild    load children
+     * @return  int
+     */
+	function fetch($id, $loadChild = true)
+	{
+		$res = parent::fetch($id);
+		$this->load_product();
+        $this->fetch_current_pa();
+			
+		return $res;
+	}
+
+    /**
+     * Function to get the unit buy price
+     *
+     * @return bool
+     */
+    function fetch_current_pa()
+    {
+		global $db,$conf;
+		
+		if(empty($conf->global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)) return false;
+		
+		if($this->pa > 0)
+		{
+			$this->current_pa = $this->pa;
+		}
+		else
+        {
+			dol_include_once('/fourn/class/fournisseur.product.class.php');
+			$p= new ProductFournisseur($db);
+			$p->find_min_price_product_fournisseur($this->fk_product);
+			
+			if($p->fourn_qty>0)	$this->current_pa = $p->fourn_price / $p->fourn_qty;
+		}
+
+		return true;
+	}
+
+    /**
+     * Function to set pa attribute from date en fk_warehouse
+     *
+     * @param   date    $date           date value
+     * @param   int     $fk_warehouse   fk_warehouse target
+     */
+    function setStockDate($date, $fk_warehouse)
+    {
+		list($pmp, $stock) = $this->getPmpStockFromDate($date, $fk_warehouse);
+
+        $this->qty_stock = $stock;
+        $this->pmp = $pmp;
+
+        $last_pa = 0;
+        $sql = 'SELECT price FROM '.MAIN_DB_PREFIX.'stock_mouvement';
+        $sql.= ' WHERE fk_entrepot = '.$fk_warehouse;
+        $sql.= ' AND fk_product = '.$this->fk_product;
+        $sql.= ' AND (origintype=\'order_supplier\' || origintype=\'invoice_supplier\')';
+        $sql.= ' AND price > 0';
+        $sql.= ' AND datem <= \''.$date.' 23:59:59\'';
+        $sql.= ' ORDER BY datem DESC LIMIT 1';
+
+        $res = $this->db->query($sql);
+        if($res && $obj = $this->db->fetch_object($res))
+        {
+            $last_pa = $obj->price;
+        }
+
+        $this->pa = $last_pa;
+    }
+
+
+    /**
+     * Get the last pmp and last stock from date and warehouse
+     *
+     * @param   date    $date           date to check
+     * @param   int     $fk_warehouse   id of warehouse
+     * @return array
+     */
+    function getPmpStockFromDate($date, $fk_warehouse)
+    {
+		$res = $this->product->load_stock();
+		
+		if($res>0)
+		{
+			$stock = isset($this->product->stock_warehouse[$fk_warehouse]->real) ? $this->product->stock_warehouse[$fk_warehouse]->real : 0;
+            $pmp = $this->product->pmp;
+		}
+		
+		//All Stock mouvement between now and inventory date
+		$sql = 'SELECT value, price';
+        $sql.= ' FROM '.MAIN_DB_PREFIX.'stock_mouvement';
+        $sql.= ' WHERE fk_product = '.$this->product->id;
+        $sql.= ' AND fk_entrepot = '.$fk_warehouse;
+        $sql.= ' AND datem > \''.date('Y-m-d 23:59:59', strtotime($date)).'\'';
+        $sql.= ' ORDER BY datem DESC';
+
+		$res = $this->db->query($sql);
+		
+		$laststock = $stock;
+		$lastpmp = $pmp;
+		
+		if($res)
+		{
+			while($mouvement = $this->db->fetch_object($res))
+            {
+				$price = ($mouvement->price > 0 && $mouvement->value > 0) ? $mouvement->price : $lastpmp;
+				$stock_value = $laststock * $lastpmp;
+				$laststock -= $mouvement->value;
+				$last_stock_value = $stock_value - ($mouvement->value * $price);
+				$lastpmp = ($laststock != 0) ? $last_stock_value / $laststock : $lastpmp;
+			}
+		}
+		
+		return array($lastpmp, $laststock);
+	}
+
+    /**
+     * Fetch the product linked with the line
+     * @return  void
+     */
+	function load_product() 
+	{
+		global $db;
+		
+		if($this->fk_product>0)
+		{
+			$this->product = new Product($db);
+			$this->product->fetch($this->fk_product);
+		}
+	}
+}
diff --git a/htdocs/product/inventory/img/bt-save.png b/htdocs/product/inventory/img/bt-save.png
new file mode 100644
index 0000000000000000000000000000000000000000..f20d292ca91805ab875cbb48391cba2e94e3f194
Binary files /dev/null and b/htdocs/product/inventory/img/bt-save.png differ
diff --git a/htdocs/product/inventory/img/inventory.png b/htdocs/product/inventory/img/inventory.png
new file mode 100644
index 0000000000000000000000000000000000000000..e54ad0eef7d76b373e8769153f9039a75681ab3b
Binary files /dev/null and b/htdocs/product/inventory/img/inventory.png differ
diff --git a/htdocs/product/inventory/img/plus.png b/htdocs/product/inventory/img/plus.png
new file mode 100644
index 0000000000000000000000000000000000000000..b7072a96960e30374c5d4f6a5e9bfc374e7a532a
Binary files /dev/null and b/htdocs/product/inventory/img/plus.png differ
diff --git a/htdocs/product/inventory/img/plus16.png b/htdocs/product/inventory/img/plus16.png
new file mode 100644
index 0000000000000000000000000000000000000000..ad17ac89391585adf3fe47f650c3e38ebd5779c7
Binary files /dev/null and b/htdocs/product/inventory/img/plus16.png differ
diff --git a/htdocs/product/inventory/lib/inventory.lib.php b/htdocs/product/inventory/lib/inventory.lib.php
new file mode 100644
index 0000000000000000000000000000000000000000..aa8c9c9677dda7ea2df90a56fd55c9f0c912b9ca
--- /dev/null
+++ b/htdocs/product/inventory/lib/inventory.lib.php
@@ -0,0 +1,104 @@
+<?php
+/* <one line to give the program's name and a brief idea of what it does.>
+ * Copyright (C) 2015 ATM Consulting <support@atm-consulting.fr>
+ *
+ * This program 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.
+ *
+ * This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/**
+ *	\file		lib/inventory.lib.php
+ *	\ingroup	inventory
+ *	\brief		This file is an example module library
+ */
+
+/**
+ *  Define head array for tabs of inventory tools setup pages
+ *
+ *  @return			Array of head
+ */
+function inventoryAdminPrepareHead()
+{
+    global $langs, $conf;
+
+    $langs->load("inventory");
+
+    $h = 0;
+    $head = array();
+
+    $head[$h][0] = DOL_URL_ROOT."/admin/inventory.php";
+    $head[$h][1] = $langs->trans("Parameters");
+    $head[$h][2] = 'settings';
+    $h++;
+    
+
+    // Show more tabs from modules
+    // Entries must be declared in modules descriptor with line
+    //$this->tabs = array(
+    //	'entity:+tabname:Title:@inventory:/inventory/mypage.php?id=__ID__'
+    //); // to add new tab
+    //$this->tabs = array(
+    //	'entity:-tabname:Title:@inventory:/inventory/mypage.php?id=__ID__'
+    //); // to remove a tab
+    complete_head_from_modules($conf, $langs, $object, $head, $h, 'inventory');
+
+    return $head;
+}
+
+function inventoryPrepareHead(&$inventory, $title='Inventory', $get='')
+{
+	global $langs;
+	
+	return array(
+		array(dol_buildpath('/product/inventory/card.php?id='.$inventory->id.$get, 1), $langs->trans($title),'inventory')
+	);
+}
+
+
+
+function inventorySelectProducts(&$inventory)
+{
+	global $conf,$db,$langs;
+	
+	$except_product_id = array();
+	
+	foreach ($inventory->Inventorydet as $Inventorydet)
+	{
+		$except_product_id[] = $Inventorydet->fk_product;
+	}
+	
+	ob_start();
+	$form = new Form($db);
+	$form->select_produits(-1, 'fk_product');
+	
+	$TChildWarehouses = array($inventory->fk_warehouse);
+	$e = new Entrepot($db);
+	$e->fetch($inventory->fk_warehouse);
+	if(method_exists($e, 'get_children_warehouses')) $e->get_children_warehouses($e->id, $TChildWarehouses);
+	
+	$Tab = array();
+	$sql = 'SELECT rowid, label
+			FROM '.MAIN_DB_PREFIX.'entrepot WHERE rowid IN('.implode(', ', $TChildWarehouses).')';
+	if(method_exists($e, 'get_children_warehouses')) $sql.= ' ORDER BY fk_parent';
+	$resql = $db->query($sql);
+	while($res = $db->fetch_object($resql)) {
+		$Tab[$res->rowid] = $res->label;
+	}
+	print '&nbsp;&nbsp;&nbsp;';
+	print $langs->trans('Warehouse').' : '.$form::selectarray('fk_warehouse', $Tab);
+	
+	$select_html = ob_get_clean();
+	
+	return $select_html;
+}
+
diff --git a/htdocs/product/inventory/list.php b/htdocs/product/inventory/list.php
new file mode 100644
index 0000000000000000000000000000000000000000..57545b07948c458e6d4a3c71d36c59b1e871dff1
--- /dev/null
+++ b/htdocs/product/inventory/list.php
@@ -0,0 +1,134 @@
+<?php
+/* Copyright (C) 2016		ATM Consulting			<support@atm-consulting.fr>
+ *
+ * This program 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.
+ *
+ * This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/**
+ *	\file       htdocs/inventory/list.php
+ *	\ingroup    product
+ *	\brief      File of class to manage inventory
+ */
+ 
+require_once '../../main.inc.php';
+
+require_once DOL_DOCUMENT_ROOT.'/product/inventory/listview.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
+include_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
+require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
+require_once DOL_DOCUMENT_ROOT.'/product/inventory/class/inventory.class.php';
+require_once DOL_DOCUMENT_ROOT.'/product/inventory/lib/inventory.lib.php';
+
+$langs->load("stock");
+$langs->load("inventory");
+
+$limit = GETPOST("limit")?GETPOST("limit","int"):$conf->liste_limit;
+$sortfield = GETPOST("sortfield",'alpha');
+$sortorder = GETPOST("sortorder",'alpha');
+$page = (GETPOST("page",'int')?GETPOST("page", 'int'):0);
+if ($page == -1) { $page = 0; }
+$offset = $limit * $page;
+$pageprev = $page - 1;
+$pagenext = $page + 1;
+if (! $sortfield) $sortfield="i.title";
+if (! $sortorder) $sortorder="ASC";
+
+if (empty($user->rights->stock->lire)) accessforbidden();
+
+
+/*
+ * Actions
+ */
+
+// None
+
+
+/*
+ * View
+ */
+
+llxHeader('',$langs->trans('inventoryListTitle'),'','');
+
+echo '<form name="formListInvetory" action="'.$_SERVER['PHP_SELF'].'" method="post" >';
+
+$inventory = new Inventory($db);
+$list = new ListView($db, 'listInventory');
+
+$THide = array('label','title');
+
+echo $list->render(Inventory::getSQL('All'), array(
+    'param' => array(
+        'limit' => $limit,
+        'offset' => $offset,
+        'sortfield' => $sortfield,
+        'sortorder'=> $sortorder,
+        'page'=>$page
+    ),
+    'limit' => array(
+	    'nbLine' => $limit,
+	),
+	'allow-field-select' => true,
+    'link'=>array(
+        'fk_warehouse'=>'<a href="'.DOL_URL_ROOT.'/product/stock/card.php?id=@val@">'.img_picto('','object_stock.png','',0).' @label@</a>'
+    ),
+    'translate'=>array(),
+    'hide'=>$THide,
+    'type'=>array(
+        'datec'=>'date',
+        'tms'=>'datetime',
+        'date_inventory'=>'date'
+    ),
+    'list'=>array(
+        'title'=>$langs->trans('inventoryListTitle'),
+        'messageNothing'=>$langs->trans('inventoryListEmpty'),
+		'image' => 'title_products.png'
+    ),
+    'title'=>array(
+        'rowid'=>$langs->trans('Title'),
+		'date_inventory'=>$langs->trans('InventoryDate'),
+        'fk_warehouse'=>$langs->trans('Warehouse'),
+        'datec'=>$langs->trans('DateCreation'),
+        'tms'=>$langs->trans('DateModification'),
+        'status'=>$langs->trans('Status')
+    ),
+    'eval'=>array(
+        'status' => '(@val@ ? img_picto("'.$langs->trans("inventoryValidate").'", "statut4") : img_picto("'.$langs->trans("inventoryDraft").'", "statut3"))',
+        'rowid'=>'Inventory::getLink(@val@)'
+    ),
+	'position' => array(
+		'text-align' => array('status' => 'right')
+		
+	),
+    'search'=>array(
+		'rowid' => array('search_type' => true, 'table' => array('i'), 'field' => array('title')),
+		'date_inventory'=>array('search_type' => 'calendars', 'table' => array('i'), 'field' => array('date_inventory')),
+		'status'=>array('search_type' => array(1=>$langs->trans("inventoryValidate"), 0=>$langs->trans("inventoryDraft")))
+    )
+));
+
+
+/*if (!empty($user->rights->stock->create))
+{
+    print '<div class="tabsAction">';
+    print '<a class="butAction" href="inventory.php?action=create">'.$langs->trans('inventoryCreate').'</a>';
+    print '</div>';
+}*/
+
+echo '</form>';
+
+llxFooter('');
+$db->close();
\ No newline at end of file
diff --git a/htdocs/product/inventory/listview.class.php b/htdocs/product/inventory/listview.class.php
new file mode 100644
index 0000000000000000000000000000000000000000..51855629686adca82d295d7bb4743663c206913c
--- /dev/null
+++ b/htdocs/product/inventory/listview.class.php
@@ -0,0 +1,1032 @@
+<?php
+/*
+ EXPERIMENTAL
+ 
+ Copyright (C) 2016 ATM Consulting <support@atm-consulting.fr>
+
+ This program and all files within this directory and sub directory
+ 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 any 
+ later version.
+ 
+ This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/**
+ *	Class to manage the lists view
+ */
+class Listview
+{
+    /**
+     *  Constructor
+     *
+     *  @param      DoliDB		$db      Database handler
+     *  @param      string		$id      html id
+     */
+	function __construct(&$db, $id)
+    {
+		$this->db = &$db;
+		$this->id = $id;
+		$this->TTotalTmp=array();
+		$this->sql = '';
+		$this->form = null;
+		$this->totalRowToShow=0;
+		$this->totalRow=0;
+	}
+
+    /**
+     * Function to init fields
+     *
+     * @param   array   $TParam     array of configuration of list
+     * @return bool
+     */
+	private function init(&$TParam)
+    {
+		global $conf, $langs, $user;
+		
+		if(!isset($TParam['hide'])) $TParam['hide']=array();
+		if(!isset($TParam['link'])) $TParam['link']=array();
+		if(!isset($TParam['type'])) $TParam['type']=array();
+		if(!isset($TParam['orderby']['noOrder'])) $TParam['orderby']['noOrder']=array();
+		if(!isset($TParam['allow-fields-select'])) $TParam['allow-fields-select'] = 0;
+		
+		if(!isset($TParam['list']))$TParam['list']=array();
+		$TParam['list'] = array_merge(array(
+			'messageNothing'=>$langs->trans('ListMessageNothingToShow')
+			,'noheader'=>0
+			,'useBottomPagination'=>0
+			,'image'=>''
+			,'title'=>$langs->trans('List')
+			,'orderDown'=>''
+			,'orderUp'=>''
+			,'id'=>$this->id
+			,'head_search'=>''
+			,'export'=>array()
+			,'view_type'=>''
+		),$TParam['list']);
+		
+		if (empty($TParam['limit'])) $TParam['limit'] = array();
+		
+		$page = GETPOST('page');
+		if (!empty($page)) $TParam['limit']['page'] = $page+1; // TODO dolibarr start page at 0 instead 1
+		
+		$TParam['limit'] = array_merge(array('page'=>1, 'nbLine' => $conf->liste_limit, 'global'=>0), $TParam['limit']);
+		
+		if (GETPOST('sortfield'))
+		{
+			$TParam['sortfield'] = GETPOST('sortfield');
+			$TParam['sortorder'] = GETPOST('sortorder');
+		}
+		
+		include_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
+		$this->form = new Form($this->db);
+	}
+
+
+    /**
+     * Function to know if we can search on null value
+     * @param   string  $key    field name
+     * @param   array   $TParam array of configuration
+     * @return bool
+     */
+    private function getSearchNull($key, &$TParam)
+    {
+		return !empty($TParam['search'][$key]['allow_is_null']);
+	}
+
+    /**
+     * @param string    $key    field name
+     * @param string     $TParam array of configuration
+     * @return array
+     */
+	private function getSearchKey($key, &$TParam)
+    {
+		$TPrefixe = array();
+		if(!empty($TParam['search'][$key]['table']))
+		{
+			if (!is_array($TParam['search'][$key]['table'])) $TParam['search'][$key]['table'] = array($TParam['search'][$key]['table']);
+			
+			foreach ($TParam['search'][$key]['table'] as $prefix_table)
+			{
+				$TPrefixe[] = $prefix_table.'.'; 
+			}
+		}
+		
+		$TKey=array();
+		if(!empty($TParam['search'][$key]['field']))
+		{
+			if (!is_array($TParam['search'][$key]['field'])) $TParam['search'][$key]['field'] = array($TParam['search'][$key]['field']);
+			
+			foreach ($TParam['search'][$key]['field'] as $i => $field)
+			{
+				$prefixe = !empty($TPrefixe[$i]) ? $TPrefixe[$i] : $TPrefixe[0];
+				$TKey[] = $prefixe. $field ;
+			}
+		}
+		else
+		{
+			$TKey[] = $TPrefixe[0].$key;
+		}
+		
+		return $TKey;
+	}
+
+    /**
+     * @param timestamp    $date   date to convert
+     * @return int|string   Date TMS or ''
+     */
+    private function dateToSQLDate($date)
+    {
+		return $this->db->idate($date);
+	}
+
+
+    /**
+     * @param string     $TSQLMore   contain some additional sql instructions
+     * @param string    $value      date with read format
+     * @param string    $sKey       field name
+     */
+    private function addSqlFromTypeDate(&$TSQLMore, &$value, $sKey)
+	{
+		if(is_array($value))
+		{
+			$TSQLDate=array();
+			if(!empty($value['start']))
+			{
+//				$valueDeb = $this->dateToSQLDate($value['start'].' 00:00:00');
+				$TSQLDate[]=$sKey." >= '".$value['start']."'" ;
+			}
+
+			if(!empty($value['end']))
+			{
+//				$valueFin = $this->dateToSQLDate($value['end'].' 23:59:59');
+				$TSQLDate[]=$sKey." <= '".$value['end']."'" ;
+			}
+
+			if(!empty($TSQLDate)) $TSQLMore[] = implode(' AND ', $TSQLDate);
+		}
+		else
+		{
+//			$value = $this->dateToSQLDate($value);
+			$TSQLMore[]=$sKey." LIKE '".$value."%'" ;
+		}
+	}
+
+
+    /**
+     * @param string     $TSQLMore   contain some additional sql instructions
+     * @param string    $value      value to filter
+     * @param string     $TParam     array of configuration
+     * @param string    $sKey       field name
+     * @param string    $key        reference of sKey to find value into TParam
+     * @return bool
+     */
+    private function addSqlFromOther(&$TSQLMore, &$value, &$TParam, $sKey, $key)
+	{
+		// Do not use empty() function, statut 0 exist
+		if ($value == '') return false;
+		elseif($value==-1) return false;
+			
+		if(isset($TParam['operator'][$key]))
+		{
+			if($TParam['operator'][$key] == '<' || $TParam['operator'][$key] == '>' || $TParam['operator'][$key]=='=')
+			{
+				$TSQLMore[] = $sKey . ' ' . $TParam['operator'][$key] . ' "' . $value . '"';
+			}
+			elseif ($TParam['operator'][$key]=='IN')
+			{
+				$TSQLMore[] = $sKey . ' ' . $TParam['operator'][$key] . ' (' . $value . ')';
+			}
+			else
+			{
+				if(strpos($value,'%')===false) $value = '%'.$value.'%';
+				$TSQLMore[]=$sKey." LIKE '".addslashes($value)."'" ;
+			}
+		}
+		else
+		{
+            if(strpos($value,'%')===false) $value = '%'.$value.'%';
+            $TSQLMore[]=$sKey." LIKE '".addslashes($value)."'" ;
+		}
+		
+		return true;
+	}
+
+
+    /**
+     * @param string    $sql    standard select sql
+     * @param string     $TParam array of configuration
+     * @return string
+     */
+    private function search($sql, &$TParam)
+    {
+		$ListPOST = GETPOST('Listview');
+		
+		if (!GETPOST("button_removefilter_x") && !GETPOST("button_removefilter.x") && !GETPOST("button_removefilter"))
+		{
+			foreach ($TParam['search'] as $field => $info)
+			{
+				$TsKey = $this->getSearchKey($field, $TParam);
+				$TSQLMore = array();
+				$allow_is_null = $this->getSearchNull($field,$TParam);
+				
+				foreach ($TsKey as $i => &$sKey)
+				{
+					$value = '';
+					if (isset($ListPOST[$this->id]['search'][$field])) $value = $ListPOST[$this->id]['search'][$field];
+					
+					if ($allow_is_null && !empty($ListPOST[$this->id]['search_on_null'][$field]))
+					{
+						$TSQLMore[] = $sKey.' IS NULL ';
+						$value = '';
+					}
+					
+					if (isset($TParam['type'][$field]) && ($TParam['type'][$field]==='date' || $TParam['type'][$field]==='datetime'))
+					{
+						$k = 'Listview_'.$this->id.'_search_'.$field;
+						if ($info['search_type'] === 'calendars')
+						{
+							$value = array();
+							
+							$timestart = dol_mktime(0, 0, 0, GETPOST($k.'_startmonth'), GETPOST($k.'_startday'), GETPOST($k.'_startyear'));
+							if ($timestart) $value['start'] = date('Y-m-d', $timestart);
+							
+							$timeend = dol_mktime(23, 59, 59, GETPOST($k.'_endmonth'), GETPOST($k.'_endday'), GETPOST($k.'_endyear'));
+							if ($timeend) $value['end'] = date('Y-m-d', $timeend);
+						}
+						else
+						{
+							$time = dol_mktime(12, 0, 0, GETPOST($k.'month'), GETPOST($k.'day'), GETPOST($k.'year'));
+							if ($time) $value = date('Y-m-d', $time);
+						}
+						
+						if (!empty($value)) $this->addSqlFromTypeDate($TSQLMore, $value, $sKey);
+					}
+					else
+					{
+						$this->addSqlFromOther($TSQLMore, $value, $TParam, $sKey, $field);
+					}
+				}
+				
+				if (!empty($TSQLMore))
+				{
+					$sql.=' AND ( '.implode(' OR ',$TSQLMore).' ) ';
+				}
+			}
+		}
+		
+		if ($sqlGROUPBY!='') $sql.=' GROUP BY '.$sqlGROUPBY;
+
+		return $sql;
+	}
+
+    /**
+     * @param string    $sql    standard select sql
+     * @param string     $TParam array of configuration
+     * @return string
+     */
+    public function render($sql, $TParam=array())
+    {
+        global $conf;
+        
+		$TField=array();
+		
+		$this->init($TParam);
+
+        $THeader = $this->initHeader($TParam);
+		
+		$sql = $this->search($sql,$TParam);
+		$sql.= $this->db->order($TParam['param']['sortfield'], $TParam['param']['sortorder']);
+
+		$nbtotalofrecords = '';
+		if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
+		{
+		    $result = $this->db->query($sql);
+		    $nbtotalofrecords = $this->db->num_rows($result);
+		}
+		$sql.= $this->db->plimit($TParam['param']['limit'] + 1, $TParam['param']['offset']);
+		
+		$this->parse_sql($THeader, $TField, $TParam, $sql);
+		
+		list($TTotal, $TTotalGroup)=$this->get_total($TField, $TParam);
+		
+		return $this->renderList($THeader, $TField, $TTotal, $TTotalGroup, $TParam);
+	}
+
+    /**
+     * @param string     $THeader    the configuration of header
+     * @param string     $TParam     array of configuration
+     * @return array
+     */
+    private function setSearch(&$THeader, &$TParam)
+    {
+		global $langs, $form;
+		
+		if(empty($TParam['search'])) return array();
+		
+		$TSearch=array();
+		
+		$nb_search_in_bar = 0;
+		
+		if(!empty($TParam['search']))
+		{
+			foreach($THeader as $key => $libelle)
+			{
+				if(empty($TSearch[$key]))$TSearch[$key]='';
+			}
+		}	
+		
+		$ListPOST = GETPOST('Listview');
+		$removeFilter = (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter"));
+		foreach($TParam['search'] as $key => $param_search)
+		{
+			$value = isset($ListPOST[$this->id]['search'][$key]) ? $ListPOST[$this->id]['search'][$key] : '';
+			if ($removeFilter) $value = '';
+			
+			$typeRecherche = (is_array($param_search) && isset($param_search['search_type'])) ? $param_search['search_type'] : $param_search;  
+			
+			if(is_array($typeRecherche))
+			{
+				$fsearch=$form->selectarray('Listview['.$this->id.'][search]['.$key.']', $typeRecherche,$value,1);
+			}
+			else if($typeRecherche==='calendar')
+			{
+				if (!$removeFilter) $value = GETPOST('Listview_'.$this->id.'_search_'.$key) ? mktime(0,0,0, (int) GETPOST('Listview_'.$this->id.'_search_'.$key.'month'), (int) GETPOST('Listview_'.$this->id.'_search_'.$key.'day'), (int) GETPOST('Listview_'.$this->id.'_search_'.$key.'year') ) : '';
+				
+				$fsearch = $form->select_date($value, 'Listview_'.$this->id.'_search_'.$key,0, 0, 1, "", 1, 0, 1);
+			}
+			else if($typeRecherche==='calendars')
+			{
+				$value_start = $value_end = '';
+				if (!$removeFilter)
+				{
+					$value_start = GETPOST('Listview_'.$this->id.'_search_'.$key.'_start') ? mktime(0,0,0, (int) GETPOST('Listview_'.$this->id.'_search_'.$key.'_startmonth'), (int) GETPOST('Listview_'.$this->id.'_search_'.$key.'_startday'), (int) GETPOST('Listview_'.$this->id.'_search_'.$key.'_startyear') ) : '';
+					$value_end = GETPOST('Listview_'.$this->id.'_search_'.$key.'_end') ? mktime(0,0,0, (int) GETPOST('Listview_'.$this->id.'_search_'.$key.'_endmonth'), (int) GETPOST('Listview_'.$this->id.'_search_'.$key.'_endday'), (int) GETPOST('Listview_'.$this->id.'_search_'.$key.'_endyear') ) : '';
+				}
+			
+				$fsearch = $form->select_date($value_start, 'Listview_'.$this->id.'_search_'.$key.'_start',0, 0, 1, "", 1, 0, 1)
+						 . $form->select_date($value_end, 'Listview_'.$this->id.'_search_'.$key.'_end',0, 0, 1, "", 1, 0, 1);
+				
+			}
+			else if(is_string($typeRecherche))
+			{
+				$fsearch=$TParam['search'][$key];	
+			}
+			else
+            {
+				$fsearch='<input type="text" name="Listview['.$this->id.'][search]['.$key.']" id="Listview['.$this->id.'][search]['.$key.']" value="'.$value.'" size="15" />';
+			}
+
+			if(!empty($param_search['allow_is_null']))
+			{
+				$valueNull = isset($ListPOST[$this->id]['search_on_null'][$key]) ? 1 : 0;
+				$fsearch.=' '.$form->checkbox1('', 'Listview['.$this->id.'][search_on_null]['.$key.']',1, $valueNull,' onclick=" if($(this).is(\':checked\')){ $(this).prev().val(\'\'); }" ').img_help(1, $langs->trans('SearchOnNUllValue'));
+			}
+
+			if(!empty($THeader[$key]))
+			{
+				$TSearch[$key] = $fsearch;
+				$nb_search_in_bar++;
+			}
+			else
+            {
+				$label = !empty($TParam['title'][$key]) ? $TParam['title'][$key] : $key ;
+				$TParam['list']['head_search'].= '<th>'.$label.'</th>';
+//				$TParam['list']['head_search'].='<div><span style="min-width:200px;display:inline-block;">'.$label.'</span> '.$fsearch.'</div>';	
+			}
+		}
+		
+		$search_button = ' <a href="#" onclick="Listview_submitSearch(this);" class="list-search-link">'.img_search().'</a>';
+
+		if(!empty($TParam['list']['head_search']))
+		{
+			$TParam['list']['head_search']='<div style="float:right;">'.$search_button.'</div>'.$TParam['list']['head_search'];
+		}
+		
+		if($nb_search_in_bar>0)
+		{
+			end($TSearch);
+			list($key,$v) = each($TSearch);
+			$TSearch[$key].=$search_button;
+		}
+		else
+        {
+			$TSearch=array();
+		}
+		
+		return $TSearch;
+	}
+
+    /**
+     * Function to analyse and calculate the total from a column
+     *
+     * @param string $TField    TField
+     * @param string $TParam    TParam
+     * @return array
+     */
+    private function get_total(&$TField, &$TParam)
+    {
+		$TTotal=$TTotalGroup=array();	
+		
+		if(!empty($TParam['math']) && !empty($TField[0]))
+		{
+			foreach($TField[0] as $field=>$value)
+			{
+				$TTotal[$field]='';	
+				$TTotalGroup[$field] = '';
+			}
+		
+			foreach($TParam['math'] as $field=>$typeMath)
+			{
+				if(is_array($typeMath))
+				{
+					$targetField = $typeMath[1];
+					$typeMath = $typeMath[0];
+				}
+				else
+                {
+					$targetField = $field;
+				}
+
+				if($typeMath == 'groupsum')
+				{
+					$TTotalGroup[$field] = array('target'=>$targetField, 'values'=> $this->TTotalTmp['@groupsum'][$targetField]);
+				}
+				else if($typeMath=='average')
+				{
+					$TTotal[$field]=array_sum($this->TTotalTmp[$targetField]) / count($this->TTotalTmp[$targetField]);
+				}
+				elseif($typeMath=='count')
+                {
+					$TTotal[$field]=count($this->TTotalTmp[$targetField]);
+				}
+				else
+                {
+					$TTotal[$field]=array_sum($this->TTotalTmp[$targetField]);
+				}
+			}
+		}
+		
+		return array($TTotal,$TTotalGroup);
+	}
+
+    /**
+     * @return string
+     */
+	/*
+    private function getJS()
+    {
+		$javaScript = '<script language="javascript">
+		if(typeof(Listview_include)=="undefined") {
+			document.write("<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/core/js/listview.js?version='.DOL_VERSION.'\"></scr");
+	  		document.write("ipt>");
+		}
+		</script>';
+
+		return $javaScript;
+	}
+    */
+	
+    /**
+     * @param string $TParam    TParam
+     * @param string $TField    TField
+     * @param string $THeader   THeader
+     * @return array
+     */
+    private function setExport(&$TParam, $TField, $THeader)
+    {
+		global $langs;
+		
+		$Tab=array();
+		if(!empty($TParam['export']))
+		{
+			$token = GETPOST('token');
+			if(empty($token)) $token = md5($this->id.time().rand(1,9999));
+
+            $_SESSION['token_list_'.$token] = gzdeflate( serialize( array(
+                'title'=>$this->title,
+                'sql'=>$this->sql,
+                'TBind'=>$this->TBind,
+                'TChamps'=>$TField,
+                'TEntete'=>$THeader
+            )));
+
+            foreach($TParam['export'] as $mode_export)
+            {
+                $Tab[] = array(
+                    'label'=>$langs->trans('Export'.$mode_export),
+                    'url'=>dol_buildpath('/abricot/downlist.php',1),
+                    'mode'=>$mode_export,
+                    'token'=>$token,
+                    'session_name'=>session_name()
+                );
+			}
+			
+		}
+		
+		return $Tab;
+	}
+
+    /**
+     * @param string $TField        TField
+     * @param string $TTotalGroup   TTotalGroup
+     * @return array
+     */
+    private function addTotalGroup($TField, $TTotalGroup)
+    {
+		global $langs;
+		
+		$Tab=array();
+		$proto_total_line = array();
+		$tagbase = $old_tagbase = null;
+		$addGroupLine = false;
+		
+		foreach($TField as $k=>&$line)
+		{
+			if(empty($proto_total_line))
+			{
+				foreach($line as $field=>$value)
+				{
+					$proto_total_line[$field] = '';
+				}
+				$group_line = $proto_total_line;	
+			}
+			
+			$addGroupLine = false;
+			
+			$tagbase = '';
+			foreach($line as $field=>$value)
+			{
+				if(!empty($TTotalGroup[$field]))
+				{
+					$tagbase.=$value.'|';
+					$group_line[$field] = '<div style="text-align:right; font-weight:bold; color:#552266;">'.(empty($value) ? $langs->trans('Empty') : $value ).' : </div>';
+					$group_line[$TTotalGroup[$field]['target']] = '<div style="text-align:right; font-weight:bold; color:#552266;">'.price($TTotalGroup[$field]['values'][$value]).'</div>';
+					$addGroupLine = true;
+				}
+			}
+			
+			if(!is_null($old_tagbase) && $old_tagbase!=$tagbase && $addGroupLine)
+			{
+				$Tab[] = $previous_group_line;
+			}
+			
+			$old_tagbase = $tagbase;
+			$previous_group_line = $group_line;
+			$group_line = $proto_total_line;
+			
+			$Tab[] = $line;
+		}
+
+		if($addGroupLine)
+		{
+			$Tab[] = $previous_group_line;
+		}
+		
+		return $Tab;
+	}
+
+    /**
+     * @param string $THeader   THeader
+     * @param string $TField    TField
+     * @param string $TTotal    TTotal
+     * @param string $TTotalGroup   TTotalGroup
+     * @param string $TParam        TParam
+     * @return string
+     */
+    private function renderList(&$THeader, &$TField, &$TTotal, &$TTotalGroup, &$TParam)
+    {
+		global $bc;
+		
+		$TSearch = $this->setSearch($THeader, $TParam);
+		$TExport = $this->setExport($TParam, $TField, $THeader);
+		$TField = $this->addTotalGroup($TField,$TTotalGroup);
+		
+		//$out = $this->getJS();
+		
+		$dolibarr_decalage = $this->totalRow > $this->totalRowToShow ? 1 : 0;
+		ob_start();
+		print_barre_liste($TParam['list']['title'], $TParam['limit']['page']-1, $_SERVER["PHP_SELF"], '&'.$TParam['list']['param_url'], $TParam['sortfield'], $TParam['sortorder'], '', $this->totalRowToShow+$dolibarr_decalage, $this->totalRow, $TParam['list']['image'], 0, '', '', $TParam['limit']['nbLine']);
+		$out .= ob_get_clean();
+		
+	
+		$out.= '<table id="'.$this->id.'" class="liste" width="100%"><thead>';
+			
+    	if(count($TSearch)>0)
+		{
+			$out.='<tr class="liste_titre liste_titre_search barre-recherche">';
+			
+			foreach ($THeader as $field => $head)
+			{
+				if ($field === 'selectedfields')
+				{
+					$out.= '<td class="liste_titre" align="right">'.$this->form->showFilterAndCheckAddButtons(0).'</td>';
+				}
+				else
+				{
+					$moreattrib = 'style="width:'.$head['width'].';text-align:'.$head['text-align'].'"';
+					$out .= '<td class="liste_titre" '.$moreattrib.'>'.$TSearch[$field].'</td>';
+				}
+			}
+			
+			$out.='</tr>';
+		}
+				
+		$out.= '<tr class="liste_titre">';
+		foreach($THeader as $field => $head)
+		{
+			$moreattrib = '';
+			$search = '';
+			$prefix = '';
+
+			if ($field === 'selectedfields')
+			{
+				$moreattrib = 'align="right" ';
+				$prefix = 'maxwidthsearch ';
+			}
+
+			if (empty($head['width'])) $head['width'] = 'auto';
+			if (!empty($head['width']) && !empty($head['text-align'])) $moreattrib .= 'style="width:'.$head['width'].';text-align:'.$head['text-align'].'"';
+
+			if (isset($TParam['search'][$field]['search_type']) && $TParam['search'][$field]['search_type'] !== false)
+			{
+				$TsKey = $this->getSearchKey($field, $TParam);
+				if (!empty($TsKey)) $search = implode(',', $TsKey);
+				else $search = $field;
+			}
+
+			$out .= getTitleFieldOfList($head['label'], 0, $_SERVER["PHP_SELF"], $search, '', $moreparam, $moreattrib, $TParam['sortfield'], $TParam['sortorder'], $prefix);
+			$out .= $head['more'];
+		}
+		
+		//$out .= '<th aligne="right" class="maxwidthsearch liste_titre">--</th>';
+		$out .= '</tr>';
+		
+		$out.='</thead><tbody>';
+		
+		if(empty($TField))
+		{
+			if (!empty($TParam['list']['messageNothing'])) $out .= '<tr class="oddeven"><td colspan="'.(count($TParam['title'])+1).'"><span class="opacitymedium">'.$TParam['list']['messageNothing'].'</span></td></tr>';
+		}
+		else
+        {
+			$var=true;
+			$line_number = 0;
+			foreach($TField as $fields)
+			{
+				if($this->in_view($TParam, $line_number))
+				{
+					$var=!$var;
+					$out.='<tr '.$bc[$var].'> <!-- '.$field.' -->';
+
+					foreach ($THeader as $field => $head)
+					{
+						$moreattrib = 'style="width:'.$head['width'].';text-align:'.$head['text-align'].'"';
+						$out.='<td class="'.$field.'" '.$moreattrib.'>'.$fields[$field].'</td>';
+					}
+
+					$out.='</tr>';
+				}
+				
+				$line_number++;
+			}
+			
+			$out.='</tbody>';
+			
+			if (!empty($TParam['list']['haveTotal']))
+			{
+				$out.='<tfoot><tr class="liste_total">';
+			
+				foreach ($THeader as $field => $head)
+				{
+					if (isset($TTotal[$field]))
+					{
+						$moreattrib = 'style="width:'.$head['width'].';text-align:'.$head['text-align'].'"';
+						$out.='<td align="right" class="'.$field.'" '.$moreattrib.'>'.price($TTotal[$field]).'</td>';
+					}
+				}
+					
+				$out.='</tr></tfoot>';
+			}
+		}
+
+		$out .= '</table>';
+		
+		return $out;
+	}
+
+    /**
+     * @param string $db        Db
+     * @param string $TField    TField
+     * @param string $TParam    TParam
+     */
+    public function renderArray(&$db, $TField, $TParam=array())
+    {
+		$this->typeRender = 'array';
+
+		$TField=array();	
+		
+		$this->init($TParam);
+		$THeader = $this->initHeader($TParam);
+		
+		$this->parse_array($THeader, $TField, $TParam);
+		list($TTotal, $TTotalGroup)=$this->get_total($TField, $TParam);
+		
+		$this->renderList($THeader, $TField, $TTotal, $TTotalGroup, $TParam);
+	}
+
+
+    /**
+     * @param string $THeader   THeader
+     * @param string $TField    TField
+     * @param string $TParam    TParam
+     * @return bool
+     */
+    private function parse_array(&$THeader, &$TField, &$TParam)
+    {
+		$this->totalRow = count($TField);
+		
+		$this->THideFlip = array_flip($TParam['hide']);
+		$this->TTotalTmp=array();
+		
+		if (empty($TField)) return false;
+		
+		foreach($TField as $row)
+		{
+			$this->set_line($TField, $TParam, $row);
+		}
+	}
+
+	
+	private function initHeader(&$TParam)
+	{
+		global $user,$conf;
+		
+		$THeader = array();
+		
+		$TField=$TFieldVisibility=array();
+		foreach ($TParam['title'] as $field => $value)
+		{
+			$TField[$field]=true;
+		}
+		
+		$contextpage=md5($_SERVER['PHP_SELF']);
+		if(!empty($TParam['allow-field-select']))
+		{
+			$selectedfields = GETPOST('Listview'.$this->id.'_selectedfields');
+			
+			if(!empty($selectedfields))
+			{
+				include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
+				$tabparam['MAIN_SELECTEDFIELDS_'.$contextpage] = $selectedfields;
+	    		$result=dol_set_user_param($this->db, $conf, $user, $tabparam);
+			}
+			
+			$tmpvar='MAIN_SELECTEDFIELDS_'.$contextpage;
+			if (! empty($user->conf->{$tmpvar}))
+			{
+				$tmparray = explode(',', $user->conf->{$tmpvar});
+				$TParam['hide'] = array();
+		        foreach($TField as $field => $dummy)
+		        {
+		          	$label = $TParam['title'][$field];
+					if(!in_array($field, $tmparray))
+					{
+				  		$TParam['hide'][] = $field;
+						$visible = 0;
+				  	}
+					else
+					{
+						$visible = 1;
+					}
+		            
+					$TFieldVisibility[$field] = array(
+						'label'=>$label
+						,'checked'=>$visible
+					);
+		        }
+			}
+			else
+            {
+				foreach($TField as $field=>$dummy)
+		        {
+		        	$label = isset($TParam['title'][$field]) ? $TParam['title'][$field] : $field;
+					$visible = (!in_array($field, $TParam['hide'])) ? 1 : 0;
+					$TFieldVisibility[$field]=array(
+						'label'=>$label,
+						'checked'=>$visible
+					);
+				}
+			}	
+
+			$selectedfields = $this->form->multiSelectArrayWithCheckbox('Listview'.$this->id.'_selectedfields', $TFieldVisibility, $contextpage);	// This also change content of $arrayfields_0
+		}
+
+		foreach ($TParam['title'] as $field => $label)
+		{
+			$visible = (!in_array($field, $TParam['hide'])) ? 1 : 0;
+			if($visible)
+			{
+				$THeader[$field] = array(
+					'label'=>$label,
+					'order'=>(in_array($field, $TParam['orderby']['noOrder']) ? 0 : 1),
+					'width'=>(!empty($TParam['size']['width'][$field]) ? $TParam['size']['width'][$field] : 'auto'),
+					'text-align'=>(!empty($TParam['position']['text-align'][$field]) ? $TParam['position']['text-align'][$field] : 'auto'),
+					'more'=>''
+				);
+			}
+		}
+		
+		if(!empty($selectedfields))
+		{
+			$THeader['selectedfields']['label']='<div style="float:right">'.$selectedfields.'</div>';
+		}
+		
+		return $THeader;
+	}
+
+    /**
+     * @param string $TParam        TParam
+     * @param string $line_number   aaa
+     * @return bool
+     */
+    private function in_view(&$TParam, $line_number)
+    {
+		global $conf;
+
+		if(!empty($_REQUEST['get-all-for-export'])) return true;
+
+		$page_number = !empty($TParam['limit']['page']) ? $TParam['limit']['page'] : 1;
+		$line_per_page = !empty($TParam['limit']['nbLine']) ? $TParam['limit']['nbLine'] : $conf->liste_limit;
+		
+		$start = ($page_number-1) * $line_per_page;
+		$end = ($page_number* $line_per_page) -1;
+		
+		if($line_number>=$start && $line_number<=$end) return true;
+		else return false;
+	}
+
+    /**
+     * @param string $TField        TField
+     * @param string $TParam        TParam
+     * @param string $currentLine   aaa
+     */
+    private function set_line(&$TField, &$TParam, $currentLine)
+    {
+        global $conf;
+
+        $line_number = count($TField);
+
+        if($this->in_view($TParam,$line_number))
+        {
+			$this->totalRowToShow++;
+            $row=array(); $trans = array();
+            foreach($currentLine as $field=>$value)
+            {
+                if(is_object($value))
+                {
+                    if(get_class($value)=='stdClass') {$value=print_r($value, true);}
+                    else $value=(string) $value;
+                }
+
+                $trans['@'.$field.'@'] = $value;
+
+                if(!empty($TParam['math'][$field]))
+                {
+                    $float_value = (double) strip_tags($value);
+                    $this->TTotalTmp[$field][] = $float_value;
+                }
+
+                if(!in_array($field,$TParam['hide']))
+                {
+                    $row[$field]=$value;
+
+                    if(isset($TParam['eval'][$field]) && in_array($field,array_keys($row)))
+                    {
+                        $strToEval = 'return '.strtr( $TParam['eval'][$field],  array_merge( $trans, array('@val@'=>$row[$field])  )).';';
+                        $row[$field] = eval($strToEval);
+                    }
+
+                    if(isset($TParam['type'][$field]) && !isset($TParam['eval'][$field]))
+                    {
+                        if($TParam['type'][$field]=='date' || $TParam['type'][$field]=='datetime' )
+                        {
+                            if($row[$field] != '0000-00-00 00:00:00' && $row[$field] != '1000-01-01 00:00:00' && $row[$field] != '0000-00-00' && !empty($row[$field]))
+                            {
+                                if($TParam['type'][$field]=='datetime')$row[$field] = dol_print_date(strtotime($row[$field]),'dayhoursec');
+                                else $row[$field] = dol_print_date(strtotime($row[$field]),'day');
+                            }
+                            else
+                            {
+                                $row[$field] = '';
+                            }
+                        }
+
+                        if($TParam['type'][$field]=='hour') { $row[$field] = date('H:i', strtotime($row[$field])); }
+                        if($TParam['type'][$field]=='money') { $row[$field] = '<div align="right">'.price($row[$field],0,'',1,-1,2).'</div>'; }
+                        if($TParam['type'][$field]=='number') { $row[$field] = '<div align="right">'.price($row[$field]).'</div>'; }
+                        if($TParam['type'][$field]=='integer') { $row[$field] = '<div align="right">'.((int) $row[$field]).'</div>'; }
+                    }
+
+                    if(isset($TParam['link'][$field]))
+                    {
+                        if(empty($row[$field]) && $row[$field]!==0 && $row[$field]!=='0')$row[$field]='(vide)';
+                        $row[$field]= strtr( $TParam['link'][$field],  array_merge( $trans, array('@val@'=>$row[$field]))) ;
+                    }
+
+                    if(isset($TParam['translate'][$field]))
+                    {
+                        if(isset($TParam['translate'][$field][''])) unset($TParam['translate'][$field]['']);
+
+                        $row[$field] = strtr( $row[$field], $TParam['translate'][$field]);
+                    }
+                }
+            }
+        }
+        else
+        {
+            $row = array();
+
+            foreach($currentLine as $field=>&$value)
+            {
+                if(!isset($this->THideFlip[$field]))
+                {
+                    if(isset($TParam['math'][$field]) && !empty($TParam['math'][$field]))
+                    {
+                        $float_value = (double) strip_tags($value);
+                        $this->TTotalTmp[$field][] = $float_value;
+                    }
+
+                    $row[$field] = $value;
+                }
+            }
+        }
+
+        if(!empty($TParam['math'][$field]))
+        {
+            foreach($row as $field=>$value)
+            {
+                if(!empty($TParam['math'][$field]) && is_array($TParam['math'][$field]))
+                {
+                    $toField = $TParam['math'][$field][1];
+                    $float_value = (double) strip_tags($row[$toField]);
+                    $this->TTotalTmp['@groupsum'][$toField][ $row[$field]  ] += $float_value;
+                }
+            }
+        }
+
+        $TField[] = $row;
+	}
+
+    /**
+     * @param string $sql       sql
+     * @param string $TParam    TParam
+     * @return string
+     */
+    private function limitSQL($sql, &$TParam)
+    {
+		if(!empty($TParam['limit']['global']) && strpos($sql,'LIMIT ')===false )
+		{
+			$sql.=' LIMIT '.(int) $TParam['limit']['global'];
+		}
+		
+		return $sql;
+	}
+
+    /**
+     * @param string $THeader   THeader
+     * @param string $TField    TField
+     * @param string $TParam    TParam
+     * @param string $sql       sql
+     */
+    private function parse_sql(&$THeader, &$TField, &$TParam, $sql)
+    {
+		$this->sql = $this->limitSQL($sql, $TParam);
+		
+		$this->TTotalTmp=array();
+		$this->THideFlip = array_flip($TParam['hide']);
+		
+		$res = $this->db->query($this->sql);
+		if($res!==false)
+		{
+			$this->totalRow = $this->db->num_rows($res);
+			dol_syslog(get_class($this)."::parse_sql id=".$this->id." sql=".$this->sql, LOG_DEBUG);
+			
+			while($currentLine = $this->db->fetch_object($res))
+            {
+				$this->set_line($TField, $TParam, $currentLine);
+			}
+		}
+		else
+        {
+			dol_syslog(get_class($this)."::parse_sql id=".$this->id." sql=".$this->sql, LOG_ERR);
+		}
+	}	
+}
diff --git a/htdocs/product/inventory/tpl/inventory.tpl.php b/htdocs/product/inventory/tpl/inventory.tpl.php
new file mode 100644
index 0000000000000000000000000000000000000000..05de0f4c0025d626b79e3aaa0969aa7070181908
--- /dev/null
+++ b/htdocs/product/inventory/tpl/inventory.tpl.php
@@ -0,0 +1,205 @@
+<script type="text/javascript">
+    function save_qty(k) {
+        
+        var $input = $('input[name="qty_to_add['+k+']"]');
+        var fk_det_inventory = $('input[name=det_id_'+k+']').val();
+        var qty = $input.val();
+        
+        $('#a_save_qty_'+k).hide();
+        
+        $.ajax({
+            url:"ajax/ajax.inventory.php"
+            ,data:{
+                'fk_det_inventory' : fk_det_inventory
+                ,'qty': qty
+                ,'put':'qty'
+            }
+            
+        }).done(function(data) {
+            $('#qty_view_'+k).html(data);
+            $input.val(0);
+            $.jnotify("Quantité ajoutée : "+qty, "mesgs" );
+            
+            $('#a_save_qty_'+k).show();
+            
+            hide_save_button();
+        });
+        
+        
+    }
+    
+    function save_pmp(k) {
+    	
+        var $input = $('input[name="new_pmp['+k+']"]');
+        var fk_det_inventory = $('input[name=det_id_'+k+']').val();
+        var pmp = $input.val();
+        
+        $('#a_save_new_pmp_'+k).hide();
+        
+        $.ajax({
+            url:"ajax/ajax.inventory.php"
+            ,data:{
+                'fk_det_inventory' : fk_det_inventory
+                ,'pmp': pmp
+                ,'put':'pmp'
+            }
+            
+        }).done(function(data) {
+           	$input.css({"background-color":"#66ff66"});
+            $.jnotify("PMP sauvegardé : "+pmp, "mesgs" );
+            $('#a_save_new_pmp_'+k).show();
+             
+        });
+        
+    }
+    
+    function hide_save_button() {
+       var nb = 0;
+       $('input[name^="qty_to_add"]').each(function() {
+           nb += $(this).val();
+       });
+       
+       if(nb>0) {
+           $('input[name=modify]').show();
+           
+       }
+       else{
+           $('input[name=modify]').hide();
+           
+       }
+        
+    }
+</script>
+
+<?php if ($object->status != 1) { ?>
+	<strong><?php echo $langs->trans('AddInventoryProduct'); ?> : </strong>
+	<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
+		<input type="hidden" name="action" value="add_line" />
+		<input type="hidden" name="id" value="<?php echo $object->id; ?>" />
+	
+		<?php echo inventorySelectProducts($object); ?>
+		
+			<input class="button" type="submit" value="<?php echo $langs->trans('AddProduct'); ?>" />
+	</form><br>
+<?php } ?>
+
+<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
+	
+	<?php if ($view['is_already_validate'] == 1) { ?>
+		<div class="warning">Cet inventaire est validé</div>
+	<?php } ?>
+	
+	<input type="hidden" name="action" value="save" />
+	<input type="hidden" name="id" value="<?php echo $object->id; ?>" />
+	
+	<table width="100%" class="noborder workstation">
+		<?php
+		
+		_headerList($view); 
+        
+        $total_pmp = $total_pa = $total_pmp_actual = $total_pa_actual =$total_current_pa=$total_current_pa_actual = 0;
+        $i=1;
+        
+        foreach ($lines as $k=>$row) { 
+            
+            $total_pmp+=$row['pmp_stock'];
+            $total_pa+=$row['pa_stock'];
+            $total_pmp_actual+=$row['pmp_actual'];
+            $total_pa_actual+=$row['pa_actual'];
+            
+			if($i%20 === 0)
+			{
+            	_headerList($view);
+			} // Fin IF principal
+	    	?>
+			<tr style="background-color:<?php echo ($k%2 == 0) ? '#fff':'#eee'; ?>;">
+				<td align="left">&nbsp;&nbsp;<?php echo $row['produit']; ?></td>
+				<td align="center"><?php echo $row['entrepot']; ?></td>
+				<?php if (! empty($conf->barcode->enabled)) { ?>
+					<td align="center"><?php echo $row['barcode']; ?></td>
+				<?php } ?>
+				<?php if ($can_validate == 1) { ?>
+					<td align="center" style="background-color: #e8e8ff;"><?php echo $row['qty_stock']; ?></td>
+					<td align="right" style="background-color: #e8e8ff;"><?php echo price( $row['pmp_stock']); ?></td>
+					<td align="right" style="background-color: #e8e8ff;"><?php echo price( $row['pa_stock']); ?></td>
+	               <?php
+	                 if(!empty($conf->global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)){
+	                 	echo '<td align="right" style="background-color: #e8e8ff;">'.price($row['current_pa_stock']).'</td>';
+						 $total_current_pa+=$row['current_pa_stock'];
+	                 }   
+	                    
+	               ?>
+				<?php } ?>
+				<td align="center"><?php echo $row['qty']; ?>&nbsp;&nbsp;<span id="qty_view_<?php echo $row['k']; ?>"><?php echo $row['qty_view']; ?></span>
+                    <input type="hidden" name="det_id_<?php echo $row['k']; ?>" value="<?php echo $row['id']; ?>" /> 
+                </td>
+                <?php if ($can_validate == 1) { ?>
+                    <td align="right"><?php echo price($row['pmp_actual']); ?></td>
+                    <?php
+                    if(!empty($user->rights->stock->changePMP)) {
+                    	echo '<td align="right">'.$row['pmp_new'].'</td>';	
+					}
+                    ?>
+                    <td align="right"><?php echo price($row['pa_actual']); ?></td>
+		               <?php
+		                 if(!empty($conf->global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)){
+		                 	echo '<td align="right">'.price($row['current_pa_actual']).'</td>';
+							 $total_current_pa_actual+=$row['current_pa_actual'];
+		                 }   
+		                    
+		               ?>
+                    <td align="center"><?php echo $row['qty_regulated']; ?></td>
+				<?php } ?>
+				<?php if ($view['is_already_validate'] != 1) { ?>
+					<td align="center" width="20%"><?php echo $row['action']; ?></td>
+				<?php } ?>
+			</tr>
+			<?php $i++; 
+        
+        } 
+		
+		_footerList($view,$total_pmp,$total_pmp_actual,$total_pa,$total_pa_actual, $total_current_pa,$total_current_pa_actual);
+	
+		?>
+	</table>
+	
+	<?php if ($object->status != 1) { ?>
+		<div class="tabsAction" style="height:30px;">
+			<?php if ($action!= 'edit') { ?>
+				<!-- <a href="<?php echo $view_url; ?>?id=<?php echo $object->id; ?>&action=exportCSV" class="butAction"><?php echo $langs->trans('ExportCSV') ?></a> -->
+				<a href="<?php echo $view_url; ?>?id=<?php echo $object->id; ?>&action=edit" class="butAction"><?php echo $langs->trans('Modify') ?></a>
+				<?php 
+				 if(!empty($user->rights->stock->changePMP)) {
+				 	echo '<a href="'.$view_url.'?id='.$object->id.'&action=changePMP" class="butAction">'.$langs->trans('ApplyPMP').'</a>';
+				 }
+				
+				if ($can_validate == 1) { ?>
+					<a href="<?php echo $view_url; ?>?id=<?php echo $object->id; ?>&action=regulate&token=" class="butAction"><?php echo $langs->trans('RegulateStock') ?></a>
+				<?php } ?>
+			<?php } ?>
+			<?php if ($action == 'edit') { ?>
+				<input name="back" type="button" class="butAction" value="<?php echo $langs->trans('ExitEditMode'); ?>" onclick="document.location='?id=<?php echo $object->id; ?>&action=view';" />
+			<?php } ?>
+			<?php if ($can_validate == 1) { ?>
+                <a href="<?php echo $view_url; ?>?id=<?php echo $object->id; ?>&action=flush" class="butActionDelete"><?php  echo $langs->trans('Flush'); ?></a>
+                &nbsp;&nbsp;&nbsp;
+                <a href="<?php echo $view_url; ?>?id=<?php echo $object->id; ?>&action=delete" class="butActionDelete"><?php echo $langs->trans('Delete') ?></a>
+        	<?php } ?>
+		</div>
+	<?php } ?>
+	<?php if ($object->status == 1) { ?>
+		<div class="tabsAction">
+			<?php if ($can_validate == 1) { ?>
+
+				<!-- <a href="<?php echo $view_url; ?>?id=<?php echo $object->id; ?>&action=exportCSV" class="butAction"><?php echo $langs->trans('ExportCSV') ?></a> -->
+				<a href="#" title="<?php echo $langs->trans('InventoryAlreadyValidated'); ?>" class="butActionRefused"><?php echo $langs->trans('Delete') ?></a>
+				
+			<?php } ?>
+		</div>
+	<?php } ?>
+</form>
+<p>Date de création : <?php echo $object->getDate('datec') ?>
+<br />Dernière mise à jour : <?php echo $object->getDate('tms') ?></p>
+	
+
+	
diff --git a/htdocs/product/traduction.php b/htdocs/product/traduction.php
index b5f4b8b34ae02514f11ce2b6ac396326f5ca6c11..03f7e1c54acd31c052930ac480d5f6b6087dd42a 100644
--- a/htdocs/product/traduction.php
+++ b/htdocs/product/traduction.php
@@ -277,16 +277,14 @@ if ($action == 'edit')
 }
 else if ($action != 'add')
 {
-    //if ($cnt_trans) print '<div class="underbanner clearboth"></div>';
-    
 	if (! empty($object->multilangs))
 	{
 		foreach ($object->multilangs as $key => $value)
 		{
 			$s=picto_from_langcode($key);
-			//print '<tr><td>';
 			print ($s?$s.' ':'')." <b>".$langs->trans('Language_'.$key).":</b> ".'<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=delete&langtodelete='.$key.'">'.img_delete('', 'class="valigntextbottom"').'</a>';
-			//print '</td><td></td></tr>';
+			
+			print '<div class="fichecenter">';
 			print '<div class="underbanner clearboth"></div>';
 			print '<table class="border" width="100%">';
 			print '<tr><td class="titlefieldcreate">'.$langs->trans('Label').'</td><td>'.$object->multilangs[$key]["label"].'</td></tr>';
@@ -296,6 +294,7 @@ else if ($action != 'add')
                 print '<tr><td>'.$langs->trans('Other').' ('.$langs->trans("NotUsed").')</td><td>'.$object->multilangs[$key]["other"].'</td></tr>';
 			}
 			print '</table>';
+			print '</div>';
 		}
 	}
 	if (! $cnt_trans && $action != 'add') print '<div class="opacitymedium">'. $langs->trans('NoTranslation').'</div>';
diff --git a/htdocs/projet/activity/perday.php b/htdocs/projet/activity/perday.php
index c50cbd014f7e520d77f71fceff1355f5de44b78d..c1aa8aaa469d12b92d9d021e239456e964a24cad 100644
--- a/htdocs/projet/activity/perday.php
+++ b/htdocs/projet/activity/perday.php
@@ -407,25 +407,7 @@ print '<div class="clearboth" style="padding-bottom: 8px;"></div>';
 print '<div class="div-table-responsive">';
 print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'" id="tablelines3">'."\n";
 
-print '<tr class="liste_titre">';
-print '<td>'.$langs->trans("RefTask").'</td>';
-print '<td>'.$langs->trans("LabelTask").'</td>';
-print '<td>'.$langs->trans("ProjectRef").'</td>';
-if (! empty($conf->global->PROJECT_LINES_PERDAY_SHOW_THIRDPARTY))
-{
-    print '<td>'.$langs->trans("ThirdParty").'</td>';
-}
-print '<td align="right" class="maxwidth100">'.$langs->trans("PlannedWorkload").'</td>';
-print '<td align="right" class="maxwidth100">'.$langs->trans("ProgressDeclared").'</td>';
-print '<td align="right" class="maxwidth100">'.$langs->trans("TimeSpent").'</td>';
-if ($usertoprocess->id == $user->id) print '<td align="right" class="maxwidth100">'.$langs->trans("TimeSpentByYou").'</td>';
-else print '<td align="right" class="maxwidth100">'.$langs->trans("TimeSpentByUser").'</td>';
-print '<td align="center">'.$langs->trans("HourStart").'</td>';
-print '<td align="center" colspan="2">'.$langs->trans("Duration").'</td>';
-print '<td align="right">'.$langs->trans("Note").'</td>';
-print "</tr>\n";
-
-print '<tr class="liste_titre">';
+print '<tr class="liste_titre_filter">';
 print '<td class="liste_titre"><input type="text" size="4" name="search_task_ref" value="'.dol_escape_htmltag($search_task_ref).'"></td>';
 print '<td class="liste_titre"><input type="text" size="4" name="search_task_label" value="'.dol_escape_htmltag($search_task_label).'"></td>';
 print '<td class="liste_titre"><input type="text" size="4" name="search_project_ref" value="'.dol_escape_htmltag($search_project_ref).'"></td>';
@@ -444,6 +426,24 @@ print $searchpitco;
 print '</td>';
 print "</tr>\n";
 
+print '<tr class="liste_titre">';
+print '<td>'.$langs->trans("RefTask").'</td>';
+print '<td>'.$langs->trans("LabelTask").'</td>';
+print '<td>'.$langs->trans("ProjectRef").'</td>';
+if (! empty($conf->global->PROJECT_LINES_PERDAY_SHOW_THIRDPARTY))
+{
+    print '<td>'.$langs->trans("ThirdParty").'</td>';
+}
+print '<td align="right" class="maxwidth100">'.$langs->trans("PlannedWorkload").'</td>';
+print '<td align="right" class="maxwidth100">'.$langs->trans("ProgressDeclared").'</td>';
+print '<td align="right" class="maxwidth100">'.$langs->trans("TimeSpent").'</td>';
+if ($usertoprocess->id == $user->id) print '<td align="right" class="maxwidth100">'.$langs->trans("TimeSpentByYou").'</td>';
+else print '<td align="right" class="maxwidth100">'.$langs->trans("TimeSpentByUser").'</td>';
+print '<td align="center">'.$langs->trans("HourStart").'</td>';
+print '<td align="center" colspan="2">'.$langs->trans("Duration").'</td>';
+print '<td align="right">'.$langs->trans("Note").'</td>';
+print "</tr>\n";
+
 
 // By default, we can edit only tasks we are assigned to
 $restrictviewformytask=(empty($conf->global->PROJECT_TIME_SHOW_TASK_NOT_ASSIGNED)?1:0);
diff --git a/htdocs/projet/activity/perweek.php b/htdocs/projet/activity/perweek.php
index 989424afd671f7682b11191bb2f404dcf3dbdbec..905b93393dd2f4108bcb120037671fec044a34ec 100644
--- a/htdocs/projet/activity/perweek.php
+++ b/htdocs/projet/activity/perweek.php
@@ -402,6 +402,26 @@ print '<div class="clearboth" style="padding-bottom: 8px;"></div>';
 print '<div class="div-table-responsive">';
 print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'" id="tablelines3">'."\n";
 
+print '<tr class="liste_titre_filter">';
+print '<td class="liste_titre"><input type="text" size="4" name="search_task_ref" value="'.dol_escape_htmltag($search_task_ref).'"></td>';
+print '<td class="liste_titre"><input type="text" size="4" name="search_task_label" value="'.dol_escape_htmltag($search_task_label).'"></td>';
+print '<td class="liste_titre"><input type="text" size="4" name="search_project_ref" value="'.dol_escape_htmltag($search_project_ref).'"></td>';
+if (! empty($conf->global->PROJECT_LINES_PERWEEK_SHOW_THIRDPARTY)) print '<td class="liste_titre"><input type="text" size="4" name="search_thirdparty" value="'.dol_escape_htmltag($search_thirdparty).'"></td>';
+print '<td class="liste_titre"></td>';
+print '<td class="liste_titre"></td>';
+print '<td class="liste_titre"></td>';
+print '<td class="liste_titre"></td>';
+for($i=0;$i<7;$i++)
+{
+    print '<td class="liste_titre"></td>';
+}
+// Action column
+print '<td class="liste_titre nowrap" align="right">';
+$searchpitco=$form->showFilterAndCheckAddButtons(0);
+print $searchpitco;
+print '</td>';
+print "</tr>\n";
+
 print '<tr class="liste_titre">';
 print '<td>'.$langs->trans("RefTask").'</td>';
 print '<td>'.$langs->trans("LabelTask").'</td>';
@@ -425,26 +445,6 @@ for($i=0;$i<7;$i++)
 print '<td></td>';
 print "</tr>\n";
 
-print '<tr class="liste_titre">';
-print '<td class="liste_titre"><input type="text" size="4" name="search_task_ref" value="'.dol_escape_htmltag($search_task_ref).'"></td>';
-print '<td class="liste_titre"><input type="text" size="4" name="search_task_label" value="'.dol_escape_htmltag($search_task_label).'"></td>';
-print '<td class="liste_titre"><input type="text" size="4" name="search_project_ref" value="'.dol_escape_htmltag($search_project_ref).'"></td>';
-if (! empty($conf->global->PROJECT_LINES_PERWEEK_SHOW_THIRDPARTY)) print '<td class="liste_titre"><input type="text" size="4" name="search_thirdparty" value="'.dol_escape_htmltag($search_thirdparty).'"></td>';
-print '<td class="liste_titre"></td>';
-print '<td class="liste_titre"></td>';
-print '<td class="liste_titre"></td>';
-print '<td class="liste_titre"></td>';
-for($i=0;$i<7;$i++)
-{
-    print '<td class="liste_titre"></td>';
-}
-// Action column
-print '<td class="liste_titre nowrap" align="right">';
-$searchpitco=$form->showFilterAndCheckAddButtons(0);
-print $searchpitco;
-print '</td>';
-print "</tr>\n";
-
 // By default, we can edit only tasks we are assigned to
 $restrictviewformytask=(empty($conf->global->PROJECT_TIME_SHOW_TASK_NOT_ASSIGNED)?1:0);
 
diff --git a/htdocs/societe/admin/contact_extrafields.php b/htdocs/societe/admin/contact_extrafields.php
index 37db7d02e4c8214983a418f4f7324e4c56f76179..2a60252f7f8ebfddf8fed81a22ff2f466be25c48 100644
--- a/htdocs/societe/admin/contact_extrafields.php
+++ b/htdocs/societe/admin/contact_extrafields.php
@@ -70,7 +70,7 @@ print load_fiche_titre($langs->trans("CompanySetup"),$linkback,'title_setup');
 
 $head = societe_admin_prepare_head();
 
-dol_fiche_head($head, 'attributes_contacts', $langs->trans("ThirdParties"), 0, 'company');
+dol_fiche_head($head, 'attributes_contacts', $langs->trans("ThirdParties"), -1, 'company');
 
 require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_view.tpl.php';
 
diff --git a/htdocs/societe/admin/societe.php b/htdocs/societe/admin/societe.php
index 517672d14ed738a9b870351b04d67a5478c4c33b..63ba12197fddaa32967425566930404b41eaeffe 100644
--- a/htdocs/societe/admin/societe.php
+++ b/htdocs/societe/admin/societe.php
@@ -307,7 +307,7 @@ print load_fiche_titre($langs->trans("CompanySetup"),$linkback,'title_setup');
 
 $head = societe_admin_prepare_head();
 
-dol_fiche_head($head, 'general', $langs->trans("ThirdParties"), 0, 'company');
+dol_fiche_head($head, 'general', $langs->trans("ThirdParties"), -1, 'company');
 
 $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
 
diff --git a/htdocs/societe/admin/societe_extrafields.php b/htdocs/societe/admin/societe_extrafields.php
index 89f44d53aa78ce1f971d28f59ca80ec9b32e0ce5..a722ec61b863d9a829a2418ee537ab7bc261c81e 100644
--- a/htdocs/societe/admin/societe_extrafields.php
+++ b/htdocs/societe/admin/societe_extrafields.php
@@ -71,7 +71,7 @@ print load_fiche_titre($langs->trans("CompanySetup"),$linkback,'title_setup');
 
 $head = societe_admin_prepare_head();
 
-dol_fiche_head($head, 'attributes', $langs->trans("ThirdParties"), 0, 'company');
+dol_fiche_head($head, 'attributes', $langs->trans("ThirdParties"), -1, 'company');
 
 require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_view.tpl.php';
 
diff --git a/htdocs/societe/card.php b/htdocs/societe/card.php
index bb043076157c5374507b6e5e37b6fd614c95d613..ca09825f62a9bee66131153a5d0c8fa437bdf585 100644
--- a/htdocs/societe/card.php
+++ b/htdocs/societe/card.php
@@ -1743,7 +1743,7 @@ else
             //TODO: Place into a function to control showing by country or study better option
             if($mysoc->localtax1_assuj=="1" && $mysoc->localtax2_assuj=="1")
             {
-                print '<tr><td>'.fieldLabel($langs->transcountry("LocalTax1IsUsed",$mysoc->country_code),'localtax1assuj_value').'</td><td colspan="3">';
+                print '<tr><td>'.fieldLabel($langs->transcountry("LocalTax1IsUsed",$mysoc->country_code),'localtax1assuj_value').'</td><td>';
                 print $form->selectyesno('localtax1assuj_value',$object->localtax1_assuj,1);
                 if(! isOnlyOneLocalTax(1))
                 {
@@ -1752,7 +1752,7 @@ else
                     print '</span>';
                 }
             
-                print '</td><td>'.fieldLabel($langs->transcountry("LocalTax2IsUsed",$mysoc->country_code),'localtax2assuj_value').'</td><td colspan="3">';
+                print '</td><td>'.fieldLabel($langs->transcountry("LocalTax2IsUsed",$mysoc->country_code),'localtax2assuj_value').'</td><td>';
                 print $form->selectyesno('localtax2assuj_value',$object->localtax2_assuj,1);
                 if  (! isOnlyOneLocalTax(2))
                 {
diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php
index 74aef09e7a992ae2d0ff8e11259490aeea63cc83..0581ed1960e1d23055a16c3f00f9796465134247 100644
--- a/htdocs/societe/class/societe.class.php
+++ b/htdocs/societe/class/societe.class.php
@@ -3326,18 +3326,6 @@ class Societe extends CommonObject
 		return "Error, mode/status not found";
 	}
 
-	/**
-	 *  Set commnunication level
-	 *
-	 *  @param  User	$user		User making change
-	 *	@return	int					<0 if KO, >0 if OK
-     * @deprecated Use update function instead
-	 */
-	function set_commnucation_level($user)
-	{
-		return $this->update($this->id, $user);
-	}
-
 	/**
 	 *  Set outstanding value
 	 *
diff --git a/htdocs/societe/societecontact.php b/htdocs/societe/societecontact.php
index 2bda75867dc8534bec1799b325c32970f339e294..b5ffc87517ff57bb910cd05eb5cb4ddcb7dccd11 100644
--- a/htdocs/societe/societecontact.php
+++ b/htdocs/societe/societecontact.php
@@ -107,13 +107,14 @@ else if ($action == 'deletecontact' && $user->rights->societe->creer)
 		dol_print_error($db);
 	}
 }
-
+/*
 else if ($action == 'setaddress' && $user->rights->societe->creer)
 {
 	$object->fetch($id);
 	$result=$object->setDeliveryAddress($_POST['fk_address']);
 	if ($result < 0) dol_print_error($db,$object->error);
-}
+}*/
+
 
 /*
  * View
diff --git a/htdocs/supplier_proposal/card.php b/htdocs/supplier_proposal/card.php
index 0bac6dab14f14ecb9f59095959a99f9642163603..d36b471a721217f48be492c4de4a63772e86b77e 100644
--- a/htdocs/supplier_proposal/card.php
+++ b/htdocs/supplier_proposal/card.php
@@ -1,6 +1,6 @@
 <?php
 /* Copyright (C) 2001-2007 Rodolphe Quiedeville  <rodolphe@quiedeville.org>
- * Copyright (C) 2004-2016 Laurent Destailleur   <eldy@users.sourceforge.net>
+ * Copyright (C) 2004-2017 Laurent Destailleur   <eldy@users.sourceforge.net>
  * Copyright (C) 2004      Eric Seigne           <eric.seigne@ryxeo.com>
  * Copyright (C) 2005      Marc Barilley / Ocebo <marc@ocebo.com>
  * Copyright (C) 2005-2012 Regis Houssin         <regis.houssin@capnetworks.com>
@@ -261,7 +261,7 @@ if (empty($reshook))
 					$object->modelpdf = GETPOST('model');
 					$object->author = $user->id; // deprecated
 					$object->note = GETPOST('note');
-					$object->statut = 0;
+					$object->statut = SupplierProposal::STATUS_DRAFT;
 
 					$id = $object->create_from($user);
 				} else {
@@ -436,16 +436,16 @@ if (empty($reshook))
 	// Reopen proposal
 	else if ($action == 'confirm_reopen' && $user->rights->supplier_proposal->cloturer && ! GETPOST('cancel')) {
 		// prevent browser refresh from reopening proposal several times
-		if ($object->statut == 2 || $object->statut == 3 || $object->statut == 4) {
-			$object->reopen($user, 1);
+		if ($object->statut == SupplierProposal::STATUS_SIGNED || $object->statut == SupplierProposal::STATUS_NOTSIGNED || $object->statut == SupplierProposal::STATUS_CLOSE) {
+			$object->reopen($user, SupplierProposal::STATUS_VALIDATED);
 		}
 	}
 
 	// Close proposal
 	else if ($action == 'close' && $user->rights->supplier_proposal->cloturer && ! GETPOST('cancel')) {
-		// prevent browser refresh from reopening proposal several times
-		if ($object->statut == 2) {
-			$object->setStatut(4);
+	    // prevent browser refresh from reopening proposal several times
+	    if ($object->statut == SupplierProposal::STATUS_SIGNED) {
+			$object->setStatut(SupplierProposal::STATUS_CLOSE);
 		}
 	}
 
@@ -456,19 +456,15 @@ if (empty($reshook))
 			$action = 'statut';
 		} else {
 			// prevent browser refresh from closing proposal several times
-			if ($object->statut == 1) {
+			if ($object->statut == SupplierProposal::STATUS_VALIDATED) {
                 $object->cloture($user, GETPOST('statut'), GETPOST('note'));
 			}
 		}
 	}
 
+	// Action for direct print
 	include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
 
-
-	/*
-	 * Send mail
-	 */
-
 	// Actions to send emails
 	$actiontypecode='AC_ASKPRICE';
 	$trigger_name='SUPPLIER_PROPOSAL_SENTBYMAIL';
@@ -1243,7 +1239,7 @@ if ($action == 'create')
 		$sql .= ", " . MAIN_DB_PREFIX . "societe s";
 		$sql .= " WHERE s.rowid = p.fk_soc";
 		$sql .= " AND p.entity = " . $conf->entity;
-		$sql .= " AND p.fk_statut <> 0";
+		$sql .= " AND p.fk_statut <> ".SupplierProposal::STATUS_DRAFT;
 		$sql .= " ORDER BY Id";
 
 		$resql = $db->query($sql);
@@ -1530,6 +1526,7 @@ if ($action == 'create')
 		print '</td></tr>';
 	}
 
+	/* Not for supplier proposals
 	if ($soc->outstanding_limit)
 	{
 		// Outstanding Bill
@@ -1540,7 +1537,7 @@ if ($action == 'create')
 		print price($soc->outstanding_limit, 0, '', 1, - 1, - 1, $conf->currency);
 		print '</td>';
 		print '</tr>';
-	}
+	}*/
 
 	if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_PROPOSAL) && ! empty($conf->banque->enabled))
 	{
@@ -1661,7 +1658,7 @@ if ($action == 'create')
 	<input type="hidden" name="id" value="' . $object->id . '">
 	';
 
-	if (! empty($conf->use_javascript_ajax) && $object->statut == 0) {
+	if (! empty($conf->use_javascript_ajax) && $object->statut == SupplierProposal::STATUS_DRAFT) {
 		include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php';
 	}
 
@@ -1676,12 +1673,10 @@ if ($action == 'create')
 		$ret = $object->printObjectLines($action, $soc, $mysoc, $lineid, 1);
 
 	// Form to add new line
-	if ($object->statut == 0 && $user->rights->supplier_proposal->creer)
+	if ($object->statut == SupplierProposal::STATUS_DRAFT && $user->rights->supplier_proposal->creer)
 	{
 		if ($action != 'editline')
 		{
-			$var = true;
-
 			// Add products/services form
 			$object->formAddObjectLine(1, $soc, $mysoc);
 
@@ -1738,7 +1733,7 @@ if ($action == 'create')
 			if ($action != 'statut' && $action != 'editline')
 			{
 				// Validate
-				if ($object->statut == 0 && $object->total_ttc >= 0 && count($object->lines) > 0 &&
+				if ($object->statut == SupplierProposal::STATUS_DRAFT && $object->total_ttc >= 0 && count($object->lines) > 0 &&
 			        ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->supplier_proposal->creer))
        				|| (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->supplier_proposal->validate_advance)))
 				) {
@@ -1748,18 +1743,18 @@ if ($action == 'create')
 				}
 
 				// Edit
-				if ($object->statut == 1 && $user->rights->supplier_proposal->creer) {
+				if ($object->statut == SupplierProposal::STATUS_VALIDATED && $user->rights->supplier_proposal->creer) {
 					print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&amp;action=modif">' . $langs->trans('Modify') . '</a></div>';
 				}
 
 				// ReOpen
-				if (($object->statut == 2 || $object->statut == 3 || $object->statut == 4) && $user->rights->supplier_proposal->cloturer) {
+				if (($object->statut == SupplierProposal::STATUS_SIGNED || $object->statut == SupplierProposal::STATUS_NOTSIGNED || $object->statut == SupplierProposal::STATUS_CLOSE) && $user->rights->supplier_proposal->cloturer) {
 					print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&amp;action=reopen' . (empty($conf->global->MAIN_JUMP_TAG) ? '' : '#reopen') . '"';
 					print '>' . $langs->trans('ReOpen') . '</a></div>';
 				}
 
 				// Send
-				if ($object->statut == 1 || $object->statut == 2) {
+				if ($object->statut == SupplierProposal::STATUS_VALIDATED || $object->statut == SupplierProposal::STATUS_SIGNED) {
 					if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->supplier_proposal->send_advance) {
 						print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&amp;action=presend&amp;mode=init">' . $langs->trans('SendByMail') . '</a></div>';
 					} else
@@ -1767,20 +1762,20 @@ if ($action == 'create')
 				}
 
 				// Create an order
-				if (! empty($conf->commande->enabled) && $object->statut == 2) {
+				if (! empty($conf->commande->enabled) && $object->statut == SupplierProposal::STATUS_SIGNED) {
 					if ($user->rights->fournisseur->commande->creer) {
 						print '<div class="inline-block divButAction"><a class="butAction" href="' . DOL_URL_ROOT . '/fourn/commande/card.php?action=create&amp;origin=' . $object->element . '&amp;originid=' . $object->id . '&amp;socid=' . $object->socid . '">' . $langs->trans("AddOrder") . '</a></div>';
 					}
 				}
 
 				// Set accepted/refused
-				if ($object->statut == 1 && $user->rights->supplier_proposal->cloturer) {
+				if ($object->statut == SupplierProposal::STATUS_VALIDATED && $user->rights->supplier_proposal->cloturer) {
 					print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&amp;action=statut' . (empty($conf->global->MAIN_JUMP_TAG) ? '' : '#acceptedrefused') . '"';
 					print '>' . $langs->trans('SetAcceptedRefused') . '</a></div>';
 				}
 
 				// Close
-				if ($object->statut == 2 && $user->rights->supplier_proposal->cloturer) {
+				if ($object->statut == SupplierProposal::STATUS_SIGNED && $user->rights->supplier_proposal->cloturer) {
 				    print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&amp;action=close' . (empty($conf->global->MAIN_JUMP_TAG) ? '' : '#close') . '"';
 				    print '>' . $langs->trans('Close') . '</a></div>';
 				}
@@ -1791,7 +1786,7 @@ if ($action == 'create')
 				}
 
 				// Delete
-				if (($object->statut == 0 && $user->rights->supplier_proposal->creer) || $user->rights->supplier_proposal->supprimer) {
+				if (($object->statut == SupplierProposal::STATUS_DRAFT && $user->rights->supplier_proposal->creer) || $user->rights->supplier_proposal->supprimer) {
 					print '<div class="inline-block divButAction"><a class="butActionDelete" href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&amp;action=delete"';
 					print '>' . $langs->trans('Delete') . '</a></div>';
 				}
@@ -1814,8 +1809,6 @@ if ($action == 'create')
 		$genallowed = $user->rights->supplier_proposal->creer;
 		$delallowed = $user->rights->supplier_proposal->supprimer;
 
-		$var = true;
-
 		print $formfile->showdocuments('supplier_proposal', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang);
 
 		
@@ -1862,6 +1855,7 @@ if ($action == 'create')
 			$outputlangs = new Translate('', $conf);
 			$outputlangs->setDefaultLang($newlang);
 			$outputlangs->load('commercial');
+			$outputlangs->load('supplier_proposal');
 		}
 
 		// Build document if it not exists
diff --git a/htdocs/supplier_proposal/class/supplier_proposal.class.php b/htdocs/supplier_proposal/class/supplier_proposal.class.php
index 65efb97f824c0df9d14ece861689f84bf4ac1d53..00ca20bcd5a2cfb0cb0107e8734257936270b19e 100644
--- a/htdocs/supplier_proposal/class/supplier_proposal.class.php
+++ b/htdocs/supplier_proposal/class/supplier_proposal.class.php
@@ -154,13 +154,13 @@ class SupplierProposal extends CommonObject
 	 */
 	const STATUS_SIGNED = 2;
 	/**
-	 * Not signed quote
+	 * Not signed quote, canceled
 	 */
 	const STATUS_NOTSIGNED = 3;
 	/**
-	 * Billed or processed quote
+	 * Billed or closed/processed quote
 	 */
-	const STATUS_BILLED = 4;	
+	const STATUS_CLOSE = 4;	
 	
 	
 	
@@ -1143,9 +1143,8 @@ class SupplierProposal extends CommonObject
                 $this->note                 = $obj->note_private; // TODO deprecated
                 $this->note_private         = $obj->note_private;
                 $this->note_public          = $obj->note_public;
-                $this->statut               = $obj->fk_statut;
+                $this->statut               = (int) $obj->fk_statut;
                 $this->statut_libelle       = $obj->statut_label;
-
                 $this->datec                = $this->db->jdate($obj->datec); // TODO deprecated
                 $this->datev                = $this->db->jdate($obj->datev); // TODO deprecated
                 $this->date_creation		= $this->db->jdate($obj->datec); //Creation date
@@ -2836,7 +2835,7 @@ class SupplierProposalLine  extends CommonObjectLine
         $sql.= " ".price2num($this->localtax2_tx).",";
 		$sql.= " '".$this->localtax1_type."',";
 		$sql.= " '".$this->localtax2_type."',";
-        $sql.= " ".($this->subprice?price2num($this->subprice):"null").",";
+        $sql.= " ".price2num($this->subprice).",";
         $sql.= " ".price2num($this->remise_percent).",";
         $sql.= " ".(isset($this->info_bits)?"'".$this->info_bits."'":"null").",";
         $sql.= " ".price2num($this->total_ht).",";
@@ -2855,7 +2854,7 @@ class SupplierProposalLine  extends CommonObjectLine
 		$sql.= ", ".$this->multicurrency_total_ht;
 		$sql.= ", ".$this->multicurrency_total_tva;
 		$sql.= ", ".$this->multicurrency_total_ttc;
-		$sql.= ", ".$this->fk_unit;
+        $sql.= ", fk_unit=".($this->fk_unit?$this->fk_unit:'null');
 		$sql.= ')';
 
         dol_syslog(get_class($this).'::insert', LOG_DEBUG);
@@ -3025,13 +3024,13 @@ class SupplierProposalLine  extends CommonObjectLine
         $sql.= " , fk_parent_line=".($this->fk_parent_line>0?$this->fk_parent_line:"null");
         if (! empty($this->rang)) $sql.= ", rang=".$this->rang;
         $sql.= " , ref_fourn=".(! empty($this->ref_fourn)?"'".$this->db->escape($this->ref_fourn)."'":"null");
-		
+        $sql.= " , fk_unit=".($this->fk_unit?$this->fk_unit:'null');
+        
 		// Multicurrency
 		$sql.= " , multicurrency_subprice=".price2num($this->multicurrency_subprice)."";
         $sql.= " , multicurrency_total_ht=".price2num($this->multicurrency_total_ht)."";
         $sql.= " , multicurrency_total_tva=".price2num($this->multicurrency_total_tva)."";
         $sql.= " , multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc)."";
-        $sql.= " , fk_unit=".$this->fk_unit;
 		
 		$sql.= " WHERE rowid = ".$this->rowid;
 
diff --git a/htdocs/theme/dolibarr_logo.png b/htdocs/theme/dolibarr_logo.png
old mode 100644
new mode 100755
index 3ee46b5155303f5f03b05594070a6c076e773636..5287d9dcc25bc48dddcc351dd4aa64fd83322463
Binary files a/htdocs/theme/dolibarr_logo.png and b/htdocs/theme/dolibarr_logo.png differ
diff --git a/htdocs/theme/doliforge_logo.png b/htdocs/theme/doliforge_logo.png
deleted file mode 100644
index c9de1b5012c45670d346b4f699a01ab8d257d415..0000000000000000000000000000000000000000
Binary files a/htdocs/theme/doliforge_logo.png and /dev/null differ
diff --git a/htdocs/theme/eldy/graph-color.php b/htdocs/theme/eldy/graph-color.php
index 5995303c34a1b0b3f1265c170a8f19641c74704b..920fa7833affcc44ef9296c88197e688750eef8c 100644
--- a/htdocs/theme/eldy/graph-color.php
+++ b/htdocs/theme/eldy/graph-color.php
@@ -28,7 +28,7 @@
 
 global $theme_bordercolor, $theme_datacolor, $theme_bgcolor, $theme_bgcoloronglet;
 $theme_bordercolor = array(235,235,224);
-$theme_datacolor = array(array(136,102,136), array(140,140,220), array(190,120,120), array(0,160,140), array(190,190,100), array(115,125,150), array(100,170,20), array(250,190,30), array(150,135,125), array(85,135,150), array(150,135,80), array(150,80,150));
+$theme_datacolor = array(array(136,102,136), array(0,130,110), array(140,140,220), array(190,120,120), array(190,190,100), array(115,125,150), array(100,170,20), array(250,190,30), array(150,135,125), array(85,135,150), array(150,135,80), array(150,80,150));
 $theme_bgcolor = array(hexdec('F4'),hexdec('F4'),hexdec('F4'));
 $theme_bgcoloronglet = array(hexdec('DE'),hexdec('E7'),hexdec('EC'));
 
diff --git a/htdocs/theme/eldy/style.css.php b/htdocs/theme/eldy/style.css.php
index ebb3ee4184cbe7fb117c61bfa44d244997e093e3..d03707c945f536cab2b4984a0110b4b511563070 100644
--- a/htdocs/theme/eldy/style.css.php
+++ b/htdocs/theme/eldy/style.css.php
@@ -90,10 +90,10 @@ $colorbacklinepair1='248,248,248';    // line pair
 $colorbacklinepair2='248,248,248';    // line pair
 $colorbacklinepairhover='238,246,252';    // line pair
 $colorbackbody='255,255,255';
-$colortexttitlenotab='60,60,20';
+$colortexttitlenotab='100,60,20';
 $colortexttitle='0,0,0';
 $colortext='0,0,0';
-$colortextlink='0,0,120';
+$colortextlink='0,0,100';
 $fontsize='13';
 $fontsizesmaller='12';
 $useboldtitle=(isset($conf->global->THEME_ELDY_USEBOLDTITLE)?$conf->global->THEME_ELDY_USEBOLDTITLE:1);
@@ -155,25 +155,25 @@ if (! empty($user->conf->THEME_ELDY_ENABLE_PERSONALIZED))
 
 // Set text color to black or white
 $tmppart=explode(',',$colorbackhmenu1);
-$tmpval=(! empty($tmppart[0]) ? $tmppart[0] : '')+(! empty($tmppart[1]) ? $tmppart[1] : '')+(! empty($tmppart[2]) ? $tmppart[2] : '');
+$tmpval=(! empty($tmppart[0]) ? $tmppart[0] : 0)+(! empty($tmppart[1]) ? $tmppart[1] : 0)+(! empty($tmppart[2]) ? $tmppart[2] : 0);
 if ($tmpval <= 460) $colortextbackhmenu='FFFFFF';
 else $colortextbackhmenu='000000';
 
 $tmppart=explode(',',$colorbackvmenu1);
-$tmpval=(! empty($tmppart[0]) ? $tmppart[0] : '')+(! empty($tmppart[1]) ? $tmppart[1] : '')+(! empty($tmppart[2]) ? $tmppart[2] : '');
+$tmpval=(! empty($tmppart[0]) ? $tmppart[0] : 0)+(! empty($tmppart[1]) ? $tmppart[1] : 0)+(! empty($tmppart[2]) ? $tmppart[2] : 0);
 if ($tmpval <= 460) { $colortextbackvmenu='FFFFFF'; }
 else { $colortextbackvmenu='000000'; }
 
 $tmppart=explode(',',$colorbacktitle1);
 if ($colortexttitle == '')
 {
-    $tmpval=(! empty($tmppart[0]) ? $tmppart[0] : '')+(! empty($tmppart[1]) ? $tmppart[1] : '')+(! empty($tmppart[2]) ? $tmppart[2] : '');
+    $tmpval=(! empty($tmppart[0]) ? $tmppart[0] : 0)+(! empty($tmppart[1]) ? $tmppart[1] : 0)+(! empty($tmppart[2]) ? $tmppart[2] : 0);
     if ($tmpval <= 460) { $colortexttitle='FFFFFF'; $colorshadowtitle='888888'; }
     else { $colortexttitle='000000'; $colorshadowtitle='FFFFFF'; }
 }
 
 $tmppart=explode(',',$colorbacktabcard1);
-$tmpval=(! empty($tmppart[0]) ? $tmppart[0] : '')+(! empty($tmppart[1]) ? $tmppart[1] : '')+(! empty($tmppart[2]) ? $tmppart[2] : '');
+$tmpval=(! empty($tmppart[0]) ? $tmppart[0] : 0)+(! empty($tmppart[1]) ? $tmppart[1] : 0)+(! empty($tmppart[2]) ? $tmppart[2] : 0);
 if ($tmpval <= 460) { $colortextbacktab='FFFFFF'; }
 else { $colortextbacktab='111111'; }
 
@@ -935,7 +935,7 @@ div.blockvmenuend, div.blockvmenubookmarks {
 	padding-left: 0 !important;
 }
 div.vmenu, td.vmenu {
-	padding-right: 6px !important;
+	padding-right: 10px !important;
 }
 
 
@@ -988,7 +988,11 @@ div.fiche {
 	<?php if (! empty($conf->dol_hide_leftmenu) && ! empty($conf->dol_hide_topmenu)) print 'margin-top: 4px;'."\n"; ?>
 	<?php if (! empty($conf->dol_hide_leftmenu)) print 'margin-bottom: 12px;'."\n"; ?>
 }
+div.fiche>table:first-child {
+	margin-bottom: 15px !important;
+}
 div.fichecenter {
+	/* margin-top: 10px; */
 	width: 100%;
 	clear: both;	/* This is to have div fichecenter that are true rectangles */
 }
@@ -1737,7 +1741,7 @@ div.vmenu, td.vmenu {
 
 .vmenu {
     width: 190px;
-	margin-left: 4px;
+	margin-left: 6px;
 	<?php if (GETPOST("optioncss") == 'print') { ?>
     display: none;
 	<?php } ?>
@@ -1766,10 +1770,10 @@ a.vmenu:link, a.vmenu:visited, a.vmenu:hover, a.vmenu:active { white-space: nowr
 font.vmenudisabled  { font-size:<?php print $fontsize ?>px; font-family: <?php print $fontlist ?>; text-align: <?php print $left; ?>; font-weight: bold; color: #aaa; margin-left: 4px; }
 a.vmenu:link, a.vmenu:visited { color: #<?php echo $colortextbackvmenu; ?>; }
 
-a.vsmenu:link, a.vsmenu:visited, a.vsmenu:hover, a.vsmenu:active, span.vsmenu { font-size:<?php print $fontsize ?>px; font-family: <?php print $fontlist ?>; text-align: <?php print $left; ?>; font-weight: normal; color: #202020; margin: 1px 1px 1px 8px; }
+a.vsmenu:link, a.vsmenu:visited, a.vsmenu:hover, a.vsmenu:active, span.vsmenu { font-size:<?php print $fontsize ?>px; font-family: <?php print $fontlist ?>; text-align: <?php print $left; ?>; font-weight: normal; color: #202020; margin: 1px 1px 1px 6px; }
 font.vsmenudisabled { font-size:<?php print $fontsize ?>px; font-family: <?php print $fontlist ?>; text-align: <?php print $left; ?>; font-weight: normal; color: #aaa; }
 a.vsmenu:link, a.vsmenu:visited { color: #<?php echo $colortextbackvmenu; ?>; white-space: nowrap; }
-font.vsmenudisabledmargin { margin: 1px 1px 1px 8px; }
+font.vsmenudisabledmargin { margin: 1px 1px 1px 6px; }
 
 a.help:link, a.help:visited, a.help:hover, a.help:active, span.help { font-size:<?php print $fontsizesmaller ?>px; font-family: <?php print $fontlist ?>; text-align: <?php print $left; ?>; font-weight: normal; color: #666666; text-decoration: none; }
 
@@ -1953,10 +1957,11 @@ img.toolbarbutton {
 /* ============================================================================== */
 div.tabs {
     text-align: <?php print $left; ?>;
-    margin-left: 6px !important;
-    margin-right: 6px !important;
+    padding-left: 6px !important;
+    padding-right: 6px !important;
 	clear:both;
 	height:100%;
+	/* background-image: linear-gradient(to top,#f6f6f6 0,#fff 8px);  */	
 }
 div.tabsElem {
 	margin-top: 1px;
@@ -2016,9 +2021,12 @@ a.tabTitle {
     white-space: nowrap;
 }
 
+a.tabunactive {
+    color: rgb(<?php print $colortextlink; ?>) !important;
+}
 a.tab:link, a.tab:visited, a.tab:hover, a.tab#active {
 	font-family: <?php print $fontlist ?>;
-	padding: 8px 9px 8px;
+	padding: 12px 9px 12px;
     margin: 0em 0.2em;
     text-decoration: none;
     white-space: nowrap;
@@ -2027,11 +2035,6 @@ a.tab:link, a.tab:visited, a.tab:hover, a.tab#active {
 	border-left: 1px solid transparent;
 	border-top: 1px solid transparent;
 	border-bottom: 0px !important;
-	/*
-	-moz-border-radius:4px 4px 0 0;
-    -webkit-border-radius: 4px 4px 0 0;
-	border-radius: 4px 4px 0 0;
-	*/
 
 	background-image: none !important;
 }
@@ -2494,6 +2497,10 @@ div.pagination li.pagination .active {
   text-decoration: underline;
   box-shadow: none;
 }
+.paginationafterarrows .nohover {
+  box-shadow: none !important;
+}
+
 div.pagination li.paginationafterarrows {
 	margin-left: 10px;
 }
@@ -2941,15 +2948,15 @@ div.error {
 
 /* Info admin */
 div.info {
-  color: #303035;
+  color: #fff;
   padding: 0.4em 0.4em 0.4em 0.4em;
   margin: 0.5em 0em 0.5em 0em;
   border: 1px solid #e0e0e0;
   -moz-border-radius: 4px;
   -webkit-border-radius: 4px;
   border-radius: 4px;
-  background: #EaE4Ea;
-  text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
+  background: #806090;
+  /* text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); */
 }
 
 div.warning a, div.info a, div.error a {
@@ -2998,6 +3005,9 @@ td.legendLabel { padding: 2px 2px 2px 0 !important; }
 	margin-bottom: 2px;
 	margin-top: 10px;
 }
+.photowithborder {
+	border: 1px solid #f0f0f0;
+}
 .photointooltip {
 	margin-top: 6px;
 	margin-bottom: 6px;
@@ -3029,9 +3039,12 @@ td.legendLabel { padding: 2px 2px 2px 0 !important; }
 
 div.titre {
 	font-family: <?php print $fontlist ?>;
+	font-size: 14px;
 	font-weight: bold;
 	color: rgb(<?php print $colortexttitlenotab; ?>);
 	text-decoration: none;
+	padding-top: 5px;
+    padding-bottom: 5px;
 	/* text-shadow: 1px 1px 2px #FFFFFF; */
 }
 
diff --git a/htdocs/theme/md/style.css.php b/htdocs/theme/md/style.css.php
index 7e8a4cd22adea2ac23c1fc01e05e6aee6fc605eb..73cb6eb440b40c381787d5a6cf9e6175cc5f9f8b 100644
--- a/htdocs/theme/md/style.css.php
+++ b/htdocs/theme/md/style.css.php
@@ -159,25 +159,25 @@ if (empty($colortopbordertitle1)) $colortopbordertitle1=$colorbackhmenu1;
 
 // Set text color to black or white
 $tmppart=explode(',',$colorbackhmenu1);
-$tmpval=(! empty($tmppart[0]) ? $tmppart[0] : '')+(! empty($tmppart[1]) ? $tmppart[1] : '')+(! empty($tmppart[2]) ? $tmppart[2] : '');
+$tmpval=(! empty($tmppart[0]) ? $tmppart[0] : 0)+(! empty($tmppart[1]) ? $tmppart[1] : 0)+(! empty($tmppart[2]) ? $tmppart[2] : 0);
 if ($tmpval <= 460) $colortextbackhmenu='FFFFFF';
 else $colortextbackhmenu='000000';
 
 $tmppart=explode(',',$colorbackvmenu1);
-$tmpval=(! empty($tmppart[0]) ? $tmppart[0] : '')+(! empty($tmppart[1]) ? $tmppart[1] : '')+(! empty($tmppart[2]) ? $tmppart[2] : '');
+$tmpval=(! empty($tmppart[0]) ? $tmppart[0] : 0)+(! empty($tmppart[1]) ? $tmppart[1] : 0)+(! empty($tmppart[2]) ? $tmppart[2] : 0);
 if ($tmpval <= 460) { $colortextbackvmenu='FFFFFF'; }
 else { $colortextbackvmenu='000000'; }
 
 $tmppart=explode(',',$colorbacktitle1);
 if ($colortexttitle == '')
 {
-	$tmpval=(! empty($tmppart[0]) ? $tmppart[0] : '')+(! empty($tmppart[1]) ? $tmppart[1] : '')+(! empty($tmppart[2]) ? $tmppart[2] : '');
+	$tmpval=(! empty($tmppart[0]) ? $tmppart[0] : 0)+(! empty($tmppart[1]) ? $tmppart[1] : 0)+(! empty($tmppart[2]) ? $tmppart[2] : 0);
 	if ($tmpval <= 460) { $colortexttitle='FFFFFF'; $colorshadowtitle='888888'; }
 	else { $colortexttitle='101010'; $colorshadowtitle='FFFFFF'; }
 }
 
 $tmppart=explode(',',$colorbacktabcard1);
-$tmpval=(! empty($tmppart[0]) ? $tmppart[0] : '')+(! empty($tmppart[1]) ? $tmppart[1] : '')+(! empty($tmppart[2]) ? $tmppart[2] : '');
+$tmpval=(! empty($tmppart[0]) ? $tmppart[0] : 0)+(! empty($tmppart[1]) ? $tmppart[1] : 0)+(! empty($tmppart[2]) ? $tmppart[2] : 0);
 if ($tmpval <= 460) { $colortextbacktab='FFFFFF'; }
 else { $colortextbacktab='111111'; }
 
@@ -241,7 +241,7 @@ body {
 <?php } ?>
 	color: rgb(<?php echo $colortext; ?>);
 	font-size: <?php print $fontsize ?>px;
-	line-height: 130%;
+	line-height: 1.3;
 	font-family: <?php print $fontlist ?>;
     margin-top: 0;
     margin-bottom: 0;
@@ -1137,6 +1137,9 @@ table.noborder tr.liste_titre td {
 .pictoedit, .pictowarning, .pictodelete {
     vertical-align: text-bottom;
 }
+img.hideonsmartphone.pictoactionview {
+    vertical-align: bottom;
+}
 .colorthumb {
 	padding-left: 1px !important;
 	padding-right: 1px;
@@ -2564,6 +2567,9 @@ div.pagination li.pagination .active {
   text-decoration: underline;
   box-shadow: none;
 }
+.paginationafterarrows .nohover {
+  box-shadow: none !important;
+}
 div.pagination li.paginationafterarrows {
 	margin-left: 10px;
 }
@@ -3112,10 +3118,8 @@ td.legendLabel { padding: 2px 2px 2px 0 !important; }
 	margin-bottom: 2px;
 	margin-top: 2px;
 }
-.photowithmargin {
-/*	-webkit-box-shadow: 0px 0px 3px #777;
-	-moz-box-shadow: 0px 0px 3px #777;
-	box-shadow: 0px 0px 3px #777;*/
+.photowithborder {
+	border: 1px solid #f0f0f0;
 }
 .photointoolitp {
 	margin-top: 8px;
@@ -3145,9 +3149,12 @@ td.legendLabel { padding: 2px 2px 2px 0 !important; }
 
 div.titre {
 	font-family: <?php print $fontlist ?>;
-	font-weight: bold;
+	font-size: 14px;
+	/* font-weight: bold; */
 	color: rgb(<?php print $colortexttitlenotab; ?>);
 	text-decoration: none;
+	padding-top: 5px;
+    padding-bottom: 5px;
 	/* text-shadow: 1px 1px 2px #FFFFFF; */
 	<?php print (empty($conf->dol_optimize_smallscreen)?'':'margin-top: 4px;'); ?>
 }
@@ -4676,7 +4683,7 @@ border-top-right-radius: 6px;
 	}
 	.mainmenuaspan {
     	/*display: none;*/
-  		font-size: 10px;
+  		font-size: 12px;
     }
     .topmenuimage {
     	background-size: 26px auto;
diff --git a/htdocs/user/admin/group_extrafields.php b/htdocs/user/admin/group_extrafields.php
index 99eab0e3a882c67084edcdb33bccb62959f123a0..8dad702935fc54622e4b47356a5ad21f775bc3ba 100644
--- a/htdocs/user/admin/group_extrafields.php
+++ b/htdocs/user/admin/group_extrafields.php
@@ -71,7 +71,7 @@ print load_fiche_titre($langs->trans("UsersSetup"),$linkback,'title_setup');
 
 $head = user_admin_prepare_head();
 
-dol_fiche_head($head, 'attributes_group', $langs->trans("MenuUsersAndGroups"), 0, 'user');
+dol_fiche_head($head, 'attributes_group', $langs->trans("MenuUsersAndGroups"), -1, 'user');
 
 require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_view.tpl.php';
 
diff --git a/htdocs/user/admin/user_extrafields.php b/htdocs/user/admin/user_extrafields.php
index bb035d9f95f6517d3055ad165f9b68c08b5b9772..28bf22da65486b44890a69d845cc10eab64abc78 100644
--- a/htdocs/user/admin/user_extrafields.php
+++ b/htdocs/user/admin/user_extrafields.php
@@ -70,7 +70,7 @@ print load_fiche_titre($langs->trans("UsersSetup"),$linkback,'title_setup');
 
 $head = user_admin_prepare_head();
 
-dol_fiche_head($head, 'attributes', $langs->trans("MenuUsersAndGroups"), 0, 'user');
+dol_fiche_head($head, 'attributes', $langs->trans("MenuUsersAndGroups"), -1, 'user');
 
 require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_view.tpl.php';
 
diff --git a/htdocs/user/agenda_extsites.php b/htdocs/user/agenda_extsites.php
index d8aba34a934102ba320838c04d57b0559aa5f140..e789a8277f3c64f45a68db496a49a680275ef728 100644
--- a/htdocs/user/agenda_extsites.php
+++ b/htdocs/user/agenda_extsites.php
@@ -42,7 +42,7 @@ $actiontest=GETPOST('test','alpha');
 $actionsave=GETPOST('save','alpha');
 
 if (empty($conf->global->AGENDA_EXT_NB)) $conf->global->AGENDA_EXT_NB=5;
-$MAXAGENDA=empty($conf->global->AGENDA_EXT_NB)?5:$conf->global->AGENDA_EXT_NB;
+$MAXAGENDA=$conf->global->AGENDA_EXT_NB;
 
 // List of available colors
 $colorlist=array('BECEDD','DDBECE','BFDDBE','F598B4','F68654','CBF654','A4A4A5');
@@ -50,7 +50,8 @@ $colorlist=array('BECEDD','DDBECE','BFDDBE','F598B4','F68654','CBF654','A4A4A5')
 // Security check
 $id = GETPOST('id','int');
 $object = new User($db);
-$object->fetch($id);
+$object->fetch($id, '', '', 1);
+$object->getrights();
 
 // Security check
 $socid=0;
@@ -81,12 +82,12 @@ if (empty($reshook)) {
 	if ($actionsave) {
 		$db->begin();
 
-		$i = 1;
 		$errorsaved = 0;
 		$error = 0;
 		$tabparam = array();
 
 		// Save agendas
+		$i = 1;
 		while ($i <= $MAXAGENDA) {
 			$name = trim(GETPOST('AGENDA_EXT_NAME_'.$id.'_'.$i, 'alpha'));
 			$src = trim(GETPOST('AGENDA_EXT_SRC_'.$id.'_'.$i, 'alpha'));
@@ -110,7 +111,7 @@ if (empty($reshook)) {
 			$tabparam['AGENDA_EXT_COLOR_'.$id.'_'.$i]=$color;
 			$tabparam['AGENDA_EXT_ENABLED_'.$id.'_'.$i]=$enabled;
 
-			$i ++;
+			$i++;
 		}
 
 		if (!$error) {
@@ -167,7 +168,6 @@ print "<br>\n";
 $selectedvalue=$conf->global->AGENDA_DISABLE_EXT;
 if ($selectedvalue==1) $selectedvalue=0; else $selectedvalue=1;
 
-$var=true;
 print '<div class="div-table-responsive">';
 print "<table class=\"noborder\" width=\"100%\">";
 
@@ -180,7 +180,6 @@ print '<td align="right">'.$langs->trans("Color").'</td>';
 print "</tr>";
 
 $i=1;
-$var=true;
 while ($i <= $MAXAGENDA)
 {
 	$key=$i;
@@ -189,7 +188,7 @@ while ($i <= $MAXAGENDA)
 	$offsettz='AGENDA_EXT_OFFSETTZ_'.$id.'_'.$key;
 	$color='AGENDA_EXT_COLOR_'.$id.'_'.$key;
 
-	
+
 	print '<tr class="oddeven">';
 	// Nb
 	print '<td class="maxwidth50onsmartphone">'.$langs->trans("AgendaExtNb",$key)."</td>";
diff --git a/htdocs/user/bank.php b/htdocs/user/bank.php
index c9551cdbc235297e285e8a8b07485f3ff91fb1c4..9f36bc91e314eb8d54aa5237e442373d3c3df0f4 100644
--- a/htdocs/user/bank.php
+++ b/htdocs/user/bank.php
@@ -50,7 +50,8 @@ $result = restrictedArea($user, 'user', $id, 'user&user', $feature2);
 $object = new User($db);
 if ($id > 0 || ! empty($ref))
 {
-	$result = $object->fetch($id, $ref);
+	$result = $object->fetch($id, $ref, '', 1);
+	$object->getrights();
 }
 
 /*
diff --git a/htdocs/user/card.php b/htdocs/user/card.php
index 3255dc676cf5a7f9f4bb1eef00916a0a11792991..675f57488429d42651a34698c1cb9c1ce2213f92 100644
--- a/htdocs/user/card.php
+++ b/htdocs/user/card.php
@@ -1140,7 +1140,7 @@ else
 
     if ($id > 0)
     {
-        $object->fetch($id);
+        $object->fetch($id, '', '', 1);
         if ($res < 0) { dol_print_error($db,$object->error); exit; }
         $res=$object->fetch_optionals($object->id,$extralabels);
 		
diff --git a/htdocs/user/clicktodial.php b/htdocs/user/clicktodial.php
index 5299f3484312f5368a6b10c3ce1c72e31aac4482..1500a3be55c8705055ca1afe7ca130eb69debdc0 100644
--- a/htdocs/user/clicktodial.php
+++ b/htdocs/user/clicktodial.php
@@ -83,7 +83,8 @@ llxHeader("","ClickToDial");
 if ($id > 0)
 {
     $object = new User($db);
-    $object->fetch($id);
+    $object->fetch($id, '', '', 1);
+    $object->getrights();
     $object->fetch_clicktodial();
 
 
diff --git a/htdocs/user/document.php b/htdocs/user/document.php
index a8d5000e80998667dafb0c2a9cdb77f6611969be..8b055979992f48587c2afccf6f0fd62093391e7b 100644
--- a/htdocs/user/document.php
+++ b/htdocs/user/document.php
@@ -86,7 +86,7 @@ if (! $sortfield) $sortfield="name";
 $object = new User($db);
 if ($id > 0 || ! empty($ref))
 {
-	$result = $object->fetch($id, $ref);
+	$result = $object->fetch($id, $ref, '', 1);
 	$object->getrights();
 	$entitytouseforuserdir = $object->entity;
 	if (empty($entitytouseforuserdir)) $entitytouseforuserdir=1;
diff --git a/htdocs/user/info.php b/htdocs/user/info.php
index 86bff7147ffb4709894cd3f1c566751418d7e4ba..d20624063f24b3659f0fc1defcdc3b6385fee96f 100644
--- a/htdocs/user/info.php
+++ b/htdocs/user/info.php
@@ -34,7 +34,7 @@ $id = GETPOST('id','int');
 $object = new User($db);
 if ($id > 0 || ! empty($ref))
 {
-	$result = $object->fetch($id, $ref);
+	$result = $object->fetch($id, $ref, '', 1);
 	$object->getrights();
 }
 
diff --git a/htdocs/user/ldap.php b/htdocs/user/ldap.php
index 0f0cc6b4ed7b2daef99c9102ef3b619aa09fda8c..252ed9f82b4446cc836b8762fcfbb4ebcf4ef2fc 100644
--- a/htdocs/user/ldap.php
+++ b/htdocs/user/ldap.php
@@ -42,7 +42,7 @@ if ($user->id == $id) $feature2=''; // A user can always read its own card
 $result = restrictedArea($user, 'user', $id, 'user&user', $feature2);
 
 $object = new User($db);
-$object->fetch($id);
+$object->fetch($id, '', '', 1);
 $object->getrights();
 
 // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array
diff --git a/htdocs/user/note.php b/htdocs/user/note.php
index ae685391299bf968927140a7966cfafaeba575be..2844676a4658eab6fa1072bbd853b057da88c414 100644
--- a/htdocs/user/note.php
+++ b/htdocs/user/note.php
@@ -36,7 +36,7 @@ $langs->load("bills");
 $langs->load("users");
 
 $object = new User($db);
-$object->fetch($id);
+$object->fetch($id, '', '', 1);
 $object->getrights();
 
 // If user is not user read and no permission to read other users, we stop
@@ -52,9 +52,10 @@ $result = restrictedArea($user, 'user', $id, 'user&user', $feature2);
 // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array
 $hookmanager->initHooks(array('usercard','globalcard'));
 
-/******************************************************************************/
-/*                     Actions                                                */
-/******************************************************************************/
+
+/*
+ * Actions
+ */
 
 $parameters=array('id'=>$socid);
 $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
@@ -75,9 +76,9 @@ if (empty($reshook)) {
 }
 
 
-/******************************************************************************/
-/* Affichage fiche                                                            */
-/******************************************************************************/
+/*
+ * View
+ */
 
 llxHeader();
 
diff --git a/htdocs/user/notify/card.php b/htdocs/user/notify/card.php
index 4f47578f54356275c9fd118e61da4551fbcde679..2b7c31d75dfbd90eba816bef57419de3a2af6b06 100644
--- a/htdocs/user/notify/card.php
+++ b/htdocs/user/notify/card.php
@@ -122,7 +122,8 @@ if ($action == 'delete')
 $form = new Form($db);
 
 $object = new User($db);
-$result=$object->fetch($id);
+$result=$object->fetch($id, '', '', 1);
+$object->getrights();
 
 $title=$langs->trans("ThirdParty").' - '.$langs->trans("Notification");
 if (! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/',$conf->global->MAIN_HTML_TITLE) && $object->name) $title=$object->name.' - '.$langs->trans("Notification");
diff --git a/htdocs/user/param_ihm.php b/htdocs/user/param_ihm.php
index 473c06e73682c32cd4fb089a1a4d2e11e86f525c..9ffeb05f280b1068587e4497a262f12526361991 100644
--- a/htdocs/user/param_ihm.php
+++ b/htdocs/user/param_ihm.php
@@ -181,7 +181,7 @@ if ($action == 'edit')
 
 if ($action == 'edit')
 {
-    dol_fiche_head($head, 'guisetup', $title, 0, 'user');
+    dol_fiche_head($head, 'guisetup', $title, -1, 'user');
 
 	$linkback = '';
 
diff --git a/htdocs/user/passwordforgotten.php b/htdocs/user/passwordforgotten.php
index f7acc3609c7c610d94b851a3fcea092e7a526f95..e59e26efd0b6b7c0fe730b448ba64878beb8d88e 100644
--- a/htdocs/user/passwordforgotten.php
+++ b/htdocs/user/passwordforgotten.php
@@ -191,15 +191,6 @@ $conf_css = $themepath."?lang=".$langs->defaultlang;
 $jquerytheme = 'smoothness';
 if (! empty($conf->global->MAIN_USE_JQUERY_THEME)) $jquerytheme = $conf->global->MAIN_USE_JQUERY_THEME;
 
-if (file_exists(DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/login_background.png'))
-{
-    $login_background = DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/login_background.png';
-}
-else
-{
-    $login_background = DOL_URL_ROOT.'/theme/login_background.png';
-}
-
 if (! $username) $focus_element = 'username';
 else $focus_element = 'password';
 
diff --git a/htdocs/user/perms.php b/htdocs/user/perms.php
index e84cfe09ca8fe60eed7c54156ac0baba87ee62b9..b40c79f783eb8592ca34331f41ecfd2b02c3ac16 100644
--- a/htdocs/user/perms.php
+++ b/htdocs/user/perms.php
@@ -68,7 +68,7 @@ $result = restrictedArea($user, 'user', $id, 'user&user', $feature2);
 if ($user->id <> $id && ! $canreaduser) accessforbidden();
 
 $object = new User($db);
-$object->fetch($id);
+$object->fetch($id, '', '', 1);
 $object->getrights();
 
 // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array
diff --git a/htdocs/webservices/demo_wsclient_actioncomm.php-NORUN b/htdocs/webservices/demo_wsclient_actioncomm.php-NORUN
index d3044fc9bd837ec889ae2a7d1d320ae1590d7644..d8ad49945bd5da9dae432eac8a40d4fa939b5551 100755
--- a/htdocs/webservices/demo_wsclient_actioncomm.php-NORUN
+++ b/htdocs/webservices/demo_wsclient_actioncomm.php-NORUN
@@ -107,8 +107,7 @@ if ($action=='create')
 	'projectid'=>'',
 	'note'=>'This is note',
 	'contactid'=>'',
-	'usertodo'=>'1',
-	'userdone'=>'1',
+	'userownerod'=>'1',
 	'label'=>'Ceci est les titre de l\'envenement',
 	'percentage'=>'100',
 	'location'=>'Location1'
diff --git a/htdocs/webservices/server_actioncomm.php b/htdocs/webservices/server_actioncomm.php
index 99e8ea59e6f92028134816767a21d0c2a033c543..c7e1f769d9ae17662c2c2e32dbb5e3d84c552067 100644
--- a/htdocs/webservices/server_actioncomm.php
+++ b/htdocs/webservices/server_actioncomm.php
@@ -101,8 +101,7 @@ $actioncomm_fields= array(
 	'percentage' => array('name'=>'percentage','type'=>'xsd:string'),
 	'author' => array('name'=>'author','type'=>'xsd:string'),
 	'usermod' => array('name'=>'usermod','type'=>'xsd:string'),
-	'usertodo' => array('name'=>'usertodo','type'=>'xsd:string'),
-	'userdone' => array('name'=>'userdone','type'=>'xsd:string'),
+	'userownerid' => array('name'=>'userownerid','type'=>'xsd:string'),
 	'priority' => array('name'=>'priority','type'=>'xsd:string'),
 	'fulldayevent' => array('name'=>'fulldayevent','type'=>'xsd:string'),
 	'location' => array('name'=>'location','type'=>'xsd:string'),
@@ -291,8 +290,7 @@ function getActionComm($authentication,$id)
 			        	'percentage'=> $actioncomm->percentage,
 			        	'author'=> $actioncomm->authorid,
 			        	'usermod'=> $actioncomm->usermodid,
-			        	'usertodo'=> $actioncomm->userownerid,
-			        	'userdone'=> $actioncomm->userdoneid,
+			        	'userownerid'=> $actioncomm->userownerid,
 			        	'priority'=> $actioncomm->priority,
 			        	'fulldayevent'=> $actioncomm->fulldayevent,
 			        	'location'=> $actioncomm->location,
@@ -437,8 +435,7 @@ function createActionComm($authentication,$actioncomm)
 		$newobject->fk_project=$actioncomm['projectid'];
 		$newobject->note=$actioncomm['note'];
 		$newobject->contactid=$actioncomm['contactid'];
-		$newobject->userownerid=$actioncomm['usertodo'];
-		$newobject->userdoneid=$actioncomm['userdone'];
+		$newobject->userownerid=$actioncomm['userownerid'];
 		$newobject->label=$actioncomm['label'];
 		$newobject->percentage=$actioncomm['percentage'];
 		$newobject->priority=$actioncomm['priority'];
@@ -532,8 +529,7 @@ function updateActionComm($authentication,$actioncomm)
 			$object->contactid=$actioncomm['contactid'];
 			$object->fk_project=$actioncomm['projectid'];
 			$object->note=$actioncomm['note'];
-			$object->userownerid=$actioncomm['usertodo'];
-			$object->userdoneid=$actioncomm['userdone'];
+			$object->userownerid=$actioncomm['userownerid'];
 			$object->label=$actioncomm['label'];
 			$object->percentage=$actioncomm['percentage'];
 			$object->priority=$actioncomm['priority'];
diff --git a/scripts/emailings/mailing-send.php b/scripts/emailings/mailing-send.php
index 27cc22448e699f90f5f04490f5c744b43c0466d6..6465e765cfe546260a2e85bba38a054db0901e9e 100755
--- a/scripts/emailings/mailing-send.php
+++ b/scripts/emailings/mailing-send.php
@@ -41,11 +41,12 @@ if (! isset($argv[1]) || ! $argv[1]) {
 	exit(-1);
 }
 $id=$argv[1];
-if (! isset($argv[2]) || !empty($argv[2])) $login = $argv[2];
+if (isset($argv[2]) || !empty($argv[2])) $login = $argv[2];
 else $login = '';
 
 require_once ($path."../../htdocs/master.inc.php");
 require_once (DOL_DOCUMENT_ROOT."/core/class/CMailFile.class.php");
+require_once (DOL_DOCUMENT_ROOT."/comm/mailing/class/mailing.class.php");
 
 
 // Global variables
@@ -70,9 +71,8 @@ $user = new User($db);
 // for signature, we use user send as parameter
 if (! empty($login)) $user->fetch('',$login);
 
-// We get list of emailing to process
-$sql = "SELECT m.rowid, m.titre, m.sujet, m.body,";
-$sql.= " m.email_from, m.email_replyto, m.email_errorsto";
+// We get list of emailing id to process
+$sql = "SELECT m.rowid";
 $sql.= " FROM ".MAIN_DB_PREFIX."mailing as m";
 $sql.= " WHERE m.statut IN (1,2)";
 if ($id != 'all')
@@ -96,12 +96,15 @@ if ($resql)
 			dol_syslog("Process mailing with id ".$obj->rowid);
 			print "Process mailing with id ".$obj->rowid."\n";
 
-			$id       = $obj->rowid;
-			$subject  = $obj->sujet;
-			$message  = $obj->body;
-			$from     = $obj->email_from;
-			$replyto  = $obj->email_replyto;
-			$errorsto = $obj->email_errorsto;
+			$emailing = new Mailing($db);
+			$emailing->fetch($obj->rowid);
+			
+			$id       = $emailing->id;
+			$subject  = $emailing->sujet;
+			$message  = $emailing->body;
+			$from     = $emailing->email_from;
+			$replyto  = $emailing->email_replyto;
+			$errorsto = $emailing->email_errorsto;
 			// Le message est-il en html
 			$msgishtml=-1;  // Unknown by default
 			if (preg_match('/[\s\t]*<html>/i',$message)) $msgishtml=1;
@@ -232,6 +235,24 @@ if ($resql)
 
 							dol_syslog("ok for emailing id ".$id." #".$i.($mail->error?' - '.$mail->error:''), LOG_DEBUG);
 
+							// Note: If emailing is 100 000 targets, 100 000 entries are added, so we don't enter events for each target here
+							// We must union table llx_mailing_taget for event tab OR enter 1 event with a special table link (id of email in event)
+							// Run trigger
+							/*
+							if ($obj2->source_type == 'contact')
+							{
+							    $emailing->sendtoid = $obj2->source_id;
+							}
+							if ($obj2->source_type == 'thirdparty')
+							{
+							    $emailing->socid = $obj2->source_id;
+							}
+                            // Call trigger
+                            $result=$emailing->call_trigger('EMAILING_SENTBYMAIL',$user);
+                            if ($result < 0) $error++;
+                            // End call triggers
+						    */
+							
 							$sqlok ="UPDATE ".MAIN_DB_PREFIX."mailing_cibles";
 							$sqlok.=" SET statut=1, date_envoi='".$db->idate($now)."' WHERE rowid=".$obj2->rowid;
 							$resqlok=$db->query($sqlok);