diff --git a/htdocs/comm/mailing/card.php b/htdocs/comm/mailing/card.php
index aeaf19f8471e8eef0b0fc9e5813c012a24de693e..b7f2a002105ca0bd42a6512042b53ae009ffcb06 100644
--- a/htdocs/comm/mailing/card.php
+++ b/htdocs/comm/mailing/card.php
@@ -602,6 +602,29 @@ if (empty($reshook))
 		}
 	}
 
+	// Action confirmation validation
+	if ($action == 'confirm_settodraft' && $confirm == 'yes')
+	{
+		if ($object->id > 0)
+		{
+			$result = $object->setStatut(0);
+            if ($result > 0)
+            {
+    			//setEventMessages($langs->trans("MailingSuccessfullyValidated"), null, 'mesgs');
+    			header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
+    			exit;
+            }
+            else
+            {
+                setEventMessages($object->error, $object->errors, 'errors');
+            }
+		}
+		else
+		{
+			dol_print_error($db);
+		}
+	}
+
 	// Resend
 	if ($action == 'confirm_reset' && $confirm == 'yes')
 	{
@@ -707,7 +730,7 @@ if ($action == 'create')
 	print '<div style="padding-top: 10px">';
 	// Editeur wysiwyg
 	require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
-	$doleditor=new DolEditor('body',$_POST['body'],'',320,'dolibarr_mailings','',true,true,$conf->global->FCKEDITOR_ENABLE_MAILING,20,'90%');
+	$doleditor=new DolEditor('body',$_POST['body'],'',600,'dolibarr_mailings','',true,true,$conf->global->FCKEDITOR_ENABLE_MAILING,20,'90%');
 	$doleditor->Create();
 	print '</div>';
 	
@@ -727,7 +750,12 @@ else
 
 		dol_fiche_head($head, 'card', $langs->trans("Mailing"), 0, 'email');
 
-		// Confirmation de la validation du mailing
+		// Confirmation back to draft
+		if ($action == 'settodraft')
+		{
+			print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id,$langs->trans("SetToDraft"),$langs->trans("ConfirmUnvalidateEmailing"),"confirm_settodraft",'','',1);
+		}
+		// Confirmation validation of mailing
 		if ($action == 'valid')
 		{
 			print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id,$langs->trans("ValidMailing"),$langs->trans("ConfirmValidMailing"),"confirm_valid",'','',1);
@@ -900,10 +928,15 @@ else
 			 * Boutons d'action
 			 */
 
-			if (GETPOST("cancel") || $confirm=='no' || $action == '' || in_array($action,array('valid','delete','sendall','clone')))
+			if (GETPOST("cancel") || $confirm=='no' || $action == '' || in_array($action,array('settodraft', 'valid','delete','sendall','clone')))
 			{
 				print "\n\n<div class=\"tabsAction\">\n";
 
+				if (($object->statut == 1) && ($user->rights->mailing->valider || $object->fk_user_valid == $user->id))
+				{
+					print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=settodraft&amp;id='.$object->id.'">'.$langs->trans("SetToDraft").'</a>';
+				}
+
 				if (($object->statut == 0 || $object->statut == 1) && $user->rights->mailing->creer)
 				{
 					print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=edit&amp;id='.$object->id.'">'.$langs->trans("EditMailing").'</a>';
@@ -1065,7 +1098,7 @@ else
 				$readonly=1;
 				// Editeur wysiwyg
 				require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
-				$doleditor=new DolEditor('body',$object->body,'',320,'dolibarr_mailings','',false,true,empty($conf->global->FCKEDITOR_ENABLE_MAILING)?0:1,20,120,$readonly);
+				$doleditor=new DolEditor('body',$object->body,'',600,'dolibarr_mailings','',false,true,empty($conf->global->FCKEDITOR_ENABLE_MAILING)?0:1,20,120,$readonly);
 				$doleditor->Create();
 			}
 			else print dol_htmlentitiesbr($object->body);
@@ -1212,7 +1245,7 @@ else
 			print '<div style="padding-top: 10px">';
 			// Editeur wysiwyg
 			require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
-			$doleditor=new DolEditor('body',$object->body,'',320,'dolibarr_mailings','',true,true,$conf->global->FCKEDITOR_ENABLE_MAILING,20,'90%');
+			$doleditor=new DolEditor('body',$object->body,'',600,'dolibarr_mailings','',true,true,$conf->global->FCKEDITOR_ENABLE_MAILING,20,'90%');
 			$doleditor->Create();
 			print '</div>';
 
diff --git a/htdocs/comm/mailing/cibles.php b/htdocs/comm/mailing/cibles.php
index e104db4dcda9404ffae3b511d3014db9d193f09c..470ee2a4ec1b678743fe55ef30f5e8bcbe7c2e30 100644
--- a/htdocs/comm/mailing/cibles.php
+++ b/htdocs/comm/mailing/cibles.php
@@ -533,7 +533,7 @@ if ($object->fetch($id) >= 0)
 				print '<td align="center">';
                 if (empty($obj->source_id) || empty($obj->source_type))
                 {
-                    print $obj->source_url; // For backward compatibility
+                    print empty($obj->source_url)?'':$obj->source_url; // For backward compatibility
                 }
                 else
                 {
diff --git a/htdocs/comm/mailing/class/mailing.class.php b/htdocs/comm/mailing/class/mailing.class.php
index dc39c2e9399be21252f67e56333c9e0042cd4eee..b0dff81332c5f53aade01443ddd5e8d0a7812b4a 100644
--- a/htdocs/comm/mailing/class/mailing.class.php
+++ b/htdocs/comm/mailing/class/mailing.class.php
@@ -601,35 +601,38 @@ class Mailing extends CommonObject
 		if ($mode == 2)
 		{
 			if ($statut==-1) return $langs->trans("MailingStatusError").' '.img_error($desc);
-			if ($statut==1) return $langs->trans("MailingStatusSent").' '.img_picto($langs->trans("MailingStatusSent"),'statut4');
-			if ($statut==2) return $langs->trans("MailingStatusRead").' '.img_picto($langs->trans("MailingStatusRead"),'statut6');
-			if ($statut==3) return $langs->trans("MailingStatusNotContact").' '.img_picto($langs->trans("MailingStatusNotContact"),'statut8');
+			if ($statut==1) return $langs->trans("MailingStatusSent").' '.img_picto($langs->trans("MailingStatusSent"),'statut6');
+			if ($statut==2) return $langs->trans("MailingStatusRead").' '.img_picto($langs->trans("MailingStatusRead"),'statut4');
+			if ($statut==3) return $langs->trans("MailingStatusNotContact").' '.img_picto($langs->trans("MailingStatusNotContact"),'statut3');
 		}
 		if ($mode == 3)
 		{
 			if ($statut==-1) return $langs->trans("MailingStatusError").' '.img_error($desc);
-			if ($statut==1) return $langs->trans("MailingStatusSent").' '.img_picto($langs->trans("MailingStatusSent"),'statut4');
-			if ($statut==2) return $langs->trans("MailingStatusRead").' '.img_picto($langs->trans("MailingStatusRead"),'statut6');
-			if ($statut==3) return $langs->trans("MailingStatusNotContact").' '.img_picto($langs->trans("MailingStatusNotContact"),'statut8');
+			if ($statut==1) return $langs->trans("MailingStatusSent").' '.img_picto($langs->trans("MailingStatusSent"),'statut6');
+			if ($statut==2) return $langs->trans("MailingStatusRead").' '.img_picto($langs->trans("MailingStatusRead"),'statut4');
+			if ($statut==3) return $langs->trans("MailingStatusNotContact").' '.img_picto($langs->trans("MailingStatusNotContact"),'statut3');
 		}
 		if ($mode == 4)
 		{
 			if ($statut==-1) return $langs->trans("MailingStatusError").' '.img_error($desc);
-			if ($statut==1) return $langs->trans("MailingStatusSent").' '.img_picto($langs->trans("MailingStatusSent"),'statut4');
-			if ($statut==2) return $langs->trans("MailingStatusRead").' '.img_picto($langs->trans("MailingStatusRead"),'statut6');
-			if ($statut==3) return $langs->trans("MailingStatusNotContact").' '.img_picto($langs->trans("MailingStatusNotContact"),'statut8');
+			if ($statut==1) return $langs->trans("MailingStatusSent").' '.img_picto($langs->trans("MailingStatusSent"),'statut6');
+			if ($statut==2) return $langs->trans("MailingStatusRead").' '.img_picto($langs->trans("MailingStatusRead"),'statut4');
+			if ($statut==3) return $langs->trans("MailingStatusNotContact").' '.img_picto($langs->trans("MailingStatusNotContact"),'statut3');
 		}
 		if ($mode == 5)
 		{
-			if ($statut==-1) return $langs->trans("MailingStatusError").' '.img_error($desc);
-			if ($statut==1) return $langs->trans("MailingStatusSent").' '.img_picto($langs->trans("MailingStatusSent"),'statut4');
-			if ($statut==2) return $langs->trans("MailingStatusRead").' '.img_picto($langs->trans("MailingStatusRead"),'statut6');
-			if ($statut==3) return $langs->trans("MailingStatusNotContact").' '.img_picto($langs->trans("MailingStatusNotContact"),'statut8');
+		    if ($statut==-1) return $langs->trans("MailingStatusError").' '.img_error($desc);
+		    if ($statut==1) return $langs->trans("MailingStatusSent").' '.img_picto($langs->trans("MailingStatusSent"),'statut6');
+		    if ($statut==2) return $langs->trans("MailingStatusRead").' '.img_picto($langs->trans("MailingStatusRead"),'statut4');
+		    if ($statut==3) return $langs->trans("MailingStatusNotContact").' '.img_picto($langs->trans("MailingStatusNotContact"),'statut3');
+		}
+		if ($mode == 6)
+		{
+		    if ($statut==-1) return $langs->trans("MailingStatusError").' '.img_error($desc);
+		    if ($statut==1) return $langs->trans("MailingStatusSent").' '.img_picto($langs->trans("MailingStatusSent"),'statut6');
+		    if ($statut==2) return $langs->trans("MailingStatusRead").' '.img_picto($langs->trans("MailingStatusRead"),'statut4');
+		    if ($statut==3) return $langs->trans("MailingStatusNotContact").' '.img_picto($langs->trans("MailingStatusNotContact"),'statut3');
 		}
-
-
-
-
 	}
 
 }
diff --git a/htdocs/comm/mailing/list.php b/htdocs/comm/mailing/list.php
index b0801c817aa80c7bc51b4517715f34466ab27afb..2d6fae37b98bfb633889ae98e3e81477b10f668e 100644
--- a/htdocs/comm/mailing/list.php
+++ b/htdocs/comm/mailing/list.php
@@ -174,7 +174,7 @@ if ($result)
 		{
 			print '<td align="center">';
 			$nbemail = $obj->nbemail;
-			if ($obj->statut != 3 && !empty($conf->global->MAILING_LIMIT_SENDBYWEB) && $conf->global->MAILING_LIMIT_SENDBYWEB < $nbemail)
+			/*if ($obj->statut != 3 && !empty($conf->global->MAILING_LIMIT_SENDBYWEB) && $conf->global->MAILING_LIMIT_SENDBYWEB < $nbemail)
 			{
 				$text=$langs->trans('LimitSendingEmailing',$conf->global->MAILING_LIMIT_SENDBYWEB);
 				print $form->textwithpicto($nbemail,$text,1,'warning');
@@ -182,7 +182,8 @@ if ($result)
 			else
 			{
 				print $nbemail;
-			}
+			}*/
+			print $nbemail;
 			print '</td>';
 		}
 		// Last send
diff --git a/htdocs/compta/facture.php b/htdocs/compta/facture.php
index f332cb65203483d679d87352c3881da7a8cb2cbf..54c8bf1bac12dcce618e50fe4d1868a67ca0cf98 100644
--- a/htdocs/compta/facture.php
+++ b/htdocs/compta/facture.php
@@ -804,14 +804,14 @@ if (empty($reshook))
 	                        $line->fk_parent_line = $fk_parent_line;
 
 	                        $line->subprice =-$line->subprice; // invert price for object
-	                        $line->pa_ht = -$line->pa_ht;
+	                        $line->pa_ht = $line->pa_ht;       // we choosed to have buy/cost price always positive, so no revert of sign here
 	                        $line->total_ht=-$line->total_ht;
 	                        $line->total_tva=-$line->total_tva;
 	                        $line->total_ttc=-$line->total_ttc;
 	                        $line->total_localtax1=-$line->total_localtax1;
 	                        $line->total_localtax2=-$line->total_localtax2;
 
-	                        $result = $line->insert();
+	                        $result = $line->insert(0, 1);     // When creating credit note with same lines than source, we must ignore error if discount alreayd linked
 
 	                        $object->lines[] = $line; // insert new line in current object
 
diff --git a/htdocs/compta/facture/class/facture.class.php b/htdocs/compta/facture/class/facture.class.php
index 72e81fd252e89873e221373ff5b4d2931d0be94e..73a4a5a85ab21dccb3294a4c07c9e1db99f6acaa 100644
--- a/htdocs/compta/facture/class/facture.class.php
+++ b/htdocs/compta/facture/class/facture.class.php
@@ -1277,7 +1277,7 @@ class Facture extends CommonInvoice
 	{
 		$this->lines=array();
 
-		$sql = 'SELECT l.rowid, l.fk_product, l.fk_parent_line, l.label as custom_label, l.description, l.product_type, l.price, l.qty, l.vat_src_code, l.tva_tx,';
+		$sql = 'SELECT l.rowid, l.fk_facture, l.fk_product, l.fk_parent_line, l.label as custom_label, l.description, l.product_type, l.price, l.qty, l.vat_src_code, l.tva_tx,';
 		$sql.= ' l.situation_percent, l.fk_prev_id,';
 		$sql.= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise_percent, l.fk_remise_except, l.subprice,';
 		$sql.= ' l.rang, l.special_code,';
@@ -1304,6 +1304,7 @@ class Facture extends CommonInvoice
 
 				$line->id               = $objp->rowid;
 				$line->rowid	        = $objp->rowid;             // deprecated
+				$line->fk_facture       = $objp->fk_facture;
 				$line->label            = $objp->custom_label;		// deprecated
 				$line->desc             = $objp->description;		// Description line
 				$line->description      = $objp->description;		// Description line
@@ -1558,6 +1559,18 @@ class Facture extends CommonInvoice
 			$facligne->rang=-1;
 			$facligne->info_bits=2;
 
+			// Get buy/cost price of invoice that is source of discount
+			if ($remise->fk_facture_source > 0)
+			{
+    			$srcinvoice=new Facture($this->db);
+    			$srcinvoice->fetch($remise->fk_facture_source);
+    			$totalcostpriceofinvoice=0;
+    			include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php';  // TODO Move this into commonobject
+    			$formmargin=new FormMargin($this->db);
+    			$arraytmp=$formmargin->getMarginInfosArray($srcinvoice, false);
+        		$facligne->pa_ht = $arraytmp['pa_total'];
+			}
+			
 			$facligne->total_ht  = -$remise->amount_ht;
 			$facligne->total_tva = -$remise->amount_tva;
 			$facligne->total_ttc = -$remise->amount_ttc;
@@ -4295,10 +4308,11 @@ class FactureLigne extends CommonInvoiceLine
 	/**
 	 *	Insert line into database
 	 *
-	 *	@param      int		$notrigger		1 no triggers
-	 *	@return		int						<0 if KO, >0 if OK
+	 *	@param      int		$notrigger		                 1 no triggers
+	 *  @param      int     $noerrorifdiscountalreadylinked  1=Do not make error if lines is linked to a discount and discount already linked to another
+	 *	@return		int						                 <0 if KO, >0 if OK
 	 */
-	function insert($notrigger=0)
+	function insert($notrigger=0, $noerrorifdiscountalreadylinked=0)
 	{
 		global $langs,$user,$conf;
 
@@ -4445,13 +4459,16 @@ class FactureLigne extends CommonInvoiceLine
 					// Check if discount was found
 					if ($result > 0)
 					{
-						// Check if discount not already affected to another invoice
-						if ($discount->fk_facture)
+					    // Check if discount not already affected to another invoice
+						if ($discount->fk_facture_line > 0)
 						{
-							$this->error=$langs->trans("ErrorDiscountAlreadyUsed",$discount->id);
-							dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
-							$this->db->rollback();
-							return -3;
+						    if (empty($noerrorifdiscountalreadylinked))
+						    {
+    							$this->error=$langs->trans("ErrorDiscountAlreadyUsed",$discount->id);
+    							dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
+    							$this->db->rollback();
+    							return -3;
+						    }
 						}
 						else
 						{
diff --git a/htdocs/contact/agenda.php b/htdocs/contact/agenda.php
index 3882d2ebca328186501210d54a74d9344437aff2..e97263ebf00aa1fad603590eeb3918ebd619ad3b 100644
--- a/htdocs/contact/agenda.php
+++ b/htdocs/contact/agenda.php
@@ -81,7 +81,7 @@ if (GETPOST('actioncode','array'))
 }
 else
 {
-    $actioncode=GETPOST("actioncode","alpha",3)?GETPOST("actioncode","alpha",3):(GETPOST("actioncode")=='0'?'0':(empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE)?'':$conf->global->AGENDA_DEFAULT_FILTER_TYPE));
+    $actioncode=GETPOST("actioncode","alpha",3)?GETPOST("actioncode","alpha",3):(GETPOST("actioncode")=='0'?'0':(empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT)?'':$conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT));
 }
 $search_agenda_label=GETPOST('search_agenda_label');
 
diff --git a/htdocs/contact/card.php b/htdocs/contact/card.php
index 37bd3078c7d2f38d463d8d7bbfc8686c242f1e9d..7d95da69aef0319447f2b2cae054c7b1b635707e 100644
--- a/htdocs/contact/card.php
+++ b/htdocs/contact/card.php
@@ -714,6 +714,11 @@ else
                 print ' &nbsp; &nbsp; ';
                 print '<input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">';
             }
+            else
+            {
+                print ' &nbsp; &nbsp; ';
+                print '<input type="button" class="button" value="' . $langs->trans("Cancel") . '" onClick="javascript:history.go(-1)">';
+            }
             print '</div>';
 
             print "</form>";
@@ -997,7 +1002,7 @@ else
 
             print '<div class="center">';
             print '<input type="submit" class="button" name="save" value="'.$langs->trans("Save").'">';
-            print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
+            print ' &nbsp; &nbsp; ';
             print '<input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">';
             print '</div>';
 
@@ -1229,33 +1234,7 @@ else
         }
 
         print "</div>";
-        //print "<br>";
 
-        /*
-		if (! empty($conf->agenda->enabled))
-		{
-			$objthirdparty=$objsoc;
-			$objcon=$object;
-
-		    $out='';
-		    $permok=$user->rights->agenda->myactions->create;
-		    if ((! empty($objthirdparty->id) || ! empty($objcon->id)) && $permok)
-		    {
-		        $out.='<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create';
-		        if (get_class($objthirdparty) == 'Societe') $out.='&amp;socid='.$objthirdparty->id;
-		        $out.=(! empty($objcon->id)?'&amp;contactid='.$objcon->id:'').'&amp;backtopage=1&amp;percentage=-1">';
-		    	$out.=$langs->trans("AddAnAction").' ';
-		    	$out.=img_picto($langs->trans("AddAnAction"),'filenew');
-		    	$out.="</a>";
-			}
-
-        	print load_fiche_titre($langs->trans("TasksHistoryForThisContact"),$out,'');
-
-        	//print show_actions_todo($conf,$langs,$db,$objsoc,$object);
-
-        	print show_actions_done($conf,$langs,$db,$objsoc,$object,0,'','');
-		}
-		*/
     }
 }
 
diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php
index 7aa8249f1b72efcae9f8fe3d2a136cd7f0c53e06..2f9141868a7c469b1e8d4b1d61233d04111d3b45 100644
--- a/htdocs/core/class/commonobject.class.php
+++ b/htdocs/core/class/commonobject.class.php
@@ -2785,6 +2785,7 @@ abstract class CommonObject
         $this->db->begin();
 
         $fieldstatus="fk_statut";
+        if ($elementTable == 'mailing') $fieldstatus="statut";
         if ($elementTable == 'user') $fieldstatus="statut";
         if ($elementTable == 'expensereport') $fieldstatus="fk_statut";
 		if ($elementTable == 'commande_fournisseur_dispatch') $fieldstatus="status";
diff --git a/htdocs/core/class/discount.class.php b/htdocs/core/class/discount.class.php
index 2295a301e032b5f75d012d0a22177a5dc6848daf..5ea11cba6805dda6a94aa2d8177c95d927c42dd8 100644
--- a/htdocs/core/class/discount.class.php
+++ b/htdocs/core/class/discount.class.php
@@ -41,10 +41,10 @@ class DiscountAbsolute
     public $fk_user;				// Id utilisateur qui accorde la remise
     public $description;			// Description libre
     public $datec;					// Date creation
-    public $fk_facture_line;  		// Id invoice line when a discount linked to invoice line (for absolute discounts)
-    public $fk_facture;			// Id invoice when a discoutn linked to invoice (for credit note)
+    public $fk_facture_line;  		// Id invoice line when a discount is used into an invoice line (for absolute discounts)
+    public $fk_facture;			    // Id invoice when a discount line is used into an invoice (for credit note)
     public $fk_facture_source;		// Id facture avoir a l'origine de la remise
-    public $ref_facture_source;	// Ref facture avoir a l'origine de la remise
+    public $ref_facture_source;	    // Ref facture avoir a l'origine de la remise
 
     /**
      *	Constructor
@@ -296,7 +296,7 @@ class DiscountAbsolute
         $resql = $this->db->query($sql);
         if ($resql)
         {
-            $this->fk_facture_source=$rowidline;
+            $this->fk_facture_line=$rowidline;
             $this->fk_facture=$rowidinvoice;
             return 1;
         }
diff --git a/htdocs/core/class/html.formmargin.class.php b/htdocs/core/class/html.formmargin.class.php
index 0ac6012f271a0d4d2b4d2d3d75a66bf405bb7262..2cf82424a4e944b1fb56ec60be48cdeecc7d125f 100644
--- a/htdocs/core/class/html.formmargin.class.php
+++ b/htdocs/core/class/html.formmargin.class.php
@@ -48,6 +48,7 @@ class FormMargin
 
 	/**
 	 *	get array with margin information from lines of object
+	 *  TODO Move this in common class.
 	 *
 	 * 	@param	CommonObject	$object			Object we want to get margin information for
 	 * 	@param 	boolean			$force_price	True of not
@@ -92,19 +93,23 @@ class FormMargin
 				$line->pa_ht = $line->subprice * (1 - ($line->remise_percent / 100));
 			}
 
+			$pv = $line->qty * $line->subprice * (1 - $line->remise_percent / 100);
+			$pa_ht = ($pv < 0 ? - $line->pa_ht : $line->pa_ht);      // We choosed to have line->pa_ht always positive in database, so we guess the correct sign
+			$pa = $line->qty * $pa_ht;
+			
 			// calcul des marges
 			if (isset($line->fk_remise_except) && isset($conf->global->MARGIN_METHODE_FOR_DISCOUNT)) {    // remise
-			    $pa = $line->qty * $line->pa_ht;
-			    $pv = $line->qty * $line->subprice * (1 - $line->remise_percent / 100);
 				if ($conf->global->MARGIN_METHODE_FOR_DISCOUNT == '1') { // remise globale considérée comme produit
 					$marginInfos['pa_products'] += $pa;
 					$marginInfos['pv_products'] += $pv;
 					$marginInfos['pa_total'] +=  $pa;
 					$marginInfos['pv_total'] +=  $pv;
 					// if credit note, margin = -1 * (abs(selling_price) - buying_price)
-					if ($pv < 0)
-						$marginInfos['margin_on_products'] += -1 * (abs($pv) - $pa);
-					else
+					//if ($pv < 0)
+					//{
+					//	$marginInfos['margin_on_products'] += -1 * (abs($pv) - $pa);
+					//}
+					//else
 						$marginInfos['margin_on_products'] += $pv - $pa;
 				}
 				elseif ($conf->global->MARGIN_METHODE_FOR_DISCOUNT == '2') { // remise globale considérée comme service
@@ -113,9 +118,9 @@ class FormMargin
 					$marginInfos['pa_total'] +=  $pa;
 					$marginInfos['pv_total'] +=  $pv;
 					// if credit note, margin = -1 * (abs(selling_price) - buying_price)
-					if ($pv < 0)
-						$marginInfos['margin_on_services'] += -1 * (abs($pv) - $pa);
-					else
+					//if ($pv < 0)
+					//	$marginInfos['margin_on_services'] += -1 * (abs($pv) - $pa);
+					//else
 						$marginInfos['margin_on_services'] += $pv - $pa;
 				}
 				elseif ($conf->global->MARGIN_METHODE_FOR_DISCOUNT == '3') { // remise globale prise en compte uniqt sur total
@@ -126,29 +131,29 @@ class FormMargin
 			else {
 				$type=$line->product_type?$line->product_type:$line->fk_product_type;
 				if ($type == 0) {  // product
-				    $pa = $line->qty * $line->pa_ht;
-				    $pv = $line->qty * $line->subprice * (1 - $line->remise_percent / 100);
 					$marginInfos['pa_products'] += $pa;
 					$marginInfos['pv_products'] += $pv;
 					$marginInfos['pa_total'] +=  $pa;
 					$marginInfos['pv_total'] +=  $pv;
 					// if credit note, margin = -1 * (abs(selling_price) - buying_price)
-					if ($pv < 0)
-						$marginInfos['margin_on_products'] += -1 * (abs($pv) - $pa);
-					else
-						$marginInfos['margin_on_products'] += $pv - $pa;
+					//if ($pv < 0)
+					//{
+					//    $marginInfos['margin_on_products'] += -1 * (abs($pv) - $pa);
+					//}
+					//else
+					//{
+					    $marginInfos['margin_on_products'] += $pv - $pa;
+					//}
 				}
 				elseif ($type == 1) {  // service
-				    $pa = $line->qty * $line->pa_ht;
-				    $pv = $line->qty * $line->subprice * (1 - $line->remise_percent / 100);
 					$marginInfos['pa_services'] += $pa;
 					$marginInfos['pv_services'] += $pv;
 					$marginInfos['pa_total'] +=  $pa;
 					$marginInfos['pv_total'] +=  $pv;
 					// if credit note, margin = -1 * (abs(selling_price) - buying_price)
-					if ($pv < 0)
-						$marginInfos['margin_on_services'] += -1 * (abs($pv) - $pa);
-					else
+					//if ($pv < 0)
+					//	$marginInfos['margin_on_services'] += -1 * (abs($pv) - $pa);
+					//else
 						$marginInfos['margin_on_services'] += $pv - $pa;
 				}
 			}
@@ -164,9 +169,9 @@ class FormMargin
 			$marginInfos['mark_rate_services'] = 100 * $marginInfos['margin_on_services'] / $marginInfos['pv_services'];
 
 		// if credit note, margin = -1 * (abs(selling_price) - buying_price)
-		if ($marginInfos['pv_total'] < 0)
-			$marginInfos['total_margin'] = -1 * (abs($marginInfos['pv_total']) - $marginInfos['pa_total']);
-		else
+		//if ($marginInfos['pv_total'] < 0)
+		//	$marginInfos['total_margin'] = -1 * (abs($marginInfos['pv_total']) - $marginInfos['pa_total']);
+		//else
 			$marginInfos['total_margin'] = $marginInfos['pv_total'] - $marginInfos['pa_total'];
 		if ($marginInfos['pa_total'] > 0)
 			$marginInfos['total_margin_rate'] = 100 * $marginInfos['total_margin'] / $marginInfos['pa_total'];
diff --git a/htdocs/core/class/html.formprojet.class.php b/htdocs/core/class/html.formprojet.class.php
index 0129f1c1382f99a41c2b44adbcaca8af1f3edf7f..86601da07376b8674af05f1b2312c578d21beee3 100644
--- a/htdocs/core/class/html.formprojet.class.php
+++ b/htdocs/core/class/html.formprojet.class.php
@@ -569,9 +569,10 @@ class FormProjets
 	 *    @param   int         $useshortlabel      Use short label
 	 *    @param   int         $showallnone        Add choice "All" and "None"
 	 *    @param   int         $showpercent        Show default probability for status
+	 *    @param   string      $morecss            Add more css
 	 *    @return  int|string                      The HTML select list of element or '' if nothing or -1 if KO
 	 */
-	function selectOpportunityStatus($htmlname, $preselected='-1', $showempty=1, $useshortlabel=0, $showallnone=0, $showpercent=0)
+	function selectOpportunityStatus($htmlname, $preselected='-1', $showempty=1, $useshortlabel=0, $showallnone=0, $showpercent=0, $morecss='')
 	{
 		global $conf, $langs;
 
@@ -587,7 +588,7 @@ class FormProjets
 			$i = 0;
 			if ($num > 0)
 			{
-				$sellist = '<select class="flat oppstatus" id="'.$htmlname.'" name="'.$htmlname.'">';
+				$sellist = '<select class="flat oppstatus'.($morecss?' '.$morecss:'').'" id="'.$htmlname.'" name="'.$htmlname.'">';
 				if ($showempty) $sellist.= '<option value="-1"></option>';
 				if ($showallnone) $sellist.= '<option value="all"'.($preselected == 'all'?' selected="selected"':'').'>--'.$langs->trans("OnlyOpportunitiesShort").'--</option>';
 				if ($showallnone) $sellist.= '<option value="openedopp"'.($preselected == 'openedopp'?' selected="selected"':'').'>--'.$langs->trans("OpenedOpportunitiesShort").'--</option>';
diff --git a/htdocs/core/lib/security.lib.php b/htdocs/core/lib/security.lib.php
index 4cfc077f0be8c7af794b8141f2f0c55698da9bfb..ced20a79ea64d6821788eabefc551d8d660fa513 100644
--- a/htdocs/core/lib/security.lib.php
+++ b/htdocs/core/lib/security.lib.php
@@ -339,7 +339,8 @@ function restrictedArea($user, $features, $objectid=0, $tableandshare='', $featu
 }
 
 /**
- * Check access by user to object
+ * Check access by user to object.
+ * This function is also called by restrictedArea
  *
  * @param User		$user			User to check
  * @param array		$featuresarray	Features/modules to check
@@ -348,8 +349,8 @@ function restrictedArea($user, $features, $objectid=0, $tableandshare='', $featu
  * @param string	$feature2		Feature to check, second level of permission (optional). Can be or check with 'level1|level2'.
  * @param string	$dbt_keyfield	Field name for socid foreign key if not fk_soc. Not used if objectid is null (optional)
  * @param string	$dbt_select		Field name for select if not rowid. Not used if objectid is null (optional)
- *
  * @return	bool		True if user has access, False otherwise
+ * @see restrictedArea
  */
 function checkUserAccessToObject($user, $featuresarray, $objectid=0, $tableandshare='', $feature2='', $dbt_keyfield='', $dbt_select='rowid')
 {
diff --git a/htdocs/core/modules/mailings/advthirdparties.modules.php b/htdocs/core/modules/mailings/advthirdparties.modules.php
index cd0f229983d8f0c85a90cc6a27745ace02dae5a2..737b239498f2f009e38311e3b6632f2e6ba5d91c 100644
--- a/htdocs/core/modules/mailings/advthirdparties.modules.php
+++ b/htdocs/core/modules/mailings/advthirdparties.modules.php
@@ -26,6 +26,7 @@ include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
 class mailing_advthirdparties extends MailingTargets
 {
 	var $name='ThirdPartyAdvancedTargeting';
+	// This label is used if no translation is found for key XXX neither MailingModuleDescXXX where XXX=name is found
 	var $desc="Third parties";
 	var $require_admin=0;
 
diff --git a/htdocs/core/modules/mailings/contacts1.modules.php b/htdocs/core/modules/mailings/contacts1.modules.php
index 99de75c6d264b9744bf76a6da6945312243af72b..02bcc17ec30854aad6a08a1abae2b10b5c6fd351 100644
--- a/htdocs/core/modules/mailings/contacts1.modules.php
+++ b/htdocs/core/modules/mailings/contacts1.modules.php
@@ -34,12 +34,12 @@ include_once DOL_DOCUMENT_ROOT.'/core/modules/mailings/modules_mailings.php';
 class mailing_contacts1 extends MailingTargets
 {
 	var $name='ContactCompanies';                     // Identifiant du module mailing
-	// This label is used if no translation is found for key MailingModuleDescXXX where XXX=name is found
-	var $desc='Contacts des tiers (prospects, clients, fournisseurs...)';
+	// This label is used if no translation is found for key XXX neither MailingModuleDescXXX where XXX=name is found
+	var $desc='Contacts of thirdparties (prospects, customers, suppliers...)';
 	var $require_module=array("societe");               // Module mailing actif si modules require_module actifs
 	var $require_admin=0;                               // Module mailing actif pour user admin ou non
 	var $picto='contact';
-
+	
 	var $db;
 
 
diff --git a/htdocs/core/modules/mailings/contacts2.modules.php b/htdocs/core/modules/mailings/contacts2.modules.php
index 08e92af45e867672d31417c92f7fe2d6c2310f2e..778b2182e1ab2b5beff150395382bd1fae3c4c0b 100644
--- a/htdocs/core/modules/mailings/contacts2.modules.php
+++ b/htdocs/core/modules/mailings/contacts2.modules.php
@@ -33,7 +33,7 @@ include_once DOL_DOCUMENT_ROOT.'/core/modules/mailings/modules_mailings.php';
 class mailing_contacts2 extends MailingTargets
 {
     var $name='ContactsByFunction';
-    // This label is used if no translation is found for key MailingModuleDescXXX where XXX=name is found
+	// This label is used if no translation is found for key XXX neither MailingModuleDescXXX where XXX=name is found
     var $desc='Add contacts by function';
     var $require_admin=0;
 
diff --git a/htdocs/core/modules/mailings/contacts3.modules.php b/htdocs/core/modules/mailings/contacts3.modules.php
index b9878fd1c834a27ad34c789ef68bc73aa488d750..2c142541023e8ddacad19486919174fdf979ab55 100644
--- a/htdocs/core/modules/mailings/contacts3.modules.php
+++ b/htdocs/core/modules/mailings/contacts3.modules.php
@@ -32,8 +32,8 @@ include_once DOL_DOCUMENT_ROOT.'/core/modules/mailings/modules_mailings.php';
 class mailing_contacts3 extends MailingTargets
 {
 	var $name='ContactsByCompanyCategory';
-    // This label is used if no translation is found for key MailingModuleDescXXX where XXX=name is found
-    var $desc='Add contacts by company category';
+	// This label is used if no translation is found for key XXX neither MailingModuleDescXXX where XXX=name is found
+	var $desc='Add contacts by company category';
     var $require_admin=0;
 
     var $require_module=array();
diff --git a/htdocs/core/modules/mailings/contacts4.modules.php b/htdocs/core/modules/mailings/contacts4.modules.php
index 421fd2676c84ae1f63f8e5cf3fb1013d092e24e7..a79d48a03e4b054dc45e2bf0e95df2ba88cb9bb9 100644
--- a/htdocs/core/modules/mailings/contacts4.modules.php
+++ b/htdocs/core/modules/mailings/contacts4.modules.php
@@ -32,8 +32,8 @@ include_once DOL_DOCUMENT_ROOT.'/core/modules/mailings/modules_mailings.php';
 class mailing_contacts4 extends MailingTargets
 {
 	var $name='ContactsByCategory';
-    // This label is used if no translation is found for key MailingModuleDescXXX where XXX=name is found
-    var $desc='Add contacts by category';
+	// This label is used if no translation is found for key XXX neither MailingModuleDescXXX where XXX=name is found
+	var $desc='Add contacts by category';
     var $require_admin=0;
 
     var $require_module=array();
diff --git a/htdocs/core/modules/mailings/example.modules.php b/htdocs/core/modules/mailings/example.modules.php
index f0f8b99e3c57354da82936d571bca9c316c70a1c..548510f81a0fa23fd841a8867c2fce444eaa38c4 100644
--- a/htdocs/core/modules/mailings/example.modules.php
+++ b/htdocs/core/modules/mailings/example.modules.php
@@ -32,7 +32,9 @@ class mailing_example extends MailingTargets
     var $desc='Put here a description';
 	// CHANGE THIS: Set to 1 if selector is available for admin users only
     var $require_admin=0;
-
+    // CHANGE THIS: Add a tooltip language key to add a tooltip help icon after the email target selector 
+    var $tooltip='MyTooltipLangKey';
+    
     var $require_module=array();
     var $picto='';
     var $db;
diff --git a/htdocs/core/modules/mailings/fraise.modules.php b/htdocs/core/modules/mailings/fraise.modules.php
index 089c42d495080494fd0f8f1194297bfc0673fa1a..05d9e525652fe3b171cf00aad74bce9f1a1d53a2 100644
--- a/htdocs/core/modules/mailings/fraise.modules.php
+++ b/htdocs/core/modules/mailings/fraise.modules.php
@@ -32,12 +32,10 @@ include_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  */
 class mailing_fraise extends MailingTargets
 {
-    // CHANGE THIS: Put here a name not already used
     var $name='FundationMembers';                    // Identifiant du module mailing
-    // CHANGE THIS: Put here a description of your selector module.
-    // This label is used if no translation found for key MailingModuleDescXXX where XXX=name is found
+	// This label is used if no translation is found for key XXX neither MailingModuleDescXXX where XXX=name is found
     var $desc='Foundation members with emails (by status)';
-    // CHANGE THIS: Set to 1 if selector is available for admin users only
+    // Set to 1 if selector is available for admin users only
     var $require_admin=0;
 
     var $require_module=array('adherent');
diff --git a/htdocs/core/modules/mailings/framboise.modules.php b/htdocs/core/modules/mailings/framboise.modules.php
index a30a9ba3c17ca2f2a8e1726da428c57eb39dd57e..82f7e51e0ef090b1487a7b3a9927d5bb7f91de4c 100644
--- a/htdocs/core/modules/mailings/framboise.modules.php
+++ b/htdocs/core/modules/mailings/framboise.modules.php
@@ -23,12 +23,10 @@ include_once DOL_DOCUMENT_ROOT.'/core/modules/mailings/modules_mailings.php';
  */
 class mailing_framboise extends MailingTargets
 {
-	// CHANGE THIS: Put here a name not already used
 	var $name='MembersCategories';
-	// CHANGE THIS: Put here a description of your selector module.
-	// This label is used if no translation found for key MailingModuleDescXXX where XXX=name is found
+	// This label is used if no translation is found for key XXX neither MailingModuleDescXXX where XXX=name is found
 	var $desc="Foundation members with emails (by categories)";
-	// CHANGE THIS: Set to 1 if selector is available for admin users only
+	// Set to 1 if selector is available for admin users only
 	var $require_admin=0;
 
 	var $require_module=array("adherent","categorie");
diff --git a/htdocs/core/modules/mailings/modules_mailings.php b/htdocs/core/modules/mailings/modules_mailings.php
index 16b930e8907f8dfbebfb07af6bef5bb3bad66818..1a97f3502b7278c924ba1a8a74bdf798dec72ee9 100644
--- a/htdocs/core/modules/mailings/modules_mailings.php
+++ b/htdocs/core/modules/mailings/modules_mailings.php
@@ -49,7 +49,7 @@ class MailingTargets    // This can't be abstract as it is used for some method
     /**
      * Return description of email selector
      *
-     * @return     string      Retourne la traduction de la cle MailingModuleDescXXX ou XXX nom du module, ou $this->desc si non trouve
+     * @return     string      Return translation of module label. Try translation of $this->name then translation of 'MailingModuleDesc'.$this->name, or $this->desc if not found
      */
     function getDesc()
     {
@@ -58,7 +58,9 @@ class MailingTargets    // This can't be abstract as it is used for some method
         $langs->load("mails");
         $transstring="MailingModuleDesc".$this->name;
         $s='';
-        if ($langs->trans($transstring) != $transstring) $s=$langs->trans($transstring);
+
+        if ($langs->trans($this->name) != $this->name) $s=$langs->trans($this->name);
+        elseif ($langs->trans($transstring) != $transstring) $s=$langs->trans($transstring);
         else $s=$this->desc;
 
         if ($this->tooltip && is_object($form)) $s .= ' '.$form->textwithpicto('', $langs->trans($this->tooltip), 1, 1);
diff --git a/htdocs/core/modules/mailings/pomme.modules.php b/htdocs/core/modules/mailings/pomme.modules.php
index 3db13ac824ceb215e26ab305218d0fbcdb310a38..5824f45636524c0ba7a227bac28dc95b4491bc84 100644
--- a/htdocs/core/modules/mailings/pomme.modules.php
+++ b/htdocs/core/modules/mailings/pomme.modules.php
@@ -31,6 +31,7 @@ include_once DOL_DOCUMENT_ROOT.'/core/modules/mailings/modules_mailings.php';
 class mailing_pomme extends MailingTargets
 {
 	var $name='DolibarrUsers';                      // Identifiant du module mailing
+	// This label is used if no translation is found for key XXX neither MailingModuleDescXXX where XXX=name is found
 	var $desc='Dolibarr users with emails';  		// Libelle utilise si aucune traduction pour MailingModuleDescXXX ou XXX=name trouv�e
 	var $require_module=array();                    // Module mailing actif si modules require_module actifs
 	var $require_admin=1;                           // Module mailing actif pour user admin ou non
diff --git a/htdocs/core/modules/mailings/thirdparties.modules.php b/htdocs/core/modules/mailings/thirdparties.modules.php
index cfccc1ff6733691cbaa5f8239864ce801ca64dc8..55cce13fbcfd13d06da21b8c19884f366511f96d 100644
--- a/htdocs/core/modules/mailings/thirdparties.modules.php
+++ b/htdocs/core/modules/mailings/thirdparties.modules.php
@@ -24,6 +24,7 @@ include_once DOL_DOCUMENT_ROOT.'/core/modules/mailings/modules_mailings.php';
 class mailing_thirdparties extends MailingTargets
 {
 	var $name='ContactsCategories';
+	// This label is used if no translation is found for key XXX neither MailingModuleDescXXX where XXX=name is found
 	var $desc="Third parties (by categories)";
 	var $require_admin=0;
 
diff --git a/htdocs/core/modules/mailings/thirdparties_services_expired.modules.php b/htdocs/core/modules/mailings/thirdparties_services_expired.modules.php
index 39790959b973b1d21f8777204e05c94ad8a8c1b9..de92354a964b4b4a4f1919eb60aaa1c99384fda8 100644
--- a/htdocs/core/modules/mailings/thirdparties_services_expired.modules.php
+++ b/htdocs/core/modules/mailings/thirdparties_services_expired.modules.php
@@ -23,6 +23,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
 class mailing_thirdparties_services_expired extends MailingTargets
 {
     var $name='DolibarrContractsLinesExpired';
+	// This label is used if no translation is found for key XXX neither MailingModuleDescXXX where XXX=name is found
     var $desc='Third parties with expired contract\'s lines';
     var $require_admin=0;
 
diff --git a/htdocs/core/modules/mailings/xinputfile.modules.php b/htdocs/core/modules/mailings/xinputfile.modules.php
index 04c4be3ce2e3135146e3f2b0035670bc4f87b9fd..152322c28990d0beb5b2b3bac8f9ff2e65d1543d 100644
--- a/htdocs/core/modules/mailings/xinputfile.modules.php
+++ b/htdocs/core/modules/mailings/xinputfile.modules.php
@@ -31,6 +31,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
 class mailing_xinputfile extends MailingTargets
 {
 	var $name='EmailsFromFile';              // Identifiant du module mailing
+	// This label is used if no translation is found for key XXX neither MailingModuleDescXXX where XXX=name is found
 	var $desc='EMails from a file';          // Libelle utilise si aucune traduction pour MailingModuleDescXXX ou XXX=name trouv�e
 	var $require_module=array();             // Module mailing actif si modules require_module actifs
 	var $require_admin=0;                    // Module mailing actif pour user admin ou non
diff --git a/htdocs/core/modules/mailings/xinputuser.modules.php b/htdocs/core/modules/mailings/xinputuser.modules.php
index 4c5567f574d71afe0fef3b7ab90eb3db26a65344..794de3d929418fe4d1f0dbb837013ec5a735dc86 100644
--- a/htdocs/core/modules/mailings/xinputuser.modules.php
+++ b/htdocs/core/modules/mailings/xinputuser.modules.php
@@ -31,6 +31,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
 class mailing_xinputuser extends MailingTargets
 {
 	var $name='EmailsFromUser';              // Identifiant du module mailing
+	// This label is used if no translation is found for key XXX neither MailingModuleDescXXX where XXX=name is found
 	var $desc='EMails input by user';        // Libelle utilise si aucune traduction pour MailingModuleDescXXX ou XXX=name trouv�e
 	var $require_module=array();            // Module mailing actif si modules require_module actifs
 	var $require_admin=0;                    // Module mailing actif pour user admin ou non
diff --git a/htdocs/core/modules/modProduct.class.php b/htdocs/core/modules/modProduct.class.php
index 195b59ed85d21b55fc209830d916aa360f0b8a58..28b51d1ce571d04b6102a3673d6695981b758065 100644
--- a/htdocs/core/modules/modProduct.class.php
+++ b/htdocs/core/modules/modProduct.class.php
@@ -169,7 +169,7 @@ class modProduct extends DolibarrModules
 		if (! empty($conf->global->EXPORTTOOL_CATEGORIES)) $this->export_entities_array[$r]=array_merge($this->export_entities_array[$r],array("group_concat(cat.label)"=>'category'));
 		if (! empty($conf->stock->enabled)) $this->export_entities_array[$r]=array_merge($this->export_entities_array[$r],array('p.stock'=>'product','p.pmp'=>'product'));
 		if (! empty($conf->barcode->enabled)) $this->export_entities_array[$r]=array_merge($this->export_entities_array[$r],array('p.barcode'=>'product'));
-		if (! empty($conf->fournisseur->enabled)) $this->export_entities_array[$r]=array_merge($this->export_entities_array[$r],array('s.nom'=>'product','pf.ref_fourn'=>'product','pf.unitprice'=>'product'));
+		if (! empty($conf->fournisseur->enabled)) $this->export_entities_array[$r]=array_merge($this->export_entities_array[$r],array('s.nom'=>'company','pf.ref_fourn'=>'product','pf.unitprice'=>'product'));
 		if (! empty($conf->global->MAIN_MULTILANGS)) $this->export_entities_array[$r]=array_merge($this->export_entities_array[$r],array('l.lang'=>'translation', 'l.label'=>'translation','l.description'=>'translation','l.note'=>'translation'));
 		$keyforselect='product'; $keyforelement='product'; $keyforaliasextra='extra';
 		include DOL_DOCUMENT_ROOT.'/core/extrafieldsinexport.inc.php';
@@ -211,7 +211,35 @@ class modProduct extends DolibarrModules
 			$this->export_sql_end[$r] .=' WHERE p.fk_product_type = 0 AND p.entity IN ('.getEntity("product", 1).')';
 		}
 
-
+		if (! empty($conf->global->PRODUIT_SOUSPRODUITS))
+		{
+        	$r++;
+    		$this->export_code[$r]=$this->rights_class.'_'.$r;
+    		$this->export_label[$r]="AssociatedProducts";	// Translation key (used only if key ExportDataset_xxx_z not found)
+    		$this->export_permission[$r]=array(array("produit","export"));
+    		$this->export_fields_array[$r]=array('p.rowid'=>"Id",'p.ref'=>"Ref",'p.label'=>"Label",'p.description'=>"Description",'p.url'=>"PublicUrl",'p.accountancy_code_sell'=>"ProductAccountancySellCode",'p.accountancy_code_buy'=>"ProductAccountancyBuyCode",'p.note'=>"Note",'p.length'=>"Length",'p.surface'=>"Surface",'p.volume'=>"Volume",'p.weight'=>"Weight",'p.customcode'=>'CustomCode','p.price_base_type'=>"PriceBase",'p.price'=>"UnitPriceHT",'p.price_ttc'=>"UnitPriceTTC",'p.tva_tx'=>'VATRate','p.tosell'=>"OnSell",'p.tobuy'=>"OnBuy",'p.datec'=>'DateCreation','p.tms'=>'DateModification');
+    		if (! empty($conf->stock->enabled)) $this->export_fields_array[$r]=array_merge($this->export_fields_array[$r],array('p.stock'=>'Stock','p.seuil_stock_alerte'=>'StockLimit','p.desiredstock'=>'DesiredStock','p.pmp'=>'PMPValue'));
+    		if (! empty($conf->barcode->enabled)) $this->export_fields_array[$r]=array_merge($this->export_fields_array[$r],array('p.barcode'=>'BarCode'));
+    		$this->export_fields_array[$r]=array_merge($this->export_fields_array[$r],array('pa.qty'=>'Qty','pa.incdec'=>'ComposedProductIncDecStock'));
+    		$this->export_TypeFields_array[$r]=array('p.ref'=>"Text",'p.label'=>"Text",'p.description'=>"Text",'p.url'=>"Text",'p.accountancy_code_sell'=>"Text",'p.accountancy_code_buy'=>"Text",'p.note'=>"Text",'p.length'=>"Numeric",'p.surface'=>"Numeric",'p.volume'=>"Numeric",'p.weight'=>"Numeric",'p.customcode'=>'Text','p.price_base_type'=>"Text",'p.price'=>"Numeric",'p.price_ttc'=>"Numeric",'p.tva_tx'=>'Numeric','p.tosell'=>"Boolean",'p.tobuy'=>"Boolean",'p.datec'=>'Date','p.tms'=>'Date');
+    		if (! empty($conf->stock->enabled)) $this->export_TypeFields_array[$r]=array_merge($this->export_TypeFields_array[$r],array('p.stock'=>'Numeric','p.seuil_stock_alerte'=>'Numeric','p.desiredstock'=>'Numeric','p.pmp'=>'Numeric','p.cost_price'=>'Numeric'));
+    		if (! empty($conf->barcode->enabled)) $this->export_TypeFields_array[$r]=array_merge($this->export_TypeFields_array[$r],array('p.barcode'=>'Text'));
+    		$this->export_TypeFields_array[$r]=array_merge($this->export_TypeFields_array[$r],array('pa.qty'=>'Numeric'));
+    		$this->export_entities_array[$r]=array('p.rowid'=>"virtualproduct",'p.ref'=>"virtualproduct",'p.label'=>"virtualproduct",'p.description'=>"virtualproduct",'p.url'=>"virtualproduct",'p.accountancy_code_sell'=>'virtualproduct','p.accountancy_code_buy'=>'virtualproduct','p.note'=>"virtualproduct",'p.length'=>"virtualproduct",'p.surface'=>"virtualproduct",'p.volume'=>"virtualproduct",'p.weight'=>"virtualproduct",'p.customcode'=>'virtualproduct','p.price_base_type'=>"virtualproduct",'p.price'=>"virtualproduct",'p.price_ttc'=>"virtualproduct",'p.tva_tx'=>"virtualproduct",'p.tosell'=>"virtualproduct",'p.tobuy'=>"virtualproduct",'p.datec'=>"virtualproduct",'p.tms'=>"virtualproduct");
+    		if (! empty($conf->stock->enabled)) $this->export_entities_array[$r]=array_merge($this->export_entities_array[$r],array('p.stock'=>'virtualproduct','p.seuil_stock_alerte'=>'virtualproduct','p.desiredstock'=>'virtualproduct','p.pmp'=>'virtualproduct'));
+    		if (! empty($conf->barcode->enabled)) $this->export_entities_array[$r]=array_merge($this->export_entities_array[$r],array('p.barcode'=>'virtualproduct'));
+            $this->export_entities_array[$r]=array_merge($this->export_entities_array[$r],array('pa.qty'=>"subproduct",'pa.incdec'=>'subproduct'));
+    		$keyforselect='product'; $keyforelement='product'; $keyforaliasextra='extra';
+    		include DOL_DOCUMENT_ROOT.'/core/extrafieldsinexport.inc.php';
+            $this->export_fields_array[$r]=array_merge($this->export_fields_array[$r],array('p2.rowid'=>"Id",'p2.ref'=>"Ref",'p2.label'=>"Label",'p2.description'=>"Description"));
+    		$this->export_entities_array[$r]=array_merge($this->export_entities_array[$r],array('p2.rowid'=>"subproduct",'p2.ref'=>"subproduct",'p2.label'=>"subproduct",'p2.description'=>"subproduct"));
+    		$this->export_sql_start[$r]='SELECT DISTINCT ';
+    		$this->export_sql_end[$r]  =' FROM '.MAIN_DB_PREFIX.'product as p';
+    		$this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'product_extrafields as extra ON p.rowid = extra.fk_object,';
+    		$this->export_sql_end[$r] .=' '.MAIN_DB_PREFIX.'product_association as pa, '.MAIN_DB_PREFIX.'product as p2';
+    		$this->export_sql_end[$r] .=' WHERE p.fk_product_type = 0 AND p.entity IN ('.getEntity("product", 1).')';
+    		$this->export_sql_end[$r] .=' AND p.rowid = pa.fk_product_pere AND p2.rowid = pa.fk_product_fils';
+		}		
 
 		// Imports
 		//--------
diff --git a/htdocs/core/tpl/login.tpl.php b/htdocs/core/tpl/login.tpl.php
index a9d7c73ae1a1e16510a96634a4aabedbe7a73ee1..3772b44c9fcec901c4f90d0bb4b11744636f37d3 100644
--- a/htdocs/core/tpl/login.tpl.php
+++ b/htdocs/core/tpl/login.tpl.php
@@ -16,6 +16,9 @@
  * along with this program. If not, see <http://www.gnu.org/licenses/>.
  */
 
+// Need global variable $title to be defined by caller (like dol_loginfunction)
+
+
 header('Cache-Control: Public, must-revalidate');
 header("Content-type: text/html; charset=".$conf->file->character_set_client);
 
@@ -35,7 +38,10 @@ $arrayofjs=array(
 );
 $titleofloginpage=$langs->trans('Login').' @ '.$titletruedolibarrversion;	// $titletruedolibarrversion is defined by dol_loginfunction in security2.lib.php. We must keep the @, some tools use it to know it is login page and find true dolibarr version.
 
-print top_htmlhead('',$titleofloginpage,0,0,$arrayofjs);
+$disablenofollow=1;
+if (! preg_match('/'.constant('DOL_APPLICATION_TITLE').'/', $title)) $disablenofollow=0;
+
+print top_htmlhead('', $titleofloginpage, 0, 0, $arrayofjs, array(), 0, $disablenofollow);
 ?>
 <!-- BEGIN PHP TEMPLATE LOGIN.TPL.PHP -->
 
@@ -71,7 +77,13 @@ $(document).ready(function () {
 <input type="hidden" name="dol_use_jmobile" id="dol_use_jmobile" value="<?php echo $dol_use_jmobile; ?>" />
 
 <table class="login_table_title center" title="<?php echo dol_escape_htmltag($title); ?>">
-<tr class="vmenu"><td class="center"><?php echo dol_escape_htmltag($title); ?></td></tr>
+<tr class="vmenu"><td class="center">
+<?php
+if ($disablenofollow) echo '<a class="login_table_title" href="https://www.dolibarr.org" target="_blank">';
+echo dol_escape_htmltag($title); 
+if ($disablenofollow) echo '</a>';
+?>
+</td></tr>
 </table>
 <br>
 
diff --git a/htdocs/core/tpl/objectline_view.tpl.php b/htdocs/core/tpl/objectline_view.tpl.php
index 62d4b0007edee067435a65c62133a8a52102f3ee..1c600655bdc1d8cbc22876883d37b37ff08fbdc9 100755
--- a/htdocs/core/tpl/objectline_view.tpl.php
+++ b/htdocs/core/tpl/objectline_view.tpl.php
@@ -70,19 +70,20 @@ if (empty($usemargins)) $usemargins=0;
 		<?php
 		if ($line->description)
 		{
-			if ($line->description == '(CREDIT_NOTE)' && $objp->fk_remise_except > 0)
+			if ($line->description == '(CREDIT_NOTE)' && $line->fk_remise_except > 0)
 			{
 				$discount=new DiscountAbsolute($this->db);
 				$discount->fetch($line->fk_remise_except);
 				echo ($txt?' - ':'').$langs->transnoentities("DiscountFromCreditNote",$discount->getNomUrl(0));
 			}
-			elseif ($line->description == '(DEPOSIT)' && $objp->fk_remise_except > 0)
+			elseif ($line->description == '(DEPOSIT)' && $line->fk_remise_except > 0)
 			{
 				$discount=new DiscountAbsolute($this->db);
 				$discount->fetch($line->fk_remise_except);
 				echo ($txt?' - ':'').$langs->transnoentities("DiscountFromDeposit",$discount->getNomUrl(0));
 				// Add date of deposit
-				if (! empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) echo ' ('.dol_print_date($discount->datec).')';
+				if (! empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) 
+				    echo ' ('.dol_print_date($discount->datec).')';
 			}
 			else
 			{
diff --git a/htdocs/exports/export.php b/htdocs/exports/export.php
index 604af2155817ebda12cc330e450a7a69bd98683d..01e963585ecae299e4edf6e822afea1691776976 100644
--- a/htdocs/exports/export.php
+++ b/htdocs/exports/export.php
@@ -61,6 +61,8 @@ $entitytoicon = array(
     'other'        => 'generic',
 	'account'      => 'account',
 	'product'      => 'product',
+    'virtualproduct'=>'product',
+	'subproduct'   => 'product',
     'warehouse'    => 'stock',
     'batch'        => 'stock',
 	'category'     => 'category',
@@ -93,6 +95,8 @@ $entitytolang = array(
 	'account'      => 'BankTransactions',
 	'payment'      => 'Payment',
 	'product'      => 'Product',
+	'virtualproduct'  => 'AssociatedProducts',
+	'subproduct'      => 'SubProduct',
     'service'      => 'Service',
     'stock'        => 'Stock',
     'batch'        => 'Batch',
diff --git a/htdocs/fourn/commande/info.php b/htdocs/fourn/commande/info.php
index d858dc7172c77363d4c738c5a2bfcfe00e5d0aac..50b310a55e5426f1aac221dac55f02b04a9c3702 100644
--- a/htdocs/fourn/commande/info.php
+++ b/htdocs/fourn/commande/info.php
@@ -45,7 +45,7 @@ if (GETPOST('actioncode','array'))
 }
 else
 {
-    $actioncode=GETPOST("actioncode","alpha",3)?GETPOST("actioncode","alpha",3):(GETPOST("actioncode")=='0'?'0':(empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE)?'':$conf->global->AGENDA_DEFAULT_FILTER_TYPE));
+    $actioncode=GETPOST("actioncode","alpha",3)?GETPOST("actioncode","alpha",3):(GETPOST("actioncode")=='0'?'0':(empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECTS)?'':$conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECTS));
 }
 $search_agenda_label=GETPOST('search_agenda_label');
 
diff --git a/htdocs/langs/en_US/mails.lang b/htdocs/langs/en_US/mails.lang
index 0c894cc7b19887afd698eeff3163e696b10c1794..c337b6e1119f9441fd8f4a9b67313baae85ee157 100644
--- a/htdocs/langs/en_US/mails.lang
+++ b/htdocs/langs/en_US/mails.lang
@@ -74,7 +74,11 @@ ResultOfMailSending=Result of mass EMail sending
 NbSelected=Nb selected
 NbIgnored=Nb ignored
 NbSent=Nb sent
-ContactsWithThirdpartyFilter=Contact with customer filters
+ConfirmUnvalidateEmailing=Are you sure you want to change email <b>%s</b> to draft status?
+MailingModuleDescContactsWithThirdpartyFilter=Contact with customer filters
+MailingModuleDescContactsByCompanyCategory=Contacts by third party category
+MailingModuleDescContactsByCategory=Contacts by categories
+MailingModuleDescContactsByFunction=Contacts by position
 
 # Libelle des modules de liste de destinataires mailing
 LineInFile=Line %s in file
diff --git a/htdocs/langs/en_US/products.lang b/htdocs/langs/en_US/products.lang
index 9af364c64a84afcdc4b6ec8bf7951836b1460bc7..0abf09b3442723aee50e0e4d63576a38f580d018 100644
--- a/htdocs/langs/en_US/products.lang
+++ b/htdocs/langs/en_US/products.lang
@@ -258,4 +258,4 @@ VolumeUnits=Volume unit
 SizeUnits=Size unit
 DeleteProductBuyPrice=Delete buying price
 ConfirmDeleteProductBuyPrice=Are you sure you want to delete this buying price?
-
+SubProduct=Sub product
diff --git a/htdocs/langs/en_US/projects.lang b/htdocs/langs/en_US/projects.lang
index 392e20697aa8d8df7accdac2b4c0464761c48ddc..8e40307cac68df6f6d5c181aaa725c226afe0299 100644
--- a/htdocs/langs/en_US/projects.lang
+++ b/htdocs/langs/en_US/projects.lang
@@ -96,6 +96,7 @@ ValidateProject=Validate projet
 ConfirmValidateProject=Are you sure you want to validate this project?
 CloseAProject=Close project
 ConfirmCloseAProject=Are you sure you want to close this project?
+AlsoCloseAProject=Also close project (keep it open if you still need to follow production tasks on it)
 ReOpenAProject=Open project
 ConfirmReOpenAProject=Are you sure you want to re-open this project?
 ProjectContact=Project contacts
@@ -121,7 +122,7 @@ CloneProjectFiles=Clone project joined files
 CloneTaskFiles=Clone task(s) joined files (if task(s) cloned)
 CloneMoveDate=Update project/tasks dates from now?
 ConfirmCloneProject=Are you sure to clone this project?
-ProjectReportDate=Change task date according project start date
+ProjectReportDate=Change task dates according to new project start date
 ErrorShiftTaskDate=Impossible to shift task date according to new project start date
 ProjectsAndTasksLines=Projects and tasks
 ProjectCreatedInDolibarr=Project %s created
diff --git a/htdocs/main.inc.php b/htdocs/main.inc.php
index 80c6b1b3dca4763e8aa6555326aaf232e7cfd114..960ea1ab2320662f7efa76dc633fd6f4571e7bea 100644
--- a/htdocs/main.inc.php
+++ b/htdocs/main.inc.php
@@ -993,9 +993,10 @@ function top_httphead()
  * @param 	array  	$arrayofjs		Array of complementary js files
  * @param 	array  	$arrayofcss		Array of complementary css files
  * @param 	int    	$disablejmobile	Disable jmobile
+ * @param   int     $disablenofollow Disable no follow tag
  * @return	void
  */
-function top_htmlhead($head, $title='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $disablejmobile=0)
+function top_htmlhead($head, $title='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $disablejmobile=0, $disablenofollow=0)
 {
     global $user, $conf, $langs, $db;
 
@@ -1017,13 +1018,13 @@ function top_htmlhead($head, $title='', $disablejs=0, $disablehead=0, $arrayofjs
         print "<head>\n";
 		if (GETPOST('dol_basehref')) print '<base href="'.dol_escape_htmltag(GETPOST('dol_basehref')).'">'."\n";
         // Displays meta
-        print '<meta name="robots" content="noindex,nofollow">'."\n";      				// Do not index
+        print '<meta name="robots" content="noindex'.($disablenofollow?'':',nofollow').'">'."\n";      				// Do not index
         print '<meta name="viewport" content="width=device-width, initial-scale=1.0">';	// Scale for mobile device
         print '<meta name="author" content="Dolibarr Development Team">'."\n";
 		$favicon=dol_buildpath('/theme/'.$conf->theme.'/img/favicon.ico',1);
         if (! empty($conf->global->MAIN_FAVICON_URL)) $favicon=$conf->global->MAIN_FAVICON_URL;
         print '<link rel="shortcut icon" type="image/x-icon" href="'.$favicon.'"/>'."\n";
-        if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && ! GETPOST('textbrowser')) print '<link rel="top" title="'.$langs->trans("Home").'" href="'.(DOL_URL_ROOT?DOL_URL_ROOT:'/').'">'."\n";
+        //if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && ! GETPOST('textbrowser')) print '<link rel="top" title="'.$langs->trans("Home").'" href="'.(DOL_URL_ROOT?DOL_URL_ROOT:'/').'">'."\n";
         if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && ! GETPOST('textbrowser')) print '<link rel="copyright" title="GNU General Public License" href="http://www.gnu.org/copyleft/gpl.html#SEC1">'."\n";
         if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && ! GETPOST('textbrowser')) print '<link rel="author" title="Dolibarr Development Team" href="https://www.dolibarr.org">'."\n";
 
diff --git a/htdocs/margin/agentMargins.php b/htdocs/margin/agentMargins.php
index 61cee328b41afd452ed210dd7fc2ab1869441c47..c7a0af0b6051d2e42c003ef8a17c3e708da34293 100644
--- a/htdocs/margin/agentMargins.php
+++ b/htdocs/margin/agentMargins.php
@@ -120,6 +120,7 @@ $sql = "SELECT";
 if ($agentid > 0) $sql.= " s.rowid as socid, s.nom as name, s.code_client, s.client,";
 $sql.= " u.rowid as agent, u.login, u.lastname, u.firstname,";
 $sql.= " sum(d.total_ht) as selling_price,";
+// Note: qty and buy_price_ht is always positive (if not your database may be corrupted, you can update this)
 $sql.= " sum(".$db->ifsql('d.total_ht < 0','d.qty * d.buy_price_ht * -1','d.qty * d.buy_price_ht').") as buying_price,";
 $sql.= " sum(".$db->ifsql('d.total_ht < 0','-1 * (abs(d.total_ht) - (d.buy_price_ht * d.qty))','d.total_ht - (d.buy_price_ht * d.qty)').") as marge" ;
 $sql.= " FROM ".MAIN_DB_PREFIX."societe as s";
@@ -171,6 +172,11 @@ if ($result)
 	print '<br>';
 	print_barre_liste($langs->trans("MarginDetails"),$page,$_SERVER["PHP_SELF"],"",$sortfield,$sortorder,'',$num,$num,'');
 
+	if ($conf->global->MARGIN_TYPE == "1")
+	    $labelcostprice=$langs->trans('BuyingPrice');
+	else   // value is 'costprice' or 'pmp'
+	    $labelcostprice=$langs->trans('CostPrice');
+	
 	$i = 0;
 	print "<table class=\"noborder\" width=\"100%\">";
 
@@ -181,7 +187,7 @@ if ($result)
 		print_liste_field_titre($langs->trans("SalesRepresentative"),$_SERVER["PHP_SELF"],"u.lastname","","&amp;agentid=".$agentid,'',$sortfield,$sortorder);
 
 	print_liste_field_titre($langs->trans("SellingPrice"),$_SERVER["PHP_SELF"],"selling_price","","&amp;agentid=".$agentid,'align="right"',$sortfield,$sortorder);
-	print_liste_field_titre($langs->trans("BuyingPrice"),$_SERVER["PHP_SELF"],"buying_price","","&amp;agentid=".$agentid,'align="right"',$sortfield,$sortorder);
+	print_liste_field_titre($labelcostprice,$_SERVER["PHP_SELF"],"buying_price","","&amp;agentid=".$agentid,'align="right"',$sortfield,$sortorder);
 	print_liste_field_titre($langs->trans("Margin"),$_SERVER["PHP_SELF"],"marge","","&amp;agentid=".$agentid,'align="right"',$sortfield,$sortorder);
 	if (! empty($conf->global->DISPLAY_MARGIN_RATES))
 		print_liste_field_titre($langs->trans("MarginRate"),$_SERVER["PHP_SELF"],"","","&amp;agentid=".$agentid,'align="right"',$sortfield,$sortorder);
diff --git a/htdocs/margin/checkMargins.php b/htdocs/margin/checkMargins.php
index 93f6e6915f94aee377f94eff839c93b23cd34885..b3c663ad886310134e1d8f64afe069736442bba5 100644
--- a/htdocs/margin/checkMargins.php
+++ b/htdocs/margin/checkMargins.php
@@ -179,6 +179,11 @@ if ($result) {
 	print '<br>';
 	print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, '', $num, $nbtotalofrecords, '');
 	
+	if ($conf->global->MARGIN_TYPE == "1")
+	    $labelcostprice=$langs->trans('BuyingPrice');
+	else   // value is 'costprice' or 'pmp'
+	    $labelcostprice=$langs->trans('CostPrice');
+	
 	$moreforfilter='';
 	
     print '<div class="div-table-responsive">';
@@ -189,11 +194,7 @@ if ($result) {
 	print_liste_field_titre($langs->trans("Ref"), $_SERVER["PHP_SELF"], "f.ref", "", $options, '', $sortfield, $sortorder);
 	print_liste_field_titre($langs->trans("Description"), $_SERVER["PHP_SELF"], "", "", $options, 'width=20%', $sortfield, $sortorder);
 	print_liste_field_titre($langs->trans("UnitPriceHT"), $_SERVER["PHP_SELF"], "d.subprice", "", $options, 'align="right"', $sortfield, $sortorder);
-	if ($conf->global->MARGIN_TYPE == "1") {
-		print_liste_field_titre($langs->trans("BuyingPrice"), $_SERVER["PHP_SELF"], "d.buy_price_ht", "", $options, 'align="right"', $sortfield, $sortorder);
-	} else {
-		print_liste_field_titre($langs->trans("CostPrice"), $_SERVER["PHP_SELF"], "d.buy_price_ht", "", $options, 'align="right"', $sortfield, $sortorder);
-	}
+	print_liste_field_titre($labelcostprice, $_SERVER["PHP_SELF"], "d.buy_price_ht", "", $options, 'align="right"', $sortfield, $sortorder);
 	print_liste_field_titre($langs->trans("Qty"), $_SERVER["PHP_SELF"], "d.qty", "", $options, 'align="right"', $sortfield, $sortorder);
 	print_liste_field_titre($langs->trans("AmountTTC"), $_SERVER["PHP_SELF"], "d.total_ht", "", $options, 'align="right"', $sortfield, $sortorder);
 	
diff --git a/htdocs/margin/customerMargins.php b/htdocs/margin/customerMargins.php
index 8b960a150a4efb896c7ee02f5fa09e1cf0db9de4..abfb89171ddd847b3b91ab7e1f1c8da4cd3c3f26 100644
--- a/htdocs/margin/customerMargins.php
+++ b/htdocs/margin/customerMargins.php
@@ -173,6 +173,7 @@ $sql = "SELECT";
 $sql.= " s.rowid as socid, s.nom as name, s.code_client, s.client,";
 if ($client) $sql.= " f.rowid as facid, f.facnumber, f.total as total_ht, f.datef, f.paye, f.fk_statut as statut,";
 $sql.= " sum(d.total_ht) as selling_price,";
+// Note: qty and buy_price_ht is always positive (if not your database may be corrupted, you can update this)
 $sql.= " sum(".$db->ifsql('d.total_ht < 0','d.qty * d.buy_price_ht * -1','d.qty * d.buy_price_ht').") as buying_price,";
 $sql.= " sum(".$db->ifsql('d.total_ht < 0','-1 * (abs(d.total_ht) - (d.buy_price_ht * d.qty))','d.total_ht - (d.buy_price_ht * d.qty)').") as marge";
 $sql.= " FROM ".MAIN_DB_PREFIX."societe as s";
@@ -207,6 +208,11 @@ if ($result)
   	print '<br>';
 	print_barre_liste($langs->trans("MarginDetails"),$page,$_SERVER["PHP_SELF"],"",$sortfield,$sortorder,'',$num,$num,'');
 
+	if ($conf->global->MARGIN_TYPE == "1")
+	    $labelcostprice=$langs->trans('BuyingPrice');
+	else   // value is 'costprice' or 'pmp'
+	    $labelcostprice=$langs->trans('CostPrice');
+	
 	$i = 0;
 	print "<table class=\"noborder\" width=\"100%\">";
 
@@ -218,7 +224,7 @@ if ($result)
 	else
   		print_liste_field_titre($langs->trans("Customer"),$_SERVER["PHP_SELF"],"s.nom","","&amp;socid=".$socid,'',$sortfield,$sortorder);
 	print_liste_field_titre($langs->trans("SellingPrice"),$_SERVER["PHP_SELF"],"selling_price","","&amp;socid=".$socid,'align="right"',$sortfield,$sortorder);
-	print_liste_field_titre($langs->trans("BuyingPrice"),$_SERVER["PHP_SELF"],"buying_price","","&amp;socid=".$socid,'align="right"',$sortfield,$sortorder);
+	print_liste_field_titre($labelcostprice,$_SERVER["PHP_SELF"],"buying_price","","&amp;socid=".$socid,'align="right"',$sortfield,$sortorder);
 	print_liste_field_titre($langs->trans("Margin"),$_SERVER["PHP_SELF"],"marge","","&amp;socid=".$socid,'align="right"',$sortfield,$sortorder);
 	if (! empty($conf->global->DISPLAY_MARGIN_RATES))
 		print_liste_field_titre($langs->trans("MarginRate"),$_SERVER["PHP_SELF"],"","","&amp;socid=".$socid,'align="right"',$sortfield,$sortorder);
diff --git a/htdocs/margin/lib/margins.lib.php b/htdocs/margin/lib/margins.lib.php
index 84d7945ec0d6ce393ec0a45a1e0a471e1ad13d99..d7dbd5d81eb478184a87f57c15f524c66625b58c 100644
--- a/htdocs/margin/lib/margins.lib.php
+++ b/htdocs/margin/lib/margins.lib.php
@@ -109,7 +109,7 @@ function marges_prepare_head()
  * @param 	float	$localtax2_tx		Vat rate special 2 (not used)
  * @param 	int		$fk_pa				Id of buying price (prefer set this to 0 and provide $paht instead. With id, buying price may have change)
  * @param 	float	$paht				Buying price without tax
- * @return	array						Array of margin info
+ * @return	array						Array of margin info (buying price, marge rate, marque rate)
  */
 function getMarginInfos($pvht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $paht)
 {
@@ -134,7 +134,7 @@ function getMarginInfos($pvht, $remise_percent, $tva_tx, $localtax1_tx, $localta
 	}
 	else
 	{
-		$paht_ret	= $paht;
+		$paht_ret = $paht;
 	}
 
 	// Calculate selling unit price including line discount
diff --git a/htdocs/margin/productMargins.php b/htdocs/margin/productMargins.php
index dcf80e9a49ccf81c776b466b5d105289fb7658ea..ff06d6ce69e38d95aa61a269e5da2309fe4c953e 100644
--- a/htdocs/margin/productMargins.php
+++ b/htdocs/margin/productMargins.php
@@ -169,6 +169,7 @@ $sql = "SELECT p.label, p.rowid, p.fk_product_type, p.ref, p.entity as pentity,"
 if ($id > 0) $sql.= " d.fk_product,";
 if ($id > 0) $sql.= " f.rowid as facid, f.facnumber, f.total as total_ht, f.datef, f.paye, f.fk_statut as statut,";
 $sql.= " SUM(d.total_ht) as selling_price,";
+// Note: qty and buy_price_ht is always positive (if not your database may be corrupted, you can update this)
 $sql.= " SUM(".$db->ifsql('d.total_ht < 0','d.qty * d.buy_price_ht * -1','d.qty * d.buy_price_ht').") as buying_price,";
 $sql.= " SUM(".$db->ifsql('d.total_ht < 0','-1 * (abs(d.total_ht) - (d.buy_price_ht * d.qty))','d.total_ht - (d.buy_price_ht * d.qty)').") as marge";
 $sql.= " FROM ".MAIN_DB_PREFIX."societe as s";
@@ -203,6 +204,11 @@ if ($result)
 	print '<br>';
 	print_barre_liste($langs->trans("MarginDetails"),$page,$_SERVER["PHP_SELF"],"&amp;id=".$id,$sortfield,$sortorder,'',$num,$num,'');
 
+	if ($conf->global->MARGIN_TYPE == "1")
+	    $labelcostprice=$langs->trans('BuyingPrice');
+	else   // value is 'costprice' or 'pmp'
+	    $labelcostprice=$langs->trans('CostPrice');
+	    
 	$moreforfilter='';
 	
 	$i = 0;
@@ -215,9 +221,11 @@ if ($result)
   		print_liste_field_titre($langs->trans("DateInvoice"),$_SERVER["PHP_SELF"],"f.datef","","&amp;id=".$id,'align="center"',$sortfield,$sortorder);
   	}
   	else
+  	{
   		print_liste_field_titre($langs->trans("ProductService"),$_SERVER["PHP_SELF"],"p.ref","","&amp;id=".$id,'',$sortfield,$sortorder);
+  	}
 	print_liste_field_titre($langs->trans("SellingPrice"),$_SERVER["PHP_SELF"],"selling_price","","&amp;id=".$id,'align="right"',$sortfield,$sortorder);
-	print_liste_field_titre($langs->trans("BuyingPrice"),$_SERVER["PHP_SELF"],"buying_price","","&amp;id=".$id,'align="right"',$sortfield,$sortorder);
+	print_liste_field_titre($labelcostprice,$_SERVER["PHP_SELF"],"buying_price","","&amp;id=".$id,'align="right"',$sortfield,$sortorder);
 	print_liste_field_titre($langs->trans("Margin"),$_SERVER["PHP_SELF"],"marge","","&amp;id=".$id,'align="right"',$sortfield,$sortorder);
 	if (! empty($conf->global->DISPLAY_MARGIN_RATES))
 		print_liste_field_titre($langs->trans("MarginRate"),$_SERVER["PHP_SELF"],"","","&amp;id=".$id,'align="right"',$sortfield,$sortorder);
diff --git a/htdocs/product/card.php b/htdocs/product/card.php
index 5a7158cd190165476099203e43567c3f8b03a1e5..66abe3df5568e67cdd6628698cf55ee95a2223f2 100644
--- a/htdocs/product/card.php
+++ b/htdocs/product/card.php
@@ -1156,7 +1156,7 @@ else
 
 		print '<div class="center">';
 		print '<input type="submit" class="button" value="' . $langs->trans("Create") . '">';
-		print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
+        print ' &nbsp; &nbsp; ';
 		print '<input type="button" class="button" value="' . $langs->trans("Cancel") . '" onClick="javascript:history.go(-1)">';
 		print '</div>';
 
diff --git a/htdocs/product/stock/massstockmove.php b/htdocs/product/stock/massstockmove.php
index 944cc27dffb669172512fb190d2e3351ef3fe707..03c0ebd78ba756d442c6d3c0cc512684be955dba 100644
--- a/htdocs/product/stock/massstockmove.php
+++ b/htdocs/product/stock/massstockmove.php
@@ -342,7 +342,7 @@ print '<input type="hidden" name="token" value="' .$_SESSION['newtoken'] . '">';
 print '<input type="hidden" name="action" value="addline">';
 
 
-print '<div class="div-table-responsive">';
+print '<div class="div-table-responsive-no-max">';
 print '<table class="liste" width="100%">';
 //print '<div class="tagtable centpercent">';
 
diff --git a/htdocs/product/stock/replenishorders.php b/htdocs/product/stock/replenishorders.php
index 785760ef5111c69e8068069ae2027fb9069a001f..4986d7c524d579199eff769b5159f60b11f496ce 100644
--- a/htdocs/product/stock/replenishorders.php
+++ b/htdocs/product/stock/replenishorders.php
@@ -39,6 +39,41 @@ $langs->load("orders");
 if ($user->societe_id) $socid=$user->societe_id;
 $result=restrictedArea($user,'produit|service');
 
+$sref = GETPOST('search_ref', 'alpha');
+$snom = GETPOST('search_nom', 'alpha');
+$suser = GETPOST('search_user', 'alpha');
+$sttc = GETPOST('search_ttc', 'alpha');
+$sall = GETPOST('search_all', 'alpha');
+$sdate = GETPOST('search_date', 'alpha');
+$page = GETPOST('page', 'int');
+$sproduct = GETPOST('sproduct', 'int');
+
+$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit;
+$sortfield = GETPOST("sortfield");
+$sortorder = GETPOST("sortorder");
+if (!$sortorder) $sortorder = 'DESC';
+if (!$sortfield) $sortfield = 'cf.date_creation';
+$page = GETPOST("page");
+if ($page < 0) $page = 0;
+$offset = $limit * $page;
+
+
+
+/*
+ * Actions
+ */
+
+if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers
+{
+    $sall="";
+    $sref="";
+    $snom="";
+    $suser="";
+    $sttc="";
+    $sdate='';
+    $sproduct=0;
+}
+
 
 
 /*
@@ -65,21 +100,6 @@ $head[1][2] = 'replenishorders';
 dol_fiche_head($head, 'replenishorders', '', 0, '');
 
 $commandestatic = new CommandeFournisseur($db);
-$sref = GETPOST('search_ref', 'alpha');
-$snom = GETPOST('search_nom', 'alpha');
-$suser = GETPOST('search_user', 'alpha');
-$sttc = GETPOST('search_ttc', 'int');
-$sall = GETPOST('search_all', 'alpha');
-$sdate = GETPOST('search_date', 'alpha');
-$page = GETPOST('page', 'int');
-$sproduct = GETPOST('sproduct', 'int');
-$sortorder = GETPOST('sortorder', 'alpha');
-$sortfield = GETPOST('sortfield', 'alpha');
-
-if (!$sortorder) $sortorder = 'DESC';
-if (!$sortfield) $sortfield = 'cf.date_creation';
-
-$offset = $conf->liste_limit * $page ;
 
 $sql = 'SELECT s.rowid as socid, s.nom as name, cf.date_creation as dc,';
 $sql.= ' cf.rowid, cf.ref, cf.fk_statut, cf.total_ttc, cf.fk_user_author,';
@@ -101,25 +121,10 @@ if ($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) {
 if (!$user->rights->societe->client->voir && !$socid) {
     $sql .= ' AND s.rowid = sc.fk_soc AND sc.fk_user = ' . $user->id;
 }
-if ($sref) {
-    //natural search
-    $scrit = explode(' ', $sref);
-    foreach ($scrit as $crit) {
-        $sql .= ' AND cf.ref LIKE "%' . $db->escape($crit) . '%"';
-    }
-}
-if ($snom) {
-    $scrit = explode(' ', $snom);
-    foreach ($scrit as $crit) {
-        $sql .= ' AND s.nom LIKE "%' . $db->escape($crit) . '%"';
-    }
-}
-if ($suser) {
-    $sql .= ' AND u.login LIKE "%' . $db->escape($suser) . '%"';
-}
-if ($sttc) {
-    $sql .= ' AND cf.total_ttc = ' . price2num($sttc);
-}
+if ($sref) $sql .= natural_search('cf.ref', $sref);
+if ($snom) $sql .= natural_search('s.nom', $snom);
+if ($suser) $sql .= natural_search('u.login', $suser);
+if ($sttc) $sql .= natural_search('cf.total_ttc', $sttc, 1);
 if ($sdate)
 {
     if (GETPOST('search_datemonth', 'int') && GETPOST('search_dateday', 'int') && GETPOST('search_dateyear', 'int'))
@@ -132,21 +137,15 @@ if ($sdate)
     }
     $sql .= " AND cf.date_creation = '" . $db->idate($date) . "'";
 }
-if ($sall) {
-    $sql .= ' AND (cf.ref LIKE "%' . $db->escape($sall) . '%" ';
-    $sql .= 'OR cf.note LIKE "%' . $db->escape($sall) . '%")';
-}
-if (!empty($socid)) {
-    $sql .= ' AND s.rowid = ' . $socid;
-}
-
+if ($sall) $sql .= natural_search(array('cf.ref','cf.note'), $sall);
+if (!empty($socid)) $sql .= ' AND s.rowid = ' . $socid;
 if (GETPOST('statut', 'int')) {
     $sql .= ' AND fk_statut = ' . GETPOST('statut', 'int');
 }
 $sql .= ' GROUP BY cf.rowid, cf.ref, cf.date_creation, cf.fk_statut';
 $sql .= ', cf.total_ttc, cf.fk_user_author, u.login, s.rowid, s.nom';
 $sql .= $db->order($sortfield, $sortorder);
-$sql .= $db->plimit($conf->liste_limit+1, $offset);
+$sql .= $db->plimit($limit+1, $offset);
 //print $sql;
 
 $resql = $db->query($sql);
@@ -242,9 +241,8 @@ if ($resql)
          $form->select_date('', 'search_date', 0, 0, 1, '', 1, 0, 1, 0, '').
          '</td>'.
          '<td class="liste_titre" align="right">';
-    $src = DOL_URL_ROOT . '/theme/' . $conf->theme . '/img/search.png';
-    $value = dol_escape_htmltag($langs->trans('Search'));
-    print '<input type="image" class="liste_titre" name="button_search" src="' . $src . '" value="' . $value . '" title="' . $value . '">'.
+         $searchpitco=$form->showFilterAndCheckAddButtons(0);
+         print $searchpitco;
          '</td>'.
          '</tr>';
 
diff --git a/htdocs/projet/activity/perday.php b/htdocs/projet/activity/perday.php
index e694d6630a92c537076cd4b49a691bbdc25f886b..195ad3dbd89af5cbf1cd30a7c5e241baff56b475 100644
--- a/htdocs/projet/activity/perday.php
+++ b/htdocs/projet/activity/perday.php
@@ -427,7 +427,7 @@ 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_PERDAY_SHOW_THIRDPARTY)) print '<td class="liste_total"><input type="text" size="4" name="search_thirdparty" value="'.dol_escape_htmltag($search_thirdparty).'"></td>';
+if (! empty($conf->global->PROJECT_LINES_PERDAY_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>';
diff --git a/htdocs/projet/activity/perweek.php b/htdocs/projet/activity/perweek.php
index 584923636f0ac183c7cb9d44c6d99f3d15d6cccf..9a34913b2f568e0d5006d9d212332f2164383a45 100644
--- a/htdocs/projet/activity/perweek.php
+++ b/htdocs/projet/activity/perweek.php
@@ -427,7 +427,7 @@ 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_total"><input type="text" size="4" name="search_thirdparty" value="'.dol_escape_htmltag($search_thirdparty).'"></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>';
diff --git a/htdocs/projet/card.php b/htdocs/projet/card.php
index 71f2dcd02c9cde75b824156f072bc8474e4fdbe4..6221e4c2b8777c0b1b1b8b65afed0822d1094984 100644
--- a/htdocs/projet/card.php
+++ b/htdocs/projet/card.php
@@ -286,11 +286,23 @@ if (empty($reshook))
 	    		if ($result < 0)
 	    		{
 	    			$error++;
-				    setEventMessages($langs->trans("ErrorShiftTaskDate").':'.$object->error, $langs->trans("ErrorShiftTaskDate").':'.$object->errors, 'errors');
+				    setEventMessages($langs->trans("ErrorShiftTaskDate").':'.$object->error, $object->errors, 'errors');
 	    		}
 	    	}
 	    }
 
+		// Check if we must change status
+	    if (GETPOST('closeproject'))
+	    {
+	        $resclose = $object->setClose($user);
+	        if ($resclose < 0)
+	        {
+	            $error++;
+			    setEventMessages($langs->trans("FailedToCloseProject").':'.$object->error, $object->errors, 'errors');
+	        }
+	    }
+	    
+	    
 	    if ($error)
 	    {
 			$db->rollback();
@@ -303,6 +315,7 @@ if (empty($reshook))
 			if (GETPOST('socid','int') > 0) $object->fetch_thirdparty(GETPOST('socid','int'));
 			else unset($object->thirdparty);
 	    }
+	    
 	}
 
 	// Build doc
@@ -594,6 +607,11 @@ if ($action == 'create' && $user->rights->projet->creer)
         print ' &nbsp; &nbsp; ';
 	    print '<input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">';
     }
+    else
+    {
+        print ' &nbsp; &nbsp; ';
+        print '<input type="button" class="button" value="' . $langs->trans("Cancel") . '" onClick="javascript:history.go(-1)">';
+    }    
     print '</div>';
 
     print '</form>';
@@ -730,7 +748,11 @@ elseif ($object->id > 0)
 	        // Opportunity status
 		    print '<tr><td>'.$langs->trans("OpportunityStatus").'</td>';
 	    	print '<td>';
-		    print $formproject->selectOpportunityStatus('opp_status', $object->opp_status, 1);
+		    print $formproject->selectOpportunityStatus('opp_status', $object->opp_status, 1, 0, 0, 0, 'inline-block valignmiddle');
+		    print '<div id="divtocloseproject" class="inline-block valign" style="display: none;"> &nbsp; &nbsp; ';
+		    print '<input type="checkbox" id="inputcloseproject" name="closeproject" /> ';
+		    print $langs->trans("AlsoCloseAProject");
+		    print '</div>';
 		    print '</td>';
 		    print '</tr>';
 
@@ -843,12 +865,12 @@ elseif ($object->id > 0)
 
 	        // Opportunity percent
 	        print '<tr><td>'.$langs->trans("OpportunityProbability").'</td><td>';
-	        if (strcmp($object->opp_percent,'')) print price($object->opp_percent,'',$langs,1,0).' %';
+	        if (strcmp($object->opp_percent,'')) print price($object->opp_percent,0,$langs,1,0).' %';
 	        print '</td></tr>';
 
 	        // Opportunity Amount
 	        print '<tr><td>'.$langs->trans("OpportunityAmount").'</td><td>';
-	        if (strcmp($object->opp_amount,'')) print price($object->opp_amount,'',$langs,1,0,0,$conf->currency);
+	        if (strcmp($object->opp_amount,'')) print price($object->opp_amount,0,$langs,1,0,0,$conf->currency);
 	        print '</td></tr>';
 	    }
     
@@ -865,7 +887,7 @@ elseif ($object->id > 0)
     	     
         // Budget
         print '<tr><td>'.$langs->trans("Budget").'</td><td>';
-        if (strcmp($object->budget_amount, '')) print price($object->budget_amount,'',$langs,1,0,0,$conf->currency);
+        if (strcmp($object->budget_amount, '')) print price($object->budget_amount,0,$langs,1,0,0,$conf->currency);
         print '</td></tr>';
 
         // Other attributes
@@ -915,27 +937,49 @@ elseif ($object->id > 0)
     print '</form>';
 
     // Change probability from status
-    if (! empty($conf->use_javascript_ajax))
+    if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PROJECT_USE_OPPORTUNITIES))
     {
+        $defaultcheckedwhenoppclose=1;
+        if (empty($conf->global->PROJECT_HIDE_TASKS)) $defaultcheckedwhenoppclose=0;
+        
+        print '<!-- Javascript to manage opportunity status change -->';
         print '<script type="text/javascript" language="javascript">
-        jQuery(document).ready(function() {
-        	function change_percent()
-        	{
-                var element = jQuery("#opp_status option:selected");
-                var defaultpercent = element.attr("defaultpercent");
-                var elemcode = element.attr("elemcode");
-                /* Change percent of default percent of new status is higher */
-                if (parseFloat(jQuery("#opp_percent").val()) != parseFloat(defaultpercent))
-                {
-                    if (jQuery("#opp_percent").val() != \'\' && ! jQuery("#oldopppercent").text()) jQuery("#oldopppercent").text(\' - '.dol_escape_js($langs->transnoentities("PreviousValue")).': \'+jQuery("#opp_percent").val()+\' %\');
-                    jQuery("#opp_percent").val(defaultpercent);
-
-                }
-        	}
-        	/*init_myfunc();*/
-        	jQuery("#opp_status").change(function() {
-        		change_percent();
-        	});
+            jQuery(document).ready(function() {
+            	function change_percent()
+            	{
+                    var element = jQuery("#opp_status option:selected");
+                    var defaultpercent = element.attr("defaultpercent");
+                    var defaultcloseproject = '.$defaultcheckedwhenoppclose.';
+                    var elemcode = element.attr("elemcode");
+                    var oldpercent = \''.dol_escape_js($object->opp_percent).'\';
+
+                    console.log("We select "+elemcode);
+                    if (elemcode == \'LOST\') defaultcloseproject = 1;
+                    jQuery("#divtocloseproject").show();
+                    if (defaultcloseproject) jQuery("#inputcloseproject").prop("checked", true);
+                    else jQuery("#inputcloseproject").prop("checked", false);
+                        
+                    /* Make close project visible or not */
+                    if (elemcode == \'WON\' || elemcode == \'LOST\') 
+                    {
+                        jQuery("#divtocloseproject").show();
+                    }
+                    else
+                    {
+                        jQuery("#divtocloseproject").hide();
+                    }
+                        
+                    /* Change percent of default percent of new status is higher */
+                    if (parseFloat(jQuery("#opp_percent").val()) != parseFloat(defaultpercent))
+                    {
+                        if (jQuery("#opp_percent").val() != \'\' && oldpercent != \'\') jQuery("#oldopppercent").text(\' - '.dol_escape_js($langs->transnoentities("PreviousValue")).': \'+oldpercent+\' %\');
+                        jQuery("#opp_percent").val(defaultpercent);
+                    }
+            	}
+
+            	jQuery("#opp_status").change(function() {
+            		change_percent();
+            	});
         });
         </script>';
     }
diff --git a/htdocs/projet/class/project.class.php b/htdocs/projet/class/project.class.php
index 65c4e6bc94cf0a15c287bf9a9e621247047e8b4b..4a0c12c040ead1b1017f6441386f9f39195a62e4 100644
--- a/htdocs/projet/class/project.class.php
+++ b/htdocs/projet/class/project.class.php
@@ -773,7 +773,7 @@ class Project extends CommonObject
      * 		Close a project
      *
      * 		@param		User	$user		User that close project
-     * 		@return		int					<0 if KO, >0 if OK
+     * 		@return		int					<0 if KO, 0 if already closed, >0 if OK
      */
     function setClose($user)
     {
@@ -828,6 +828,8 @@ class Project extends CommonObject
                 return -1;
             }
         }
+        
+        return 0;
     }
 
     /**
diff --git a/htdocs/projet/info.php b/htdocs/projet/info.php
index de27a36353393585af00c7db30b22b72ffea2c19..65a95e232ff90877c210f88279da374aae8d00e1 100644
--- a/htdocs/projet/info.php
+++ b/htdocs/projet/info.php
@@ -54,7 +54,7 @@ if (GETPOST('actioncode','array'))
 }
 else
 {
-    $actioncode=GETPOST("actioncode","alpha",3)?GETPOST("actioncode","alpha",3):(GETPOST("actioncode")=='0'?'0':(empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE)?'':$conf->global->AGENDA_DEFAULT_FILTER_TYPE));
+    $actioncode=GETPOST("actioncode","alpha",3)?GETPOST("actioncode","alpha",3):(GETPOST("actioncode")=='0'?'0':(empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT)?'':$conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT));
 }
 $search_agenda_label=GETPOST('search_agenda_label');
 
diff --git a/htdocs/public/demo/index.php b/htdocs/public/demo/index.php
index e50193d8d5151b04944cbf0f40735ce41c6192f8..4c7c8cbebc89bb7ed210db7d72162ee56e4277dc 100644
--- a/htdocs/public/demo/index.php
+++ b/htdocs/public/demo/index.php
@@ -228,8 +228,8 @@ if (GETPOST("action") == 'gotodemo')
  */
 
 $head='';
-$head.='<meta name="keywords" content="dolibarr,demo,online,demonstration,example,test,web,erp,crm,demos,online">'."\n";
-$head.='<meta name="description" content="Dolibarr simple ERP/CRM demo. You can test here several profiles of Dolibarr ERP/CRM demos.">'."\n";
+$head.='<meta name="keywords" content="demo,online,demonstration,example,test,erp,crm,demos,web">'."\n";
+$head.='<meta name="description" content="Dolibarr ERP and CRM demo. You can test here several profiles for Dolibarr ERP and CRM demonstration.">'."\n";
 $head.='<style type="text/css">'."\n";
 $head.='.body { font: 12px arial,verdana,helvetica !important; }'."\n";
 $head.='.CTable {
@@ -244,10 +244,6 @@ border: 1px solid #bbb;
 border-radius: 8px;
 -moz-border-radius: 8px;
 
--moz-box-shadow: 4px 4px 4px #EEE;
--webkit-box-shadow: 4px 4px 4px #EEE;
-box-shadow: 4px 4px 4px #EEE;
-
 background: -webkit-linear-gradient(bottom, rgb(255,255,255) 85%, rgb(255,255,255) 100%);
 
 }
@@ -316,7 +312,7 @@ print "\n";
 print '<table style="font-size:14px;" class="centpercent" summary="Main table for Dolibarr demos">';
 
 print '<tr><td>';
-print '<div class="center"><img src="'.DOL_URL_ROOT.'/theme/dolibarr_logo.png" alt="Dolibarr logo"></div><br>';
+print '<div class="center"><a alt="Official portal of your ERP CRM application" targe="_blank" href="https://www.dolibarr.org"><img class="demologo" src="'.DOL_URL_ROOT.'/theme/dolibarr_logo.png" alt="Dolibarr logo"></a></div><br>';
 print '<br>';
 
 print '<div style="text-align: justify;">'.$langs->trans("DemoDesc").'</div><br>';
@@ -358,7 +354,7 @@ foreach ($demoprofiles as $profilearray)
         print '<input type="hidden" name="dol_no_mouse_hover" value="'.$conf->dol_no_mouse_hover.'">'."\n";
         print '<input type="hidden" name="dol_use_jmobile" value="'.$conf->dol_use_jmobile.'">'."\n";
 
-        print '<table summary="Dolibarr online demonstration for profile '.$profilearray['label'].'" style="font-size:14px;" width="100%" class="CTable CTableRow'.($i%2==0?'1':'0').'">'."\n";
+        print '<table summary="Dolibarr online demonstration for profile '.$profilearray['label'].'" style="font-size:14px;" class="centpercent CTable CTableRow'.($i%2==0?'1':'0').'">'."\n";
 		// Title
         print '<tr>';
 		print '<td width="130" id="a1'.$profilearray['key'].'" class="'.(empty($profilearray['url'])?'modulelineshow cursorpointer':'nomodulelines').'"><a href="'.$urlwithmod.'" class="'.(empty($profilearray['url'])?'modulelineshow':'nomodulelines').'"><img class="demothumb" src="'.$profilearray['icon'].'" alt="Demo '.$profilearray['label'].'"></a></td>';
@@ -481,7 +477,7 @@ function llxHeaderVierge($title, $head = "")
 
     top_htmlhead($head,$title);
 
-    print '<body style="padding: 20px;">'."\n";
+    print '<body class="demobody demobackground"><div style="padding: 20px;" class="demobackgrounddiv">'."\n";
 }
 
 /**
@@ -494,7 +490,7 @@ function llxFooterVierge()
     printCommonFooter('public');
 
     print "\n";
-    print "</body>\n";
+    print "</div></body>\n";
     print "</html>\n";
 }
 
diff --git a/htdocs/societe/agenda.php b/htdocs/societe/agenda.php
index 25eb78cfe246922e9b16c825affcb33724f642f3..644cda92bc4dc6527ab2afd2e47c87a009c0c7a6 100644
--- a/htdocs/societe/agenda.php
+++ b/htdocs/societe/agenda.php
@@ -41,7 +41,7 @@ if (GETPOST('actioncode','array'))
 }
 else
 {
-    $actioncode=GETPOST("actioncode","alpha",3)?GETPOST("actioncode","alpha",3):(GETPOST("actioncode")=='0'?'0':(empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE)?'':$conf->global->AGENDA_DEFAULT_FILTER_TYPE));
+    $actioncode=GETPOST("actioncode","alpha",3)?GETPOST("actioncode","alpha",3):(GETPOST("actioncode")=='0'?'0':(empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT)?'':$conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT));
 }
 $search_agenda_label=GETPOST('search_agenda_label');
 
diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php
index 05678ddb8214d6ccc3eae55a61d2b9e8c3ab28cf..76ea99b87200ce4ac94acca0c024b48d93e7559d 100644
--- a/htdocs/societe/class/societe.class.php
+++ b/htdocs/societe/class/societe.class.php
@@ -503,10 +503,9 @@ class Societe extends CommonObject
             }
             else
             {
-                if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
+                if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
                 {
-
-                    $this->error=$langs->trans("ErrorCompanyNameAlreadyExists",$this->name);
+                    $this->error=$langs->trans("ErrorCompanyNameAlreadyExists",$this->name);    // duplicate on a field (code or profid or ...)
                     $result=-1;
                 }
                 else
diff --git a/htdocs/societe/soc.php b/htdocs/societe/soc.php
index 36fe26447fa7c6c949f8eb65a278c943ecb32b2a..3da099390ac942e5d00af317fc775749adb3578d 100644
--- a/htdocs/societe/soc.php
+++ b/htdocs/societe/soc.php
@@ -514,8 +514,8 @@ if (empty($reshook))
                 }
                 else
 				{
-					
-					if($result == -3) {
+				    if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') // TODO Sometime errors on duplicate on profid and not on code, so we must manage this case
+					{
 						$duplicate_code_error = true;
 						$object->code_fournisseur = null;
 						$object->code_client = null;
@@ -1308,11 +1308,16 @@ else
 
         print '<div class="center">';
         print '<input type="submit" class="button" name="create" value="'.$langs->trans('AddThirdParty').'">';
-        if ($backtopage)
+        if (! empty($backtopage))
         {
-            print ' &nbsp; ';
+            print ' &nbsp; &nbsp; ';
             print '<input type="submit" class="button" name="cancel" value="'.$langs->trans('Cancel').'">';
         }
+        else
+        {
+            print ' &nbsp; &nbsp; ';
+            print '<input type="button" class="button" value="' . $langs->trans("Cancel") . '" onClick="javascript:history.go(-1)">';
+        }
         print '</div>'."\n";
 
         print '</form>'."\n";
@@ -1898,7 +1903,7 @@ else
 
             print '<div align="center">';
             print '<input type="submit" class="button" name="save" value="'.$langs->trans("Save").'">';
-            print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
+            print ' &nbsp; &nbsp; ';
             print '<input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">';
             print '</div>';
 
diff --git a/htdocs/theme/eldy/style.css.php b/htdocs/theme/eldy/style.css.php
index d9ed0f7960cf7a5fd394122645ac40ccfa6686fa..34536323ec627477308a0714177e39c4a1423312 100644
--- a/htdocs/theme/eldy/style.css.php
+++ b/htdocs/theme/eldy/style.css.php
@@ -2780,6 +2780,9 @@ tr.even td, tr.pair td, tr.odd td, tr.impair td, form.odd div.tagtd, form.impair
     padding: 5px 2px 5px 3px;
     border-bottom: 1px solid #ddd;
 }
+form.pair, form.impair {
+	font-weight: normal;
+}
 form.tagtr:last-of-type div.tagtd, tr.even:last-of-type td, tr.pair:last-of-type td, tr.odd:last-of-type td, tr.impair:last-of-type td {
     border-bottom: 0px !important;
 }
@@ -4552,6 +4555,14 @@ img.demothumb {
     margin-left: 10px;
 }
 
+.demobackground {
+    /*
+    background-image: url(/dolibarr_5.0/htdocs/theme/image-demo.jpg);
+    background-size: cover;
+    object-fit: contain;
+    */
+}
+
 
 
 /* ============================================================================== */
diff --git a/htdocs/theme/md/style.css.php b/htdocs/theme/md/style.css.php
index 79f608005641446663a31c41d8f98b3c3ad4ca51..f1f783f448f2770661235877c94a089e83bfd291 100644
--- a/htdocs/theme/md/style.css.php
+++ b/htdocs/theme/md/style.css.php
@@ -2653,6 +2653,9 @@ tr.even td, tr.pair td, tr.odd td, tr.impair td, form.odd div.tagtd, form.impair
     padding: 5px 2px 5px 3px;
     border-bottom: 1px solid #eee;
 }
+form.pair, form.impair {
+	font-weight: normal;
+}
 tr.even:last-of-type td, tr.pair:last-of-type td, tr.odd:last-of-type td, tr.impair:last-of-type td {
     border-bottom: 0px !important;
 }