diff --git a/ChangeLog b/ChangeLog
index bbfeb367955e7542e33a8fc702464bf5152046e8..2eca52d30a7a592c762d03bfed71f9adf503f9ea 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -105,6 +105,7 @@ WARNING: If you used external modules, some of them may need to be upgraded due
 - Fix: [ bug #774 ] Bug on creating event with box "all day" crossed
 - Fix: [ bug #810 ] Cannot update ODT template path
 - Fix: [ bug #824 ] MAIN_DB_PREFIX not use into dictionnary
+- Fix: [ bug #828 ] Error when code_region is not a number in llx_c_regions (with postgres)
 
 
 ***** ChangeLog for 3.3.1 compared to 3.3 *****
diff --git a/htdocs/admin/carrier.php b/htdocs/admin/carrier.php
deleted file mode 100644
index edb995d3fe7cd02a4de6888d72a8e4c5044fe379..0000000000000000000000000000000000000000
--- a/htdocs/admin/carrier.php
+++ /dev/null
@@ -1,222 +0,0 @@
-<?php
-/*
- * Copyright (C) 2013 Laurent Destailleur   <eldy@users.sourceforge.net>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-/**
- *  \file       htdocs/admin/carrier.php
- *  \ingroup    expedition
- *  \brief      Page to setup carriers. TODO Delete this page. We mut use dictionnary instead.
- */
-
-require '../main.inc.php';
-require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
-require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
-
-$langs->load("admin");
-$langs->load("sendings");
-$langs->load("deliveries");
-$langs->load('other');
-
-if (! $user->admin)
-    accessforbidden();
-
-$action=GETPOST('action','alpha');
-$carrier=GETPOST('carrier','int');
-
-$object = new Expedition($db);
-
-
-/*
- * Actions
- */
-//if ($action==setvalue AND $carrier)
-if ($action=='setvalue')
-{
-    // need to add check on values
-    $object->update['code']=GETPOST('code','alpha');
-    $object->update['libelle']=GETPOST('libelle','alpha');
-    $object->update['description']=GETPOST('description','alpha');
-    $object->update['tracking']=GETPOST('tracking','alpha');
-    $object->update_delivery_method($carrier);
-    header("Location: carrier.php");
-    exit;
-}
-
-if ($action=='activate_carrier' && $carrier!='')
-{
-    $object->activ_delivery_method($carrier);
-}
-
-if ($action=='disable_carrier' && $carrier!='')
-{
-    $object->disable_delivery_method($carrier);
-}
-
-/*
- * View
- */
-
-$form=new Form($db);
-
-llxHeader("","");
-
-$linkback='<a href="'.DOL_URL_ROOT.'/admin/modules.php">'.$langs->trans("BackToModuleList").'</a>';
-print_fiche_titre($langs->trans("SendingsSetup"),$linkback,'setup');
-print '<br>';
-
-
-//if ($mesg) print $mesg.'<br>';
-
-
-$h = 0;
-
-$head[$h][0] = DOL_URL_ROOT."/admin/confexped.php";
-$head[$h][1] = $langs->trans("Setup");
-$h++;
-
-$head[$h][0] = DOL_URL_ROOT."/admin/carrier.php";
-$head[$h][1] = $langs->trans("Carriers");
-$hselected=$h;
-$h++;
-
-if (! empty($conf->global->MAIN_SUBMODULE_EXPEDITION))
-{
-    $head[$h][0] = DOL_URL_ROOT."/admin/expedition.php";
-    $head[$h][1] = $langs->trans("Sending");
-    $h++;
-}
-
-if (! empty($conf->global->MAIN_SUBMODULE_LIVRAISON))
-{
-    $head[$h][0] = DOL_URL_ROOT."/admin/livraison.php";
-    $head[$h][1] = $langs->trans("Receivings");
-    $h++;
-}
-
-dol_fiche_head($head, $hselected, $langs->trans("ModuleSetup"));
-
-/*
- * Carrier List
- */
-if ($action=='edit_carrier' || $action=='setvalue')
-{
-    // Carrier Edit
-    if ($carrier!='') $object->list_delivery_methods($carrier);
-    print_titre($langs->trans("CarrierEdit"));
-
-    print '<form method="post" action="'.$_SERVER["PHP_SELF"].'?carrier='.$carrier.'">';
-    print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
-    print '<input type="hidden" name="action" value="setvalue">';
-
-
-    print '<table class="nobordernopadding" width="100%">';
-
-    $var=true;
-    print '<tr class="liste_titre">';
-    print '<td width="150">'.$langs->trans("CarrierParameter").'</td>';
-    print '<td>'.$langs->trans("Value").'</td>';
-    print "</tr>\n";
-
-    $var=!$var;
-    print '<tr '.$bc[$var].'><td class="fieldrequired">';
-    print $langs->trans("Code").'</td><td>';
-    print '<input size="32" type="text" name="code" value="'.$object->listmeths[0]['code'].'">';
-    print ' &nbsp; '.$langs->trans("Example").': CODE';
-    print '</td></tr>';
-
-    $var=!$var;
-    print '<tr '.$bc[$var].'><td class="fieldrequired">';
-    print $langs->trans("Name").'</td><td>';
-    print '<input size="32" type="text" name="libelle" value="'.$object->listmeths[0]['libelle'].'">';
-    print '</td></tr>';
-
-    $var=!$var;
-    print '<tr '.$bc[$var].'><td class="fieldrequired">';
-    print $langs->trans("Description").'</td><td>';
-    print '<input size="64" type="text" name="description" value="'.$object->listmeths[0]['description'].'">';
-    print '</td></tr>';
-
-    $var=!$var;
-    print '<tr '.$bc[$var].'><td class="fieldrequired">';
-    print $langs->trans("Tracking").'</td><td>';
-    print '<input size="80" type="text" name="tracking" value="'.$object->listmeths[0]['tracking'].'">';
-    print ' &nbsp; '.$langs->trans("Example").': http://www.website.com/dir/{TRACKID}';
-    print '</td></tr>';
-
-    if ($carrier)
-    {
-    print '<tr><td colspan="2" align="center"><br><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td></tr>';
-    }
-    else
-    {
-    print '<tr><td colspan="2" align="center"><br><input type="submit" class="button" value="'.$langs->trans("Add").'"></td></tr>';
-    }
-
-    print '</table>';
-    print '</form>';
-
-}
-else
-{
-    // Display List
-    $object->list_delivery_methods();
-    $var=true;
-    print_titre($langs->trans("CarrierList"));
-
-    print '<table class="noborder" width="100%">';
-    print '<tr class="liste_titre">';
-    print '<td width="80">'.$langs->trans("Code").'</td>';
-    print '<td width="150">'.$langs->trans("Name").'</td>';
-    print '<td>'.$langs->trans("Description").'</td>';
-    print '<td>'.$langs->trans("TrackingUrl").'</td>';
-    print '<td align="center" width="60">'.$langs->trans("Status").'</td>';
-    print '<td align="center" width="30">'.$langs->trans("Edit").'</td>';
-    print "</tr>\n";
-    $numlistmeths=count($object->listmeths);
-    for ($i=0; $i<$numlistmeths; $i++)
-    {
-        $var=!$var;
-        print "<tr ".$bc[$var].">";
-        print '<td>'.$object->listmeths[$i]['code'].'</td>';
-        print '<td>'.$object->listmeths[$i]['libelle'].'</td>';
-        print '<td>'.$object->listmeths[$i]['description'].'</td>';
-        print '<td>'.dol_trunc($object->listmeths[$i]['tracking'],92,'middle').'</td>';
-        print '<td align="center">';
-        if($object->listmeths[$i]['active'] == 0)
-        {
-            print '<a href="carrier.php?action=activate_carrier&amp;carrier='.$object->listmeths[$i]['rowid'].'">'.img_picto($langs->trans("Disabled"),'switch_off').'</a>';
-        }
-        else
-        {
-            print '<a href="carrier.php?action=disable_carrier&amp;carrier='.$object->listmeths[$i]['rowid'].'">'.img_picto($langs->trans("Enabled"),'switch_on').'</a>';
-        }
-        print '</td><td align="center">';
-        print '<a href="carrier.php?action=edit_carrier&amp;carrier='.$object->listmeths[$i]['rowid'].'">'.img_picto($langs->trans("Edit"),'edit').'</a>';
-        print '</td>';
-        print "</tr>\n";
-    }
-            print '<tr><td align="center"><a href="carrier.php?action=edit_carrier"><br>'.$langs->trans("Add").'</a></td><tr>';
-
-    print '</table><br>';
-
-    print '</div>';
-}
-
-llxFooter();
-
-$db->close();
-?>
diff --git a/htdocs/admin/compta.php b/htdocs/admin/compta.php
index a5213413d546a925a226bfe435670eae17bbc5e1..c30af26f1c009d09325375ea541537e874852bc7 100644
--- a/htdocs/admin/compta.php
+++ b/htdocs/admin/compta.php
@@ -107,7 +107,7 @@ print '<br>';
 $h = 0;
 
 $head[$h][0] = DOL_URL_ROOT."/admin/compta.php";
-$head[$h][1] = $langs->trans("Compta");
+$head[$h][1] = $langs->trans("Accountancy");
 $head[$h][2] = 'Compta';
 $hselected=$h;
 $h++;
diff --git a/htdocs/admin/confexped.php b/htdocs/admin/confexped.php
index 6653badfb36443924471fe1336435488ec187dda..d9be768461ffa088a69e55ddf0ab9205253a99ab 100644
--- a/htdocs/admin/confexped.php
+++ b/htdocs/admin/confexped.php
@@ -84,10 +84,6 @@ $head[$h][1] = $langs->trans("Setup");
 $hselected=$h;
 $h++;
 
-$head[$h][0] = DOL_URL_ROOT."/admin/carrier.php";
-$head[$h][1] = $langs->trans("Carriers");
-$h++;
-
 if (! empty($conf->global->MAIN_SUBMODULE_EXPEDITION))
 {
 	$head[$h][0] = DOL_URL_ROOT."/admin/expedition.php";
diff --git a/htdocs/admin/dict.php b/htdocs/admin/dict.php
index cf93f472019bfd8c8d89fd43a53469b2539f5873..6405e8ac8a8b075aed93b0538a660909912a99cc 100644
--- a/htdocs/admin/dict.php
+++ b/htdocs/admin/dict.php
@@ -6,9 +6,9 @@
  * Copyright (C) 2010-2011 Juanjo Menent        <jmenent@2byte.es>
  * Copyright (C) 2011      Philippe Grand       <philippe.grand@atoo-net.com>
  * Copyright (C) 2011      Remy Younes          <ryounes@gmail.com>
- * Copyright (C) 2012      Marcos García        <marcosgdf@gmail.com>
+ * Copyright (C) 2012-2013 Marcos García        <marcosgdf@gmail.com>
  * Copyright (C) 2012      Christophe Battarel	<christophe.battarel@ltairis.fr>
- * Copyright (C) 2011-2012 Alexandre Spangaro	  <alexandre.spangaro@gmail.com>
+ * Copyright (C) 2011-2012 Alexandre Spangaro	<alexandre.spangaro@gmail.com>
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -147,7 +147,7 @@ $tabsql[14]= "SELECT e.rowid as rowid, e.code as code, e.libelle, e.price, e.org
 $tabsql[15]= "SELECT rowid   as rowid, code, label as libelle, width, height, unit, active FROM ".MAIN_DB_PREFIX."c_paper_format";
 $tabsql[16]= "SELECT code, label as libelle, active FROM ".MAIN_DB_PREFIX."c_prospectlevel";
 $tabsql[17]= "SELECT id      as rowid, code, libelle, active FROM ".MAIN_DB_PREFIX."c_type_fees";
-$tabsql[18]= "SELECT rowid   as rowid, code, libelle, active FROM ".MAIN_DB_PREFIX."c_shipment_mode";
+$tabsql[18]= "SELECT rowid   as rowid, code, libelle, tracking, active FROM ".MAIN_DB_PREFIX."c_shipment_mode";
 $tabsql[19]= "SELECT id      as rowid, code, libelle, active FROM ".MAIN_DB_PREFIX."c_effectif";
 $tabsql[20]= "SELECT rowid   as rowid, code, libelle, active FROM ".MAIN_DB_PREFIX."c_input_method";
 $tabsql[21]= "SELECT c.rowid as rowid, code, label, active FROM ".MAIN_DB_PREFIX."c_availability AS c";
@@ -203,7 +203,7 @@ $tabfield[14]= "code,libelle,price,organization,country_id,country";
 $tabfield[15]= "code,libelle,width,height,unit";
 $tabfield[16]= "code,libelle";
 $tabfield[17]= "code,libelle";
-$tabfield[18]= "code,libelle";
+$tabfield[18]= "code,libelle,tracking";
 $tabfield[19]= "code,libelle";
 $tabfield[20]= "code,libelle";
 $tabfield[21]= "code,label";
@@ -231,7 +231,7 @@ $tabfieldvalue[14]= "code,libelle,price,organization,country";
 $tabfieldvalue[15]= "code,libelle,width,height,unit";
 $tabfieldvalue[16]= "code,libelle";
 $tabfieldvalue[17]= "code,libelle";
-$tabfieldvalue[18]= "code,libelle";
+$tabfieldvalue[18]= "code,libelle,tracking";
 $tabfieldvalue[19]= "code,libelle";
 $tabfieldvalue[20]= "code,libelle";
 $tabfieldvalue[21]= "code,label";
@@ -259,7 +259,7 @@ $tabfieldinsert[14]= "code,libelle,price,organization,fk_pays";
 $tabfieldinsert[15]= "code,label,width,height,unit";
 $tabfieldinsert[16]= "code,label";
 $tabfieldinsert[17]= "code,libelle";
-$tabfieldinsert[18]= "code,libelle";
+$tabfieldinsert[18]= "code,libelle,tracking";
 $tabfieldinsert[19]= "code,libelle";
 $tabfieldinsert[20]= "code,libelle";
 $tabfieldinsert[21]= "code,label";
@@ -1084,15 +1084,23 @@ if ($id)
                     }
 
                     // Est-ce une entree du dictionnaire qui peut etre desactivee ?
-                    $iserasable=1;  // Oui par defaut
-                    if (isset($obj->code) && ($obj->code == '0' || $obj->code == '' || preg_match('/unknown/i',$obj->code))) $iserasable=0;
-                    if (isset($obj->code) && $obj->code == 'RECEP') $iserasable=0;
-                    if (isset($obj->code) && $obj->code == 'EF0') $iserasable=0;
+                    // True by default
+                    $iserasable=1;
+
+                    if (isset($obj->code))
+                    {
+                    	if (($obj->code == '0' || $obj->code == '' || preg_match('/unknown/i',$obj->code))) $iserasable = 0;
+                    	else if ($obj->code == 'RECEP') $iserasable = 0;
+                    	else if ($obj->code == 'EF0') $iserasable = 0;
+                    } 
+
                     if (isset($obj->type) && in_array($obj->type, array('system', 'systemauto'))) $iserasable=0;
 
+                    $url = $_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(! empty($obj->rowid)?$obj->rowid:(! empty($obj->code)?$obj->code:'')).'&amp;code='.(! empty($obj->code)?$obj->code:'').'&amp;id='.$id.'&amp;';
+
                     // Active
                     print '<td align="center" nowrap="nowrap">';
-                    if ($iserasable) print '<a href="'.$_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(! empty($obj->rowid)?$obj->rowid:(! empty($obj->code)?$obj->code:'')).'&amp;code='.(! empty($obj->code)?$obj->code:'').'&amp;id='.$id.'&amp;action='.$acts[$obj->active].'">'.$actl[$obj->active].'</a>';
+                    if ($iserasable) print '<a href="'.$url.'action='.$acts[$obj->active].'">'.$actl[$obj->active].'</a>';
                     else
                  	{
                   		if (isset($obj->type) && in_array($obj->type, array('system', 'systemauto')) && empty($obj->active)) print $langs->trans("Deprecated");
@@ -1101,11 +1109,11 @@ if ($id)
                     print "</td>";
 
                     // Modify link
-                    if ($iserasable) print '<td align="center"><a href="'.$_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(! empty($obj->rowid)?$obj->rowid:(! empty($obj->code)?$obj->code:'')).'&amp;code='.(! empty($obj->code)?$obj->code:'').'&amp;id='.$id.'&amp;action=edit#'.(! empty($obj->rowid)?$obj->rowid:(! empty($obj->code)?$obj->code:'')).'">'.img_edit().'</a></td>';
+                    if ($iserasable) print '<td align="center"><a href="'.$url.'action=edit#'.(! empty($obj->rowid)?$obj->rowid:(! empty($obj->code)?$obj->code:'')).'">'.img_edit().'</a></td>';
                     else print '<td>&nbsp;</td>';
 
                     // Delete link
-                    if ($iserasable) print '<td align="center"><a href="'.$_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(! empty($obj->rowid)?$obj->rowid:(! empty($obj->code)?$obj->code:'')).'&amp;code='.(! empty($obj->code)?$obj->code:'').'&amp;id='.$id.'&amp;action=delete">'.img_delete().'</a></td>';
+                    if ($iserasable) print '<td align="center"><a href="'.$url.'action=delete">'.img_delete().'</a></td>';
                     else print '<td>&nbsp;</td>';
 
                     print "</tr>\n";
@@ -1153,7 +1161,7 @@ else
 
             $var=!$var;
             $value=$tabname[$i];
-            print '<tr '.$bc[$var].'><td width="30%">';
+            print '<tr '.$bc[$var].'><td width="50%">';
             if (! empty($tabcond[$i]))
             {
                 print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$i.'">'.$langs->trans($tablib[$i]).'</a>';
@@ -1299,6 +1307,7 @@ function fieldList($fieldlist,$obj='',$tabname='')
 			print '<td>';
 			$size='';
 			if ($fieldlist[$field]=='libelle') $size='size="32" ';
+			if ($fieldlist[$field]=='tracking') $size='size="92" ';
 			if ($fieldlist[$field]=='accountancy_code') $size='size="15" ';
 			if ($fieldlist[$field]=='accountancy_code_sell') $size='size="15" ';
 			if ($fieldlist[$field]=='accountancy_code_buy') $size='size="15" ';
diff --git a/htdocs/admin/expedition.php b/htdocs/admin/expedition.php
index 34535b1d321e792ae5ec10c1548a847c105b9808..28e5b912de2090462108ba0ae4f0f98c5ff451ca 100644
--- a/htdocs/admin/expedition.php
+++ b/htdocs/admin/expedition.php
@@ -201,10 +201,6 @@ $head[$h][0] = DOL_URL_ROOT."/admin/confexped.php";
 $head[$h][1] = $langs->trans("Setup");
 $h++;
 
-$head[$h][0] = DOL_URL_ROOT."/admin/carrier.php";
-$head[$h][1] = $langs->trans("Carriers");
-$h++;
-
 $head[$h][0] = DOL_URL_ROOT."/admin/expedition.php";
 $head[$h][1] = $langs->trans("Sending");
 $hselected=$h;
diff --git a/htdocs/admin/livraison.php b/htdocs/admin/livraison.php
index 49cbeee902633144c365b5da7c44def23446b527..677e2b3773b76bfada437be4514439d887b0e00e 100644
--- a/htdocs/admin/livraison.php
+++ b/htdocs/admin/livraison.php
@@ -189,10 +189,6 @@ $head[$h][0] = DOL_URL_ROOT."/admin/confexped.php";
 $head[$h][1] = $langs->trans("Setup");
 $h++;
 
-$head[$h][0] = DOL_URL_ROOT."/admin/carrier.php";
-$head[$h][1] = $langs->trans("Carriers");
-$h++;
-
 if (! empty($conf->global->MAIN_SUBMODULE_EXPEDITION))
 {
     $head[$h][0] = DOL_URL_ROOT."/admin/expedition.php";
diff --git a/htdocs/admin/modules.php b/htdocs/admin/modules.php
index 4440d632b2e6440fa740e983695d8f91c0b64ed0..acdf756eb86de00428cb1c34fb623ffc5b76f732 100644
--- a/htdocs/admin/modules.php
+++ b/htdocs/admin/modules.php
@@ -194,7 +194,7 @@ asort($orders);
 
 $nbofactivatedmodules=count($conf->modules);
 $moreinfo=$langs->trans("TotalNumberOfActivatedModules",($nbofactivatedmodules-1));
-
+if ($nbofactivatedmodules <= 1) $moreinfo .= ' '.img_warning($langs->trans("YouMustEnableOneModule"));
 print load_fiche_titre($langs->trans("ModulesSetup"),$moreinfo,'setup');
 
 // Start to show page
@@ -206,7 +206,7 @@ if ($mode==='functional')  print $langs->trans("ModulesJobDesc")."<br>\n";
 if ($mode==='marketplace') print $langs->trans("ModulesMarketPlaceDesc")."<br>\n";
 if ($mode==='expdev')      print $langs->trans("ModuleFamilyExperimental")."<br>\n";
 
-if ($nbofactivatedmodules <= 1) print ' '.img_warning($langs->trans("YouMustEnableOneModule"));
+
 //print '<br>'."\n";
 
 
diff --git a/htdocs/compta/facture.php b/htdocs/compta/facture.php
index 590901a937ab990ddf19c0d69f265aa652b288d1..2a02522bbcc56d27a9428ff9280ea740a9530075 100644
--- a/htdocs/compta/facture.php
+++ b/htdocs/compta/facture.php
@@ -794,6 +794,8 @@ else if ($action == 'add' && $user->rights->facture->creer)
 		}
 	}
 
+
+
 	// Standard or deposit or proforma invoice
 	if (($_POST['type'] == 0 || $_POST['type'] == 3 || $_POST['type'] == 4) && $_POST['fac_rec'] <= 0)
 	{
@@ -872,126 +874,197 @@ else if ($action == 'add' && $user->rights->facture->creer)
 
 				if ($id > 0)
 				{
-					dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
-
-					$classname = ucfirst($subelement);
-					$srcobject = new $classname($db);
-
-					dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines");
-					$result=$srcobject->fetch($object->origin_id);
-					if ($result > 0)
-					{
-						$lines = $srcobject->lines;
-						if (empty($lines) && method_exists($srcobject,'fetch_lines'))  $lines = $srcobject->fetch_lines();
-
-						$fk_parent_line=0;
-						$num=count($lines);
-
-						for ($i=0;$i<$num;$i++)
-						{
-							$label=(! empty($lines[$i]->label)?$lines[$i]->label:'');
-							$desc=(! empty($lines[$i]->desc)?$lines[$i]->desc:$lines[$i]->libelle);
-
-							if ($lines[$i]->subprice < 0)
+					//If deposit invoice
+					if ($_POST['type'] == 3) {
+						$typeamount=GETPOST('typedeposit','alpha');
+						$valuedeposit=GETPOST('valuedeposit','int');
+						
+						if ($typeamount=='amount') {
+							$amountdeposit=$valuedeposit;
+						}else {
+							$amountdeposit=0;
+							
+							dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
+							
+							$classname = ucfirst($subelement);
+							$srcobject = new $classname($db);
+							
+							dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add deposit line");
+							$result=$srcobject->fetch($object->origin_id);
+							if ($result > 0)
 							{
-								// Negative line, we create a discount line
-								$discount = new DiscountAbsolute($db);
-								$discount->fk_soc=$object->socid;
-								$discount->amount_ht=abs($lines[$i]->total_ht);
-								$discount->amount_tva=abs($lines[$i]->total_tva);
-								$discount->amount_ttc=abs($lines[$i]->total_ttc);
-								$discount->tva_tx=$lines[$i]->tva_tx;
-								$discount->fk_user=$user->id;
-								$discount->description=$desc;
-								$discountid=$discount->create($user);
-								if ($discountid > 0)
+								$totalamount=0;
+								$lines = $srcobject->lines;
+								$num=count($lines);
+								for ($i=0;$i<$num;$i++)
 								{
-									$result=$object->insert_discount($discountid);    // This include link_to_invoice
+									$totalamount=+$lines[$i]->subprice;
 								}
-								else
-								{
-									$mesgs[]=$discount->error;
-									$error++;
-									break;
+								
+								if ($totalamount!=0) {
+									$amountdeposit=($totalamount*$valuedeposit)/100;
 								}
 							}
 							else
 							{
-								// Positive line
-								$product_type=($lines[$i]->product_type?$lines[$i]->product_type:0);
-
-								// Date start
-								$date_start=false;
-								if ($lines[$i]->date_debut_prevue) $date_start=$lines[$i]->date_debut_prevue;
-								if ($lines[$i]->date_debut_reel) $date_start=$lines[$i]->date_debut_reel;
-								if ($lines[$i]->date_start) $date_start=$lines[$i]->date_start;
-
-								//Date end
-								$date_end=false;
-								if ($lines[$i]->date_fin_prevue) $date_end=$lines[$i]->date_fin_prevue;
-								if ($lines[$i]->date_fin_reel) $date_end=$lines[$i]->date_fin_reel;
-								if ($lines[$i]->date_end) $date_end=$lines[$i]->date_end;
-
-								// Reset fk_parent_line for no child products and special product
-								if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) {
-									$fk_parent_line = 0;
-								}
+								$mesgs[]=$srcobject->error;
+								$error++;
+							}
+							
+						}
+						
+						$result = $object->addline(
+							$id,
+							$langs->trans('Deposit'),
+							$amountdeposit, //subprice
+							1, //quantity
+							$lines[$i]->tva_tx,
+							0, //localtax1_tx
+							0, //localtax2_tx
+							0, //fk_product
+							0, //remise_percent
+							0, //date_start
+							0, //date_end
+							0,
+							$lines[$i]->info_bits, //info_bits
+							0, //info_bits
+							'HT',
+							0,
+							0, //product_type
+							1,
+							$lines[$i]->special_code,
+							$object->origin,
+							0,
+							0,
+							0,
+							0,
+							$langs->trans('Deposit')
+						);
+						
+
+					}else {
+
+						dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
+
+						$classname = ucfirst($subelement);
+						$srcobject = new $classname($db);
+
+						dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines");
+						$result=$srcobject->fetch($object->origin_id);
+						if ($result > 0)
+						{
+							$lines = $srcobject->lines;
+							if (empty($lines) && method_exists($srcobject,'fetch_lines'))  $lines = $srcobject->fetch_lines();
+
+							$fk_parent_line=0;
+							$num=count($lines);
 
-								$result = $object->addline(
-									$id,
-									$desc,
-									$lines[$i]->subprice,
-									$lines[$i]->qty,
-									$lines[$i]->tva_tx,
-									$lines[$i]->localtax1_tx,
-									$lines[$i]->localtax2_tx,
-									$lines[$i]->fk_product,
-									$lines[$i]->remise_percent,
-									$date_start,
-									$date_end,
-									0,
-									$lines[$i]->info_bits,
-									$lines[$i]->fk_remise_except,
-									'HT',
-									0,
-									$product_type,
-									$lines[$i]->rang,
-									$lines[$i]->special_code,
-									$object->origin,
-									$lines[$i]->rowid,
-									$fk_parent_line,
-									$lines[$i]->fk_fournprice,
-									$lines[$i]->pa_ht,
-									$label
-								);
-
-								if ($result > 0)
+							for ($i=0;$i<$num;$i++)
+							{
+								$label=(! empty($lines[$i]->label)?$lines[$i]->label:'');
+								$desc=(! empty($lines[$i]->desc)?$lines[$i]->desc:$lines[$i]->libelle);
+
+								if ($lines[$i]->subprice < 0)
 								{
-									$lineid=$result;
+									// Negative line, we create a discount line
+									$discount = new DiscountAbsolute($db);
+									$discount->fk_soc=$object->socid;
+									$discount->amount_ht=abs($lines[$i]->total_ht);
+									$discount->amount_tva=abs($lines[$i]->total_tva);
+									$discount->amount_ttc=abs($lines[$i]->total_ttc);
+									$discount->tva_tx=$lines[$i]->tva_tx;
+									$discount->fk_user=$user->id;
+									$discount->description=$desc;
+									$discountid=$discount->create($user);
+									if ($discountid > 0)
+									{
+										$result=$object->insert_discount($discountid);    // This include link_to_invoice
+									}
+									else
+									{
+										$mesgs[]=$discount->error;
+										$error++;
+										break;
+									}
 								}
 								else
 								{
-									$lineid=0;
-									$error++;
-									break;
-								}
+									// Positive line
+									$product_type=($lines[$i]->product_type?$lines[$i]->product_type:0);
+
+									// Date start
+									$date_start=false;
+									if ($lines[$i]->date_debut_prevue) $date_start=$lines[$i]->date_debut_prevue;
+									if ($lines[$i]->date_debut_reel) $date_start=$lines[$i]->date_debut_reel;
+									if ($lines[$i]->date_start) $date_start=$lines[$i]->date_start;
+
+									//Date end
+									$date_end=false;
+									if ($lines[$i]->date_fin_prevue) $date_end=$lines[$i]->date_fin_prevue;
+									if ($lines[$i]->date_fin_reel) $date_end=$lines[$i]->date_fin_reel;
+									if ($lines[$i]->date_end) $date_end=$lines[$i]->date_end;
+
+									// Reset fk_parent_line for no child products and special product
+									if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) {
+										$fk_parent_line = 0;
+									}
+
+									$result = $object->addline(
+										$id,
+										$desc,
+										$lines[$i]->subprice,
+										$lines[$i]->qty,
+										$lines[$i]->tva_tx,
+										$lines[$i]->localtax1_tx,
+										$lines[$i]->localtax2_tx,
+										$lines[$i]->fk_product,
+										$lines[$i]->remise_percent,
+										$date_start,
+										$date_end,
+										0,
+										$lines[$i]->info_bits,
+										$lines[$i]->fk_remise_except,
+										'HT',
+										0,
+										$product_type,
+										$lines[$i]->rang,
+										$lines[$i]->special_code,
+										$object->origin,
+										$lines[$i]->rowid,
+										$fk_parent_line,
+										$lines[$i]->fk_fournprice,
+										$lines[$i]->pa_ht,
+										$label
+									);
+
+									if ($result > 0)
+									{
+										$lineid=$result;
+									}
+									else
+									{
+										$lineid=0;
+										$error++;
+										break;
+									}
 
-								// Defined the new fk_parent_line
-								if ($result > 0 && $lines[$i]->product_type == 9) {
-									$fk_parent_line = $result;
+									// Defined the new fk_parent_line
+									if ($result > 0 && $lines[$i]->product_type == 9) {
+										$fk_parent_line = $result;
+									}
 								}
 							}
-						}
 
-						// Hooks
-						$parameters=array('objFrom'=>$srcobject);
-						$reshook=$hookmanager->executeHooks('createFrom',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
-						if ($reshook < 0) $error++;
-					}
-					else
-					{
-						$mesgs[]=$srcobject->error;
-						$error++;
+							// Hooks
+							$parameters=array('objFrom'=>$srcobject);
+							$reshook=$hookmanager->executeHooks('createFrom',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
+							if ($reshook < 0) $error++;
+						}
+						else
+						{
+							$mesgs[]=$srcobject->error;
+							$error++;
+						}
 					}
 				}
 				else
@@ -1513,7 +1586,7 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO
 		//        $file = $conf->facture->dir_output . '/' . $ref . '/' . $ref . '.pdf';
 
 		//        if (is_readable($file))
-			//        {
+		//        {
 		if ($_POST['sendto'])
 		{
 			// Le destinataire a ete fourni via le champ libre
@@ -1658,2055 +1731,2061 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO
 			$mesgs[]='<div class="error">'.$langs->trans('ErrorCantReadFile',$file).'</div>';
 			dol_syslog('Failed to read file: '.$file);
 		}
-			}
-			else
-			{
-				$langs->load("other");
-				$mesgs[]='<div class="error">'.$langs->trans('ErrorFailedToReadEntity',$langs->trans("Invoice")).'</div>';
-				dol_syslog('Impossible de lire les donnees de la facture. Le fichier facture n\'a peut-etre pas ete genere.');
-			}
+	}
+	else
+	{
+		$langs->load("other");
+		$mesgs[]='<div class="error">'.$langs->trans('ErrorFailedToReadEntity',$langs->trans("Invoice")).'</div>';
+		dol_syslog('Impossible de lire les donnees de la facture. Le fichier facture n\'a peut-etre pas ete genere.');
+	}
 
-			$action = 'presend';
+	$action = 'presend';
+}
+
+/*
+ * Generate document
+*/
+else if ($action == 'builddoc')	// En get ou en post
+{
+	$object->fetch($id);
+	$object->fetch_thirdparty();
+
+	if (GETPOST('model'))   $object->setDocModel($user, GETPOST('model'));
+	if (GETPOST('fk_bank')) $object->fk_bank=GETPOST('fk_bank');
+
+	// Define output language
+	$outputlangs = $langs;
+	$newlang='';
+	if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang=GETPOST('lang_id');
+	if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$object->client->default_lang;
+	if (! empty($newlang))
+	{
+		$outputlangs = new Translate("",$conf);
+		$outputlangs->setDefaultLang($newlang);
+	}
+	$result=facture_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
+	if ($result <= 0)
+	{
+		dol_print_error($db,$result);
+		exit;
+	}
+	else
+	{
+		header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$object->id.(empty($conf->global->MAIN_JUMP_TAG)?'':'#builddoc'));
+		exit;
 	}
+}
 
-	/*
-	 * Generate document
-	*/
-	else if ($action == 'builddoc')	// En get ou en post
+// Remove file in doc form
+else if ($action == 'remove_file')
+{
+	if ($object->fetch($id))
 	{
-		$object->fetch($id);
+		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+
 		$object->fetch_thirdparty();
 
-		if (GETPOST('model'))   $object->setDocModel($user, GETPOST('model'));
-		if (GETPOST('fk_bank')) $object->fk_bank=GETPOST('fk_bank');
+		$langs->load("other");
+		$upload_dir = $conf->facture->dir_output;
+		$file = $upload_dir . '/' . GETPOST('file');
+		$ret=dol_delete_file($file,0,0,0,$object);
+		if ($ret) setEventMessage($langs->trans("FileWasRemoved", GETPOST('urlfile')));
+		else setEventMessage($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile')), 'errors');
+		$action='';
+	}
+}
+
+if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->facture->creer)
+{
+	if ($action == 'addcontact')
+	{
+		$result = $object->fetch($id);
 
-		// Define output language
-		$outputlangs = $langs;
-		$newlang='';
-		if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang=GETPOST('lang_id');
-		if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$object->client->default_lang;
-		if (! empty($newlang))
+		if ($result > 0 && $id > 0)
 		{
-			$outputlangs = new Translate("",$conf);
-			$outputlangs->setDefaultLang($newlang);
+			$contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid'));
+			$result = $object->add_contact($contactid, $_POST["type"], $_POST["source"]);
 		}
-		$result=facture_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
-		if ($result <= 0)
+
+		if ($result >= 0)
 		{
-			dol_print_error($db,$result);
+			header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
 			exit;
 		}
 		else
 		{
-			header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$object->id.(empty($conf->global->MAIN_JUMP_TAG)?'':'#builddoc'));
-			exit;
+			if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS')
+			{
+				$langs->load("errors");
+				$mesgs[] = '<div class="error">'.$langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType").'</div>';
+			}
+			else
+			{
+				$mesgs[] = '<div class="error">'.$object->error.'</div>';
+			}
 		}
 	}
 
-	// Remove file in doc form
-	else if ($action == 'remove_file')
+	// bascule du statut d'un contact
+	else if ($action == 'swapstatut')
 	{
 		if ($object->fetch($id))
 		{
-			require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
-
-			$object->fetch_thirdparty();
-
-			$langs->load("other");
-			$upload_dir = $conf->facture->dir_output;
-			$file = $upload_dir . '/' . GETPOST('file');
-			$ret=dol_delete_file($file,0,0,0,$object);
-			if ($ret) setEventMessage($langs->trans("FileWasRemoved", GETPOST('urlfile')));
-			else setEventMessage($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile')), 'errors');
-			$action='';
+			$result=$object->swapContactStatus(GETPOST('ligne'));
+		}
+		else
+		{
+			dol_print_error($db);
 		}
 	}
 
-	if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->facture->creer)
+	// Efface un contact
+	else if ($action == 'deletecontact')
 	{
-		if ($action == 'addcontact')
-		{
-			$result = $object->fetch($id);
-
-			if ($result > 0 && $id > 0)
-			{
-				$contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid'));
-				$result = $object->add_contact($contactid, $_POST["type"], $_POST["source"]);
-			}
-
-			if ($result >= 0)
-			{
-				header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
-				exit;
-			}
-			else
-			{
-				if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS')
-				{
-					$langs->load("errors");
-					$mesgs[] = '<div class="error">'.$langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType").'</div>';
-				}
-				else
-				{
-					$mesgs[] = '<div class="error">'.$object->error.'</div>';
-				}
-			}
-		}
+		$object->fetch($id);
+		$result = $object->delete_contact($lineid);
 
-		// bascule du statut d'un contact
-		else if ($action == 'swapstatut')
+		if ($result >= 0)
 		{
-			if ($object->fetch($id))
-			{
-				$result=$object->swapContactStatus(GETPOST('ligne'));
-			}
-			else
-			{
-				dol_print_error($db);
-			}
+			header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
+			exit;
 		}
-
-		// Efface un contact
-		else if ($action == 'deletecontact')
-		{
-			$object->fetch($id);
-			$result = $object->delete_contact($lineid);
-
-			if ($result >= 0)
-			{
-				header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
-				exit;
-			}
-			else {
-				dol_print_error($db);
-			}
+		else {
+			dol_print_error($db);
 		}
 	}
+}
 
-	if ($action == 'update_extras')
+if ($action == 'update_extras')
+{
+	// Fill array 'array_options' with data from add form
+	$extralabels=$extrafields->fetch_name_optionals_label('facture');
+	$ret = $extrafields->setOptionalsFromPost($extralabels,$object);
+
+	// Actions on extra fields (by external module or standard code)
+	// FIXME le hook fait double emploi avec le trigger !!
+	$hookmanager->initHooks(array('invoicedao'));
+	$parameters=array('id'=>$object->id);
+	$reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks
+	if (empty($reshook))
 	{
-		// Fill array 'array_options' with data from add form
-		$extralabels=$extrafields->fetch_name_optionals_label('facture');
-		$ret = $extrafields->setOptionalsFromPost($extralabels,$object);
-
-		// Actions on extra fields (by external module or standard code)
-		// FIXME le hook fait double emploi avec le trigger !!
-		$hookmanager->initHooks(array('invoicedao'));
-		$parameters=array('id'=>$object->id);
-		$reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks
-		if (empty($reshook))
+		if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
 		{
-			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
+			$result=$object->insertExtraFields();
+			if ($result < 0)
 			{
-				$result=$object->insertExtraFields();
-				if ($result < 0)
-				{
-					$error++;
-				}
+				$error++;
 			}
 		}
-		else if ($reshook < 0) $error++;
-
 	}
+	else if ($reshook < 0) $error++;
 
+}
 
-	/*
-	 * View
-	*/
 
-	$form = new Form($db);
-	$formother=new FormOther($db);
-	$formfile = new FormFile($db);
-	$bankaccountstatic=new Account($db);
-	$now=dol_now();
+/*
+ * View
+*/
 
-	llxHeader('',$langs->trans('Bill'),'EN:Customers_Invoices|FR:Factures_Clients|ES:Facturas_a_clientes');
+$form = new Form($db);
+$formother=new FormOther($db);
+$formfile = new FormFile($db);
+$bankaccountstatic=new Account($db);
+$now=dol_now();
 
+llxHeader('',$langs->trans('Bill'),'EN:Customers_Invoices|FR:Factures_Clients|ES:Facturas_a_clientes');
 
 
-	/*********************************************************************
-	 *
-	* Mode creation
-	*
-	**********************************************************************/
-	if ($action == 'create')
-	{
-		$facturestatic=new Facture($db);
-		$extralabels=$extrafields->fetch_name_optionals_label('facture');
 
-		print_fiche_titre($langs->trans('NewBill'));
+/*********************************************************************
+ *
+* Mode creation
+*
+**********************************************************************/
+if ($action == 'create')
+{
+	$facturestatic=new Facture($db);
+	$extralabels=$extrafields->fetch_name_optionals_label('facture');
 
-		$soc = new Societe($db);
-		if ($socid>0) $res=$soc->fetch($socid);
+	print_fiche_titre($langs->trans('NewBill'));
 
-		if (! empty($origin) && ! empty($originid))
+	$soc = new Societe($db);
+	if ($socid>0) $res=$soc->fetch($socid);
+
+	if (! empty($origin) && ! empty($originid))
+	{
+		// Parse element/subelement (ex: project_task)
+		$element = $subelement = $origin;
+		if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs))
 		{
-			// Parse element/subelement (ex: project_task)
-			$element = $subelement = $origin;
-			if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs))
-			{
-				$element = $regs[1];
-				$subelement = $regs[2];
-			}
+			$element = $regs[1];
+			$subelement = $regs[2];
+		}
 
-			if ($element == 'project')
-			{
-				$projectid=$originid;
+		if ($element == 'project')
+		{
+			$projectid=$originid;
+		}
+		else
+		{
+			// For compatibility
+			if ($element == 'order' || $element == 'commande')    {
+				$element = $subelement = 'commande';
+			}
+			if ($element == 'propal')   {
+				$element = 'comm/propal'; $subelement = 'propal';
+			}
+			if ($element == 'contract') {
+				$element = $subelement = 'contrat';
+			}
+			if ($element == 'shipping') {
+				$element = $subelement = 'expedition';
 			}
-			else
-			{
-				// For compatibility
-				if ($element == 'order' || $element == 'commande')    {
-					$element = $subelement = 'commande';
-				}
-				if ($element == 'propal')   {
-					$element = 'comm/propal'; $subelement = 'propal';
-				}
-				if ($element == 'contract') {
-					$element = $subelement = 'contrat';
-				}
-				if ($element == 'shipping') {
-					$element = $subelement = 'expedition';
-				}
 
-				dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
+			dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
 
-				$classname = ucfirst($subelement);
-				$objectsrc = new $classname($db);
-				$objectsrc->fetch($originid);
-				if (empty($objectsrc->lines) && method_exists($objectsrc,'fetch_lines'))  $objectsrc->fetch_lines();
-				$objectsrc->fetch_thirdparty();
+			$classname = ucfirst($subelement);
+			$objectsrc = new $classname($db);
+			$objectsrc->fetch($originid);
+			if (empty($objectsrc->lines) && method_exists($objectsrc,'fetch_lines'))  $objectsrc->fetch_lines();
+			$objectsrc->fetch_thirdparty();
 
-				$projectid			= (! empty($objectsrc->fk_project)?$objectsrc->fk_project:'');
-				$ref_client			= (! empty($objectsrc->ref_client)?$objectsrc->ref_client:'');
-				$ref_int			= (! empty($objectsrc->ref_int)?$objectsrc->ref_int:'');
+			$projectid			= (! empty($objectsrc->fk_project)?$objectsrc->fk_project:'');
+			$ref_client			= (! empty($objectsrc->ref_client)?$objectsrc->ref_client:'');
+			$ref_int			= (! empty($objectsrc->ref_int)?$objectsrc->ref_int:'');
 
-				$soc = $objectsrc->thirdparty;
-				$cond_reglement_id 	= (! empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(! empty($soc->cond_reglement_id)?$soc->cond_reglement_id:1));
-				$mode_reglement_id 	= (! empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(! empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0));
-				$remise_percent 	= (! empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(! empty($soc->remise_percent)?$soc->remise_percent:0));
-				$remise_absolue 	= (! empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(! empty($soc->remise_absolue)?$soc->remise_absolue:0));
-				$dateinvoice		= empty($conf->global->MAIN_AUTOFILL_DATE)?-1:0;
-			}
-		}
-		else
-		{
-			$cond_reglement_id 	= $soc->cond_reglement_id;
-			$mode_reglement_id 	= $soc->mode_reglement_id;
-			$remise_percent 	= $soc->remise_percent;
-			$remise_absolue 	= 0;
+			$soc = $objectsrc->thirdparty;
+			$cond_reglement_id 	= (! empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(! empty($soc->cond_reglement_id)?$soc->cond_reglement_id:1));
+			$mode_reglement_id 	= (! empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(! empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0));
+			$remise_percent 	= (! empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(! empty($soc->remise_percent)?$soc->remise_percent:0));
+			$remise_absolue 	= (! empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(! empty($soc->remise_absolue)?$soc->remise_absolue:0));
 			$dateinvoice		= empty($conf->global->MAIN_AUTOFILL_DATE)?-1:0;
 		}
-		$absolute_discount=$soc->getAvailableDiscounts();
+	}
+	else
+	{
+		$cond_reglement_id 	= $soc->cond_reglement_id;
+		$mode_reglement_id 	= $soc->mode_reglement_id;
+		$remise_percent 	= $soc->remise_percent;
+		$remise_absolue 	= 0;
+		$dateinvoice		= empty($conf->global->MAIN_AUTOFILL_DATE)?-1:0;
+	}
+	$absolute_discount=$soc->getAvailableDiscounts();
 
 
-		if (! empty($conf->use_javascript_ajax))
-		{
-			print ajax_combobox('fac_replacement');
-			print ajax_combobox('fac_avoir');
-		}
+	if (! empty($conf->use_javascript_ajax))
+	{
+		print ajax_combobox('fac_replacement');
+		print ajax_combobox('fac_avoir');
+	}
 
-		print '<form name="add" action="'.$_SERVER["PHP_SELF"].'" method="POST">';
-		print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
-		print '<input type="hidden" name="action" value="add">';
-		if ($soc->id > 0)
-			print '<input type="hidden" name="socid" value="'.$soc->id.'">' ."\n";
-		print '<input name="facnumber" type="hidden" value="provisoire">';
-		print '<input name="ref_client" type="hidden" value="'.$ref_client.'">';
-		print '<input name="ref_int" type="hidden" value="'.$ref_int.'">';
-		print '<input type="hidden" name="origin" value="'.$origin.'">';
-		print '<input type="hidden" name="originid" value="'.$originid.'">';
+	print '<form name="add" action="'.$_SERVER["PHP_SELF"].'" method="POST">';
+	print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
+	print '<input type="hidden" name="action" value="add">';
+	if ($soc->id > 0)
+		print '<input type="hidden" name="socid" value="'.$soc->id.'">' ."\n";
+	print '<input name="facnumber" type="hidden" value="provisoire">';
+	print '<input name="ref_client" type="hidden" value="'.$ref_client.'">';
+	print '<input name="ref_int" type="hidden" value="'.$ref_int.'">';
+	print '<input type="hidden" name="origin" value="'.$origin.'">';
+	print '<input type="hidden" name="originid" value="'.$originid.'">';
 
-		print '<table class="border" width="100%">';
+	print '<table class="border" width="100%">';
 
-		// Ref
-		print '<tr><td class="fieldrequired">'.$langs->trans('Ref').'</td><td colspan="2">'.$langs->trans('Draft').'</td></tr>';
+	// Ref
+	print '<tr><td class="fieldrequired">'.$langs->trans('Ref').'</td><td colspan="2">'.$langs->trans('Draft').'</td></tr>';
+
+	// Factures predefinies
+	if (empty($origin) && empty($originid) && $socid>0)
+	{
+		$sql = 'SELECT r.rowid, r.titre, r.total_ttc';
+		$sql.= ' FROM '.MAIN_DB_PREFIX.'facture_rec as r';
+		$sql.= ' WHERE r.fk_soc = '.$soc->id;
 
-		// Factures predefinies
-		if (empty($origin) && empty($originid) && $socid>0)
+		$resql=$db->query($sql);
+		if ($resql)
 		{
-			$sql = 'SELECT r.rowid, r.titre, r.total_ttc';
-			$sql.= ' FROM '.MAIN_DB_PREFIX.'facture_rec as r';
-			$sql.= ' WHERE r.fk_soc = '.$soc->id;
+			$num = $db->num_rows($resql);
+			$i = 0;
 
-			$resql=$db->query($sql);
-			if ($resql)
+			if ($num > 0)
 			{
-				$num = $db->num_rows($resql);
-				$i = 0;
-
-				if ($num > 0)
+				print '<tr><td>'.$langs->trans('CreateFromRepeatableInvoice').'</td><td>';
+				print '<select class="flat" name="fac_rec">';
+				print '<option value="0" selected="selected"></option>';
+				while ($i < $num)
 				{
-					print '<tr><td>'.$langs->trans('CreateFromRepeatableInvoice').'</td><td>';
-					print '<select class="flat" name="fac_rec">';
-					print '<option value="0" selected="selected"></option>';
-					while ($i < $num)
-					{
-						$objp = $db->fetch_object($resql);
-						print '<option value="'.$objp->rowid.'"';
-						if (GETPOST('fac_rec') == $objp->rowid) print ' selected="selected"';
-						print '>'.$objp->titre.' ('.price($objp->total_ttc).' '.$langs->trans("TTC").')</option>';
-						$i++;
-					}
-					print '</select></td></tr>';
+					$objp = $db->fetch_object($resql);
+					print '<option value="'.$objp->rowid.'"';
+					if (GETPOST('fac_rec') == $objp->rowid) print ' selected="selected"';
+					print '>'.$objp->titre.' ('.price($objp->total_ttc).' '.$langs->trans("TTC").')</option>';
+					$i++;
 				}
-				$db->free($resql);
-			}
-			else
-			{
-				dol_print_error($db);
+				print '</select></td></tr>';
 			}
-		}
-
-		// Tiers
-		print '<tr>';
-		print '<td class="fieldrequired">'.$langs->trans('Customer').'</td>';
-		if($soc->id > 0)
-		{
-			print '<td colspan="2">';
-			print $soc->getNomUrl(1);
-			print '<input type="hidden" name="socid" value="'.$soc->id.'">';
-			print '</td>';
+			$db->free($resql);
 		}
 		else
 		{
-			print '<td colspan="2">';
-			print $form->select_company('','socid','s.client = 1 OR s.client = 3',1);
-			print '</td>';
+			dol_print_error($db);
 		}
-		print '</tr>'."\n";
+	}
 
-		// Type de facture
-		$facids=$facturestatic->list_replacable_invoices($soc->id);
-		if ($facids < 0)
-		{
-			dol_print_error($db,$facturestatic);
-			exit;
-		}
-		$options="";
-		foreach ($facids as $facparam)
-		{
-			$options.='<option value="'.$facparam['id'].'"';
-			if ($facparam['id'] == $_POST['fac_replacement']) $options.=' selected="selected"';
-			$options.='>'.$facparam['ref'];
-			$options.=' ('.$facturestatic->LibStatut(0,$facparam['status']).')';
-			$options.='</option>';
-		}
+	// Tiers
+	print '<tr>';
+	print '<td class="fieldrequired">'.$langs->trans('Customer').'</td>';
+	if($soc->id > 0)
+	{
+		print '<td colspan="2">';
+		print $soc->getNomUrl(1);
+		print '<input type="hidden" name="socid" value="'.$soc->id.'">';
+		print '</td>';
+	}
+	else
+	{
+		print '<td colspan="2">';
+		print $form->select_company('','socid','s.client = 1 OR s.client = 3',1);
+		print '</td>';
+	}
+	print '</tr>'."\n";
 
-		$facids=$facturestatic->list_qualified_avoir_invoices($soc->id);
-		if ($facids < 0)
-		{
-			dol_print_error($db,$facturestatic);
-			exit;
-		}
-		$optionsav="";
-		$newinvoice_static=new Facture($db);
-		foreach ($facids as $key => $valarray)
-		{
-			$newinvoice_static->id=$key;
-			$newinvoice_static->ref=$valarray['ref'];
-			$newinvoice_static->statut=$valarray['status'];
-			$newinvoice_static->type=$valarray['type'];
-			$newinvoice_static->paye=$valarray['paye'];
+	// Type de facture
+	$facids=$facturestatic->list_replacable_invoices($soc->id);
+	if ($facids < 0)
+	{
+		dol_print_error($db,$facturestatic);
+		exit;
+	}
+	$options="";
+	foreach ($facids as $facparam)
+	{
+		$options.='<option value="'.$facparam['id'].'"';
+		if ($facparam['id'] == $_POST['fac_replacement']) $options.=' selected="selected"';
+		$options.='>'.$facparam['ref'];
+		$options.=' ('.$facturestatic->LibStatut(0,$facparam['status']).')';
+		$options.='</option>';
+	}
 
-			$optionsav.='<option value="'.$key.'"';
-			if ($key == $_POST['fac_avoir']) $optionsav.=' selected="selected"';
-			$optionsav.='>';
-			$optionsav.=$newinvoice_static->ref;
-			$optionsav.=' ('.$newinvoice_static->getLibStatut(1,$valarray['paymentornot']).')';
-			$optionsav.='</option>';
-		}
+	$facids=$facturestatic->list_qualified_avoir_invoices($soc->id);
+	if ($facids < 0)
+	{
+		dol_print_error($db,$facturestatic);
+		exit;
+	}
+	$optionsav="";
+	$newinvoice_static=new Facture($db);
+	foreach ($facids as $key => $valarray)
+	{
+		$newinvoice_static->id=$key;
+		$newinvoice_static->ref=$valarray['ref'];
+		$newinvoice_static->statut=$valarray['status'];
+		$newinvoice_static->type=$valarray['type'];
+		$newinvoice_static->paye=$valarray['paye'];
+
+		$optionsav.='<option value="'.$key.'"';
+		if ($key == $_POST['fac_avoir']) $optionsav.=' selected="selected"';
+		$optionsav.='>';
+		$optionsav.=$newinvoice_static->ref;
+		$optionsav.=' ('.$newinvoice_static->getLibStatut(1,$valarray['paymentornot']).')';
+		$optionsav.='</option>';
+	}
+
+	print '<tr><td valign="top" class="fieldrequired">'.$langs->trans('Type').'</td><td colspan="2">';
+	print '<table class="nobordernopadding">'."\n";
 
-		print '<tr><td valign="top" class="fieldrequired">'.$langs->trans('Type').'</td><td colspan="2">';
-		print '<table class="nobordernopadding">'."\n";
+	// Standard invoice
+	print '<tr height="18"><td width="16px" valign="middle">';
+	print '<input type="radio" name="type" value="0"'.(GETPOST('type')==0?' checked="checked"':'').'>';
+	print '</td><td valign="middle">';
+	$desc=$form->textwithpicto($langs->trans("InvoiceStandardAsk"),$langs->transnoentities("InvoiceStandardDesc"),1);
+	print $desc;
+	print '</td></tr>'."\n";
 
-		// Standard invoice
+	// Proforma
+	if (! empty($conf->global->FACTURE_USE_PROFORMAT))
+	{
 		print '<tr height="18"><td width="16px" valign="middle">';
-		print '<input type="radio" name="type" value="0"'.(GETPOST('type')==0?' checked="checked"':'').'>';
+		print '<input type="radio" name="type" value="4"'.(GETPOST('type')==4?' checked="checked"':'').'>';
 		print '</td><td valign="middle">';
-		$desc=$form->textwithpicto($langs->trans("InvoiceStandardAsk"),$langs->transnoentities("InvoiceStandardDesc"),1);
+		$desc=$form->textwithpicto($langs->trans("InvoiceProForma"),$langs->transnoentities("InvoiceProFormaDesc"),1);
 		print $desc;
 		print '</td></tr>'."\n";
+	}
 
-		// Proforma
-		if (! empty($conf->global->FACTURE_USE_PROFORMAT))
-		{
-			print '<tr height="18"><td width="16px" valign="middle">';
-			print '<input type="radio" name="type" value="4"'.(GETPOST('type')==4?' checked="checked"':'').'>';
-			print '</td><td valign="middle">';
-			$desc=$form->textwithpicto($langs->trans("InvoiceProForma"),$langs->transnoentities("InvoiceProFormaDesc"),1);
-			print $desc;
-			print '</td></tr>'."\n";
-		}
+	if ((empty($origin)) || (($origin=='propal') && (!empty($originid))))
+	{
+		// Deposit
+		print '<tr height="18"><td width="16px" valign="middle">';
+		print '<input type="radio" name="type" value="3"'.(GETPOST('type')==3?' checked="checked"':'').'>';
+		print '</td><td valign="middle" nowrap="nowrap">';
+		$desc=$form->textwithpicto($langs->trans("InvoiceDeposit"),$langs->transnoentities("InvoiceDepositDesc"),1);
+		print '<table class="nobordernopadding"><tr><td>'.$desc.'</td>';
+		if (($origin=='propal') ) {
+			print '<td><select name="typedeposit"><option value="amount">'.$langs->trans('FixAmount').'</option>';
+			print '<option value="variable">'.$langs->trans('VarAmount').'</option></select></td>';
+			print '<td>'.$langs->trans('Value').':<input type="text" name="valuedeposit" size="3" value="'.GETPOST('valuedeposit','int').'"/>';
+		}
+		print '</td></tr></table>';
+		print '</td></tr>'."\n";
+	}
 
-		if (empty($origin))
+	if ($socid > 0)
+	{
+		// Replacement
+		print '<tr height="18"><td valign="middle">';
+		print '<input type="radio" name="type" value="1"'.(GETPOST('type')==1?' checked="checked"':'');
+		if (! $options) print ' disabled="disabled"';
+		print '>';
+		print '</td><td valign="middle">';
+		$text=$langs->trans("InvoiceReplacementAsk").' ';
+		$text.='<select class="flat" name="fac_replacement" id="fac_replacement"';
+		if (! $options) $text.=' disabled="disabled"';
+		$text.='>';
+		if ($options)
 		{
-			// Deposit
-			print '<tr height="18"><td width="16px" valign="middle">';
-			print '<input type="radio" name="type" value="3"'.(GETPOST('type')==3?' checked="checked"':'').'>';
-			print '</td><td valign="middle">';
-			$desc=$form->textwithpicto($langs->trans("InvoiceDeposit"),$langs->transnoentities("InvoiceDepositDesc"),1);
-			print $desc;
-			print '</td></tr>'."\n";
+			$text.='<option value="-1"></option>';
+			$text.=$options;
 		}
-
-		if ($socid > 0)
+		else
 		{
-			// Replacement
-			print '<tr height="18"><td valign="middle">';
-			print '<input type="radio" name="type" value="1"'.(GETPOST('type')==1?' checked="checked"':'');
-			if (! $options) print ' disabled="disabled"';
-			print '>';
-			print '</td><td valign="middle">';
-			$text=$langs->trans("InvoiceReplacementAsk").' ';
-			$text.='<select class="flat" name="fac_replacement" id="fac_replacement"';
-			if (! $options) $text.=' disabled="disabled"';
-			$text.='>';
-			if ($options)
-			{
-				$text.='<option value="-1"></option>';
-				$text.=$options;
-			}
-			else
-			{
-				$text.='<option value="-1">'.$langs->trans("NoReplacableInvoice").'</option>';
-			}
-			$text.='</select>';
-			$desc=$form->textwithpicto($text,$langs->transnoentities("InvoiceReplacementDesc"),1);
-			print $desc;
-			print '</td></tr>'."\n";
+			$text.='<option value="-1">'.$langs->trans("NoReplacableInvoice").'</option>';
 		}
+		$text.='</select>';
+		$desc=$form->textwithpicto($text,$langs->transnoentities("InvoiceReplacementDesc"),1);
+		print $desc;
+		print '</td></tr>'."\n";
+	}
 
-		if (empty($origin) && $socid > 0)
+	if (empty($origin) && $socid > 0)
+	{
+		// Credit note
+		print '<tr height="18"><td valign="middle">';
+		print '<input type="radio" name="type" value="2"'.(GETPOST('type')==2?' checked=true':'');
+		if (! $optionsav) print ' disabled="disabled"';
+		print '>';
+		print '</td><td valign="middle">';
+		$text=$langs->transnoentities("InvoiceAvoirAsk").' ';
+		//	$text.='<input type="text" value="">';
+		$text.='<select class="flat" name="fac_avoir" id="fac_avoir"';
+		if (! $optionsav) $text.=' disabled="disabled"';
+		$text.='>';
+		if ($optionsav)
 		{
-			// Credit note
-			print '<tr height="18"><td valign="middle">';
-			print '<input type="radio" name="type" value="2"'.(GETPOST('type')==2?' checked=true':'');
-			if (! $optionsav) print ' disabled="disabled"';
-			print '>';
-			print '</td><td valign="middle">';
-			$text=$langs->transnoentities("InvoiceAvoirAsk").' ';
-			//	$text.='<input type="text" value="">';
-			$text.='<select class="flat" name="fac_avoir" id="fac_avoir"';
-			if (! $optionsav) $text.=' disabled="disabled"';
-			$text.='>';
-			if ($optionsav)
-			{
-				$text.='<option value="-1"></option>';
-				$text.=$optionsav;
-			}
-			else
-			{
-				$text.='<option value="-1">'.$langs->trans("NoInvoiceToCorrect").'</option>';
-			}
-			$text.='</select>';
-			$desc=$form->textwithpicto($text,$langs->transnoentities("InvoiceAvoirDesc"),1);
-			print $desc;
-			print '</td></tr>'."\n";
+			$text.='<option value="-1"></option>';
+			$text.=$optionsav;
 		}
-
-		print '</table>';
-		print '</td></tr>';
-
-		if ($socid > 0)
+		else
 		{
-			// Discounts for third party
-			print '<tr><td>'.$langs->trans('Discounts').'</td><td colspan="2">';
-			if ($soc->remise_client) print $langs->trans("CompanyHasRelativeDiscount",'<a href="'.DOL_URL_ROOT.'/comm/remise.php?id='.$soc->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?socid='.$soc->id.'&action='.$action.'&origin='.GETPOST('origin').'&originid='.GETPOST('originid')).'">'.$soc->remise_client.'</a>');
-			else print $langs->trans("CompanyHasNoRelativeDiscount");
-			print ' <a href="'.DOL_URL_ROOT.'/comm/remise.php?id='.$soc->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?socid='.$soc->id.'&action='.$action.'&origin='.GETPOST('origin').'&originid='.GETPOST('originid')).'">('.$langs->trans("EditRelativeDiscount").')</a>';
-			print '. ';
-			print '<br>';
-			if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount",'<a href="'.DOL_URL_ROOT.'/comm/remx.php?id='.$soc->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?socid='.$soc->id.'&action='.$action.'&origin='.GETPOST('origin').'&originid='.GETPOST('originid')).'">'.price($absolute_discount).'</a>',$langs->trans("Currency".$conf->currency));
-			else print $langs->trans("CompanyHasNoAbsoluteDiscount");
-			print ' <a href="'.DOL_URL_ROOT.'/comm/remx.php?id='.$soc->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?socid='.$soc->id.'&action='.$action.'&origin='.GETPOST('origin').'&originid='.GETPOST('originid')).'">('.$langs->trans("EditGlobalDiscounts").')</a>';
-			print '.';
-			print '</td></tr>';
+			$text.='<option value="-1">'.$langs->trans("NoInvoiceToCorrect").'</option>';
 		}
+		$text.='</select>';
+		$desc=$form->textwithpicto($text,$langs->transnoentities("InvoiceAvoirDesc"),1);
+		print $desc;
+		print '</td></tr>'."\n";
+	}
 
-		// Date invoice
-		print '<tr><td class="fieldrequired">'.$langs->trans('Date').'</td><td colspan="2">';
-		$form->select_date($dateinvoice,'','','','',"add",1,1);
-		print '</td></tr>';
+	print '</table>';
+	print '</td></tr>';
 
-		// Payment term
-		print '<tr><td nowrap>'.$langs->trans('PaymentConditionsShort').'</td><td colspan="2">';
-		$form->select_conditions_paiements(isset($_POST['cond_reglement_id'])?$_POST['cond_reglement_id']:$cond_reglement_id,'cond_reglement_id');
+	if ($socid > 0)
+	{
+		// Discounts for third party
+		print '<tr><td>'.$langs->trans('Discounts').'</td><td colspan="2">';
+		if ($soc->remise_client) print $langs->trans("CompanyHasRelativeDiscount",'<a href="'.DOL_URL_ROOT.'/comm/remise.php?id='.$soc->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?socid='.$soc->id.'&action='.$action.'&origin='.GETPOST('origin').'&originid='.GETPOST('originid')).'">'.$soc->remise_client.'</a>');
+		else print $langs->trans("CompanyHasNoRelativeDiscount");
+		print ' <a href="'.DOL_URL_ROOT.'/comm/remise.php?id='.$soc->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?socid='.$soc->id.'&action='.$action.'&origin='.GETPOST('origin').'&originid='.GETPOST('originid')).'">('.$langs->trans("EditRelativeDiscount").')</a>';
+		print '. ';
+		print '<br>';
+		if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount",'<a href="'.DOL_URL_ROOT.'/comm/remx.php?id='.$soc->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?socid='.$soc->id.'&action='.$action.'&origin='.GETPOST('origin').'&originid='.GETPOST('originid')).'">'.price($absolute_discount).'</a>',$langs->trans("Currency".$conf->currency));
+		else print $langs->trans("CompanyHasNoAbsoluteDiscount");
+		print ' <a href="'.DOL_URL_ROOT.'/comm/remx.php?id='.$soc->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?socid='.$soc->id.'&action='.$action.'&origin='.GETPOST('origin').'&originid='.GETPOST('originid')).'">('.$langs->trans("EditGlobalDiscounts").')</a>';
+		print '.';
 		print '</td></tr>';
+	}
+
+	// Date invoice
+	print '<tr><td class="fieldrequired">'.$langs->trans('Date').'</td><td colspan="2">';
+	$form->select_date($dateinvoice,'','','','',"add",1,1);
+	print '</td></tr>';
 
-		// Payment mode
-		print '<tr><td>'.$langs->trans('PaymentMode').'</td><td colspan="2">';
-		$form->select_types_paiements(isset($_POST['mode_reglement_id'])?$_POST['mode_reglement_id']:$mode_reglement_id,'mode_reglement_id');
+	// Payment term
+	print '<tr><td nowrap>'.$langs->trans('PaymentConditionsShort').'</td><td colspan="2">';
+	$form->select_conditions_paiements(isset($_POST['cond_reglement_id'])?$_POST['cond_reglement_id']:$cond_reglement_id,'cond_reglement_id');
+	print '</td></tr>';
+
+	// Payment mode
+	print '<tr><td>'.$langs->trans('PaymentMode').'</td><td colspan="2">';
+	$form->select_types_paiements(isset($_POST['mode_reglement_id'])?$_POST['mode_reglement_id']:$mode_reglement_id,'mode_reglement_id');
+	print '</td></tr>';
+
+	// Project
+	if (! empty($conf->projet->enabled) && $socid>0)
+	{
+		$langs->load('projects');
+		print '<tr><td>'.$langs->trans('Project').'</td><td colspan="2">';
+		select_projects($soc->id, $projectid, 'projectid');
 		print '</td></tr>';
+	}
 
-		// Project
-		if (! empty($conf->projet->enabled) && $socid>0)
-		{
-			$langs->load('projects');
-			print '<tr><td>'.$langs->trans('Project').'</td><td colspan="2">';
-			select_projects($soc->id, $projectid, 'projectid');
-			print '</td></tr>';
-		}
+	// Other attributes
+	$parameters=array('objectsrc' => $objectsrc, 'colspan' => ' colspan="3"');
+	$reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
+	if (empty($reshook) && ! empty($extrafields->attribute_label))
+	{
+		print $object->showOptionals($extrafields,'edit');
+	}
 
-		// Other attributes
-		$parameters=array('objectsrc' => $objectsrc, 'colspan' => ' colspan="3"');
-		$reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
-		if (empty($reshook) && ! empty($extrafields->attribute_label))
-		{
-			print $object->showOptionals($extrafields,'edit');
-		}
+	// Modele PDF
+	print '<tr><td>'.$langs->trans('Model').'</td>';
+	print '<td>';
+	include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
+	$liste=ModelePDFFactures::liste_modeles($db);
+	print $form->selectarray('model',$liste,$conf->global->FACTURE_ADDON_PDF);
+	print "</td></tr>";
+
+	// Public note
+	print '<tr>';
+	print '<td class="border" valign="top">'.$langs->trans('NotePublic').'</td>';
+	print '<td valign="top" colspan="2">';
+	$note_public='';
+	if (is_object($objectsrc))    // Take value from source object
+	{
+		$note_public=$objectsrc->note_public;
+	}
+	$doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, 70);
+	print $doleditor->Create(1);
 
-		// Modele PDF
-		print '<tr><td>'.$langs->trans('Model').'</td>';
-		print '<td>';
-		include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
-		$liste=ModelePDFFactures::liste_modeles($db);
-		print $form->selectarray('model',$liste,$conf->global->FACTURE_ADDON_PDF);
-		print "</td></tr>";
+	//print '<textarea name="note_public" wrap="soft" cols="70" rows="'.ROWS_3.'">'.$note_public.'</textarea></td></tr>';
 
-		// Public note
+	// Private note
+	if (empty($user->societe_id))
+	{
 		print '<tr>';
-		print '<td class="border" valign="top">'.$langs->trans('NotePublic').'</td>';
+		print '<td class="border" valign="top">'.$langs->trans('NotePrivate').'</td>';
 		print '<td valign="top" colspan="2">';
-		$note_public='';
-		if (is_object($objectsrc))    // Take value from source object
+		$note_private='';
+		if (! empty($origin) && ! empty($originid) && is_object($objectsrc))    // Take value from source object
 		{
-			$note_public=$objectsrc->note_public;
+			$note_private=$objectsrc->note_private;
 		}
-		$doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, 70);
+		$doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, 70);
 		print $doleditor->Create(1);
+		//print '<textarea name="note_private" wrap="soft" cols="70" rows="'.ROWS_3.'">'.$note_private.'.</textarea></td></tr>';
+	}
 
-		//print '<textarea name="note_public" wrap="soft" cols="70" rows="'.ROWS_3.'">'.$note_public.'</textarea></td></tr>';
-
-		// Private note
-		if (empty($user->societe_id))
+	if (! empty($origin) && ! empty($originid) && is_object($objectsrc))
+	{
+		// TODO for compatibility
+		if ($origin == 'contrat')
 		{
-			print '<tr>';
-			print '<td class="border" valign="top">'.$langs->trans('NotePrivate').'</td>';
-			print '<td valign="top" colspan="2">';
-			$note_private='';
-			if (! empty($origin) && ! empty($originid) && is_object($objectsrc))    // Take value from source object
-			{
-				$note_private=$objectsrc->note_private;
-			}
-			$doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, 70);
-			print $doleditor->Create(1);
-			//print '<textarea name="note_private" wrap="soft" cols="70" rows="'.ROWS_3.'">'.$note_private.'.</textarea></td></tr>';
+			// Calcul contrat->price (HT), contrat->total (TTC), contrat->tva
+			$objectsrc->remise_absolue=$remise_absolue;
+			$objectsrc->remise_percent=$remise_percent;
+			$objectsrc->update_price(1,-1,1);
 		}
 
-		if (! empty($origin) && ! empty($originid) && is_object($objectsrc))
-		{
-			// TODO for compatibility
-			if ($origin == 'contrat')
-			{
-				// Calcul contrat->price (HT), contrat->total (TTC), contrat->tva
-				$objectsrc->remise_absolue=$remise_absolue;
-				$objectsrc->remise_percent=$remise_percent;
-				$objectsrc->update_price(1,-1,1);
-			}
+		print "\n<!-- ".$classname." info -->";
+		print "\n";
+		print '<input type="hidden" name="amount"         value="'.$objectsrc->total_ht.'">'."\n";
+		print '<input type="hidden" name="total"          value="'.$objectsrc->total_ttc.'">'."\n";
+		print '<input type="hidden" name="tva"            value="'.$objectsrc->total_tva.'">'."\n";
+		print '<input type="hidden" name="origin"         value="'.$objectsrc->element.'">';
+		print '<input type="hidden" name="originid"       value="'.$objectsrc->id.'">';
 
-			print "\n<!-- ".$classname." info -->";
-			print "\n";
-			print '<input type="hidden" name="amount"         value="'.$objectsrc->total_ht.'">'."\n";
-			print '<input type="hidden" name="total"          value="'.$objectsrc->total_ttc.'">'."\n";
-			print '<input type="hidden" name="tva"            value="'.$objectsrc->total_tva.'">'."\n";
-			print '<input type="hidden" name="origin"         value="'.$objectsrc->element.'">';
-			print '<input type="hidden" name="originid"       value="'.$objectsrc->id.'">';
+		$newclassname=$classname;
+		if ($newclassname == 'Propal') $newclassname = 'CommercialProposal';
+		elseif ($newclassname == 'Commande') $newclassname = 'Order';
 
-			$newclassname=$classname;
-			if ($newclassname == 'Propal') $newclassname = 'CommercialProposal';
-			elseif ($newclassname == 'Commande') $newclassname = 'Order';
+		print '<tr><td>'.$langs->trans($newclassname).'</td><td colspan="2">'.$objectsrc->getNomUrl(1).'</td></tr>';
+		print '<tr><td>'.$langs->trans('TotalHT').'</td><td colspan="2">'.price($objectsrc->total_ht).'</td></tr>';
+		print '<tr><td>'.$langs->trans('TotalVAT').'</td><td colspan="2">'.price($objectsrc->total_tva)."</td></tr>";
+		if ($mysoc->localtax1_assuj=="1") //Localtax1 RE
+		{
+			print '<tr><td>'.$langs->transcountry("AmountLT1",$mysoc->country_code).'</td><td colspan="2">'.price($objectsrc->total_localtax1)."</td></tr>";
+		}
 
-			print '<tr><td>'.$langs->trans($newclassname).'</td><td colspan="2">'.$objectsrc->getNomUrl(1).'</td></tr>';
-			print '<tr><td>'.$langs->trans('TotalHT').'</td><td colspan="2">'.price($objectsrc->total_ht).'</td></tr>';
-			print '<tr><td>'.$langs->trans('TotalVAT').'</td><td colspan="2">'.price($objectsrc->total_tva)."</td></tr>";
-			if ($mysoc->localtax1_assuj=="1") //Localtax1 RE
-			{
-				print '<tr><td>'.$langs->transcountry("AmountLT1",$mysoc->country_code).'</td><td colspan="2">'.price($objectsrc->total_localtax1)."</td></tr>";
-			}
+		if ($mysoc->localtax2_assuj=="1") //Localtax2 IRPF
+		{
+			print '<tr><td>'.$langs->transcountry("AmountLT2",$mysoc->country_code).'</td><td colspan="2">'.price($objectsrc->total_localtax2)."</td></tr>";
+		}
+		print '<tr><td>'.$langs->trans('TotalTTC').'</td><td colspan="2">'.price($objectsrc->total_ttc)."</td></tr>";
+	}
+	else
+	{
+		// Show deprecated optional form to add product line here
+		if (! empty($conf->global->PRODUCT_SHOW_WHEN_CREATE))
+		{
+			print '<tr><td colspan="3">';
 
-			if ($mysoc->localtax2_assuj=="1") //Localtax2 IRPF
+			// Zone de choix des produits predefinis a la creation
+			print '<table class="noborder" width="100%">';
+			print '<tr>';
+			print '<td>'.$langs->trans('ProductsAndServices').'</td>';
+			print '<td>'.$langs->trans('Qty').'</td>';
+			print '<td>'.$langs->trans('ReductionShort').'</td>';
+			print '<td> &nbsp; &nbsp; </td>';
+			if (! empty($conf->service->enabled))
 			{
-				print '<tr><td>'.$langs->transcountry("AmountLT2",$mysoc->country_code).'</td><td colspan="2">'.price($objectsrc->total_localtax2)."</td></tr>";
+				print '<td>'.$langs->trans('ServiceLimitedDuration').'</td>';
 			}
-			print '<tr><td>'.$langs->trans('TotalTTC').'</td><td colspan="2">'.price($objectsrc->total_ttc)."</td></tr>";
-		}
-		else
-		{
-			// Show deprecated optional form to add product line here
-			if (! empty($conf->global->PRODUCT_SHOW_WHEN_CREATE))
+			print '</tr>';
+			for ($i = 1 ; $i <= $NBLINES ; $i++)
 			{
-				print '<tr><td colspan="3">';
-
-				// Zone de choix des produits predefinis a la creation
-				print '<table class="noborder" width="100%">';
 				print '<tr>';
-				print '<td>'.$langs->trans('ProductsAndServices').'</td>';
-				print '<td>'.$langs->trans('Qty').'</td>';
-				print '<td>'.$langs->trans('ReductionShort').'</td>';
-				print '<td> &nbsp; &nbsp; </td>';
+				print '<td>';
+				// multiprix
+				if (! empty($conf->global->PRODUIT_MULTIPRICES))
+					$form->select_produits('','idprod'.$i,'',$conf->product->limit_size,$soc->price_level);
+				else
+					$form->select_produits('','idprod'.$i,'',$conf->product->limit_size);
+				print '</td>';
+				print '<td><input type="text" size="2" name="qty'.$i.'" value="1"></td>';
+				print '<td nowrap="nowrap"><input type="text" size="1" name="remise_percent'.$i.'" value="'.$soc->remise_client.'">%</td>';
+				print '<td>&nbsp;</td>';
+				// Si le module service est actif, on propose des dates de debut et fin a la ligne
 				if (! empty($conf->service->enabled))
 				{
-					print '<td>'.$langs->trans('ServiceLimitedDuration').'</td>';
-				}
-				print '</tr>';
-				for ($i = 1 ; $i <= $NBLINES ; $i++)
-				{
-					print '<tr>';
-					print '<td>';
-					// multiprix
-					if (! empty($conf->global->PRODUIT_MULTIPRICES))
-						$form->select_produits('','idprod'.$i,'',$conf->product->limit_size,$soc->price_level);
-					else
-						$form->select_produits('','idprod'.$i,'',$conf->product->limit_size);
+					print '<td nowrap="nowrap">';
+					print '<table class="nobordernopadding"><tr class="nocellnopadd">';
+					print '<td class="nobordernopadding" nowrap="nowrap">';
+					print $langs->trans('From').' ';
+					print '</td><td class="nobordernopadding" nowrap="nowrap">';
+					print $form->select_date('','date_start'.$i,$usehm,$usehm,1,"add");
+					print '</td></tr>';
+					print '<td class="nobordernopadding" nowrap="nowrap">';
+					print $langs->trans('to').' ';
+					print '</td><td class="nobordernopadding" nowrap="nowrap">';
+					print $form->select_date('','date_end'.$i,$usehm,$usehm,1,"add");
+					print '</td></tr></table>';
 					print '</td>';
-					print '<td><input type="text" size="2" name="qty'.$i.'" value="1"></td>';
-					print '<td nowrap="nowrap"><input type="text" size="1" name="remise_percent'.$i.'" value="'.$soc->remise_client.'">%</td>';
-					print '<td>&nbsp;</td>';
-					// Si le module service est actif, on propose des dates de debut et fin a la ligne
-					if (! empty($conf->service->enabled))
-					{
-						print '<td nowrap="nowrap">';
-						print '<table class="nobordernopadding"><tr class="nocellnopadd">';
-						print '<td class="nobordernopadding" nowrap="nowrap">';
-						print $langs->trans('From').' ';
-						print '</td><td class="nobordernopadding" nowrap="nowrap">';
-						print $form->select_date('','date_start'.$i,$usehm,$usehm,1,"add");
-						print '</td></tr>';
-						print '<td class="nobordernopadding" nowrap="nowrap">';
-						print $langs->trans('to').' ';
-						print '</td><td class="nobordernopadding" nowrap="nowrap">';
-						print $form->select_date('','date_end'.$i,$usehm,$usehm,1,"add");
-						print '</td></tr></table>';
-						print '</td>';
-					}
-					print "</tr>\n";
 				}
-
-				print '</table>';
-				print '</td></tr>';
+				print "</tr>\n";
 			}
-		}
 
-		print "</table>\n";
+			print '</table>';
+			print '</td></tr>';
+		}
+	}
 
-		// Button "Create Draft"
-		print '<br><center><input type="submit" class="button" name="bouton" value="'.$langs->trans('CreateDraft').'"></center>';
+	print "</table>\n";
 
-		print "</form>\n";
+	// Button "Create Draft"
+	print '<br><center><input type="submit" class="button" name="bouton" value="'.$langs->trans('CreateDraft').'"></center>';
 
-		// Show origin lines
-		if (! empty($origin) && ! empty($originid) && is_object($objectsrc))
-		{
-			print '<br>';
+	print "</form>\n";
 
-			$title=$langs->trans('ProductsAndServices');
-			print_titre($title);
+	// Show origin lines
+	if (! empty($origin) && ! empty($originid) && is_object($objectsrc))
+	{
+		print '<br>';
 
-			print '<table class="noborder" width="100%">';
+		$title=$langs->trans('ProductsAndServices');
+		print_titre($title);
 
-			$objectsrc->printOriginLinesList();
+		print '<table class="noborder" width="100%">';
 
-			print '</table>';
-		}
+		$objectsrc->printOriginLinesList();
 
+		print '</table>';
 	}
-	else if ($id > 0 || ! empty($ref))
-	{
-		/*
-		 * Show object in view mode
-		*/
 
-		$result=$object->fetch($id,$ref);
+}
+else if ($id > 0 || ! empty($ref))
+{
+	/*
+	 * Show object in view mode
+	*/
 
-		// fetch optionals attributes and labels
-		$extralabels=$extrafields->fetch_name_optionals_label('facture');
+	$result=$object->fetch($id,$ref);
 
-		if ($result > 0)
-		{
-			if ($user->societe_id>0 && $user->societe_id!=$object->socid)  accessforbidden('',0);
+	// fetch optionals attributes and labels
+	$extralabels=$extrafields->fetch_name_optionals_label('facture');
 
-			$result=$object->fetch_thirdparty();
+	if ($result > 0)
+	{
+		if ($user->societe_id>0 && $user->societe_id!=$object->socid)  accessforbidden('',0);
 
-			$soc = new Societe($db);
-			$soc->fetch($object->socid);
-			$selleruserevenustamp=$mysoc->useRevenueStamp();
+		$result=$object->fetch_thirdparty();
 
-			$totalpaye  = $object->getSommePaiement();
-			$totalcreditnotes = $object->getSumCreditNotesUsed();
-			$totaldeposits = $object->getSumDepositsUsed();
-			//print "totalpaye=".$totalpaye." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits." selleruserrevenuestamp=".$selleruserevenustamp;
+		$soc = new Societe($db);
+		$soc->fetch($object->socid);
+		$selleruserevenustamp=$mysoc->useRevenueStamp();
 
-			// We can also use bcadd to avoid pb with floating points
-			// For example print 239.2 - 229.3 - 9.9; does not return 0.
-			//$resteapayer=bcadd($object->total_ttc,$totalpaye,$conf->global->MAIN_MAX_DECIMALS_TOT);
-			//$resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT);
-			$resteapayer = price2num($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits,'MT');
+		$totalpaye  = $object->getSommePaiement();
+		$totalcreditnotes = $object->getSumCreditNotesUsed();
+		$totaldeposits = $object->getSumDepositsUsed();
+		//print "totalpaye=".$totalpaye." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits." selleruserrevenuestamp=".$selleruserevenustamp;
 
-			if ($object->paye) $resteapayer=0;
-			$resteapayeraffiche=$resteapayer;
+		// We can also use bcadd to avoid pb with floating points
+		// For example print 239.2 - 229.3 - 9.9; does not return 0.
+		//$resteapayer=bcadd($object->total_ttc,$totalpaye,$conf->global->MAIN_MAX_DECIMALS_TOT);
+		//$resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT);
+		$resteapayer = price2num($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits,'MT');
 
-			if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
-			{
-				$filterabsolutediscount="fk_facture_source IS NULL";  // If we want deposit to be substracted to payments only and not to total of final invoice
-				$filtercreditnote="fk_facture_source IS NOT NULL";    // If we want deposit to be substracted to payments only and not to total of final invoice
-			}
-			else
-			{
-				$filterabsolutediscount="fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND description='(DEPOSIT)')";
-				$filtercreditnote="fk_facture_source IS NOT NULL AND description <> '(DEPOSIT)'";
-			}
+		if ($object->paye) $resteapayer=0;
+		$resteapayeraffiche=$resteapayer;
 
-			$absolute_discount=$soc->getAvailableDiscounts('',$filterabsolutediscount);
-			$absolute_creditnote=$soc->getAvailableDiscounts('',$filtercreditnote);
-			$absolute_discount=price2num($absolute_discount,'MT');
-			$absolute_creditnote=price2num($absolute_creditnote,'MT');
+		if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
+		{
+			$filterabsolutediscount="fk_facture_source IS NULL";  // If we want deposit to be substracted to payments only and not to total of final invoice
+			$filtercreditnote="fk_facture_source IS NOT NULL";    // If we want deposit to be substracted to payments only and not to total of final invoice
+		}
+		else
+		{
+			$filterabsolutediscount="fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND description='(DEPOSIT)')";
+			$filtercreditnote="fk_facture_source IS NOT NULL AND description <> '(DEPOSIT)'";
+		}
 
-			$author = new User($db);
-			if ($object->user_author)
-			{
-				$author->fetch($object->user_author);
-			}
+		$absolute_discount=$soc->getAvailableDiscounts('',$filterabsolutediscount);
+		$absolute_creditnote=$soc->getAvailableDiscounts('',$filtercreditnote);
+		$absolute_discount=price2num($absolute_discount,'MT');
+		$absolute_creditnote=price2num($absolute_creditnote,'MT');
+
+		$author = new User($db);
+		if ($object->user_author)
+		{
+			$author->fetch($object->user_author);
+		}
 
-			$objectidnext=$object->getIdReplacingInvoice();
+		$objectidnext=$object->getIdReplacingInvoice();
 
 
-			$head = facture_prepare_head($object);
+		$head = facture_prepare_head($object);
 
-			dol_fiche_head($head, 'compta', $langs->trans('InvoiceCustomer'), 0, 'bill');
+		dol_fiche_head($head, 'compta', $langs->trans('InvoiceCustomer'), 0, 'bill');
 
-			$formconfirm='';
+		$formconfirm='';
 
-			// Confirmation de la conversion de l'avoir en reduc
-			if ($action == 'converttoreduc')
+		// Confirmation de la conversion de l'avoir en reduc
+		if ($action == 'converttoreduc')
+		{
+			$text=$langs->trans('ConfirmConvertToReduc');
+			$formconfirm=$form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id,$langs->trans('ConvertToReduc'),$text,'confirm_converttoreduc','',"yes",2);
+		}
+
+		// Confirmation to delete invoice
+		if ($action == 'delete')
+		{
+			$text=$langs->trans('ConfirmDeleteBill',$object->ref);
+			$formquestion=array();
+
+			$qualified_for_stock_change=0;
+			if (empty($conf->global->STOCK_SUPPORTS_SERVICES))
 			{
-				$text=$langs->trans('ConfirmConvertToReduc');
-				$formconfirm=$form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id,$langs->trans('ConvertToReduc'),$text,'confirm_converttoreduc','',"yes",2);
+				$qualified_for_stock_change=$object->hasProductsOrServices(2);
 			}
-
-			// Confirmation to delete invoice
-			if ($action == 'delete')
+			else
 			{
-				$text=$langs->trans('ConfirmDeleteBill',$object->ref);
-				$formquestion=array();
-				
-				$qualified_for_stock_change=0;
-				if (empty($conf->global->STOCK_SUPPORTS_SERVICES))
-				{
-					$qualified_for_stock_change=$object->hasProductsOrServices(2);
-				}
-				else
-				{
-					$qualified_for_stock_change=$object->hasProductsOrServices(1);
-				}
-				
-				if ($object->type != 3 && ! empty($conf->global->STOCK_CALCULATE_ON_BILL) && $qualified_for_stock_change && $object->statut>=1)
-				{
-					$langs->load("stocks");
-					require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
-					$formproduct=new FormProduct($db);
-					$label=$object->type==2?$langs->trans("SelectWarehouseForStockDecrease"):$langs->trans("SelectWarehouseForStockIncrease");
-					$formquestion=array(
-					//'text' => $langs->trans("ConfirmClone"),
-					//array('type' => 'checkbox', 'name' => 'clone_content',   'label' => $langs->trans("CloneMainAttributes"),   'value' => 1),
-					//array('type' => 'checkbox', 'name' => 'update_prices',   'label' => $langs->trans("PuttingPricesUpToDate"),   'value' => 1),
-					array('type' => 'other', 'name' => 'idwarehouse',   'label' => $label,   'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse'),'idwarehouse','',1,0,0,$langs->trans("NoStockAction"))));
-					$formconfirm=$form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id,$langs->trans('DeleteBill'),$text,'confirm_delete',$formquestion,"yes",1);
-				}else {
-					$formconfirm=$form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id,$langs->trans('DeleteBill'),$text,'confirm_delete','','',1);
-				}
+				$qualified_for_stock_change=$object->hasProductsOrServices(1);
 			}
 
-			// Confirmation de la validation
-			if ($action == 'valid')
+			if ($object->type != 3 && ! empty($conf->global->STOCK_CALCULATE_ON_BILL) && $qualified_for_stock_change && $object->statut>=1)
 			{
-				// on verifie si l'objet est en numerotation provisoire
-				$objectref = substr($object->ref, 1, 4);
-				if ($objectref == 'PROV')
-				{
-					$savdate=$object->date;
-					if (! empty($conf->global->FAC_FORCE_DATE_VALIDATION))
-					{
-						$object->date=dol_now();
-						$object->date_lim_reglement=$object->calculate_date_lim_reglement();
-					}
-					$numref = $object->getNextNumRef($soc);
-					//$object->date=$savdate;
-				}
-				else
-				{
-					$numref = $object->ref;
-				}
-
-				$text=$langs->trans('ConfirmValidateBill',$numref);
-				if (! empty($conf->notification->enabled))
-				{
-					require_once DOL_DOCUMENT_ROOT .'/core/class/notify.class.php';
-					$notify=new Notify($db);
-					$text.='<br>';
-					$text.=$notify->confirmMessage('NOTIFY_VAL_FAC',$object->socid);
-				}
-				$formquestion=array();
-
-				$qualified_for_stock_change=0;
-				if (empty($conf->global->STOCK_SUPPORTS_SERVICES))
-				{
-					$qualified_for_stock_change=$object->hasProductsOrServices(2);
-				}
-				else
-				{
-					$qualified_for_stock_change=$object->hasProductsOrServices(1);
-				}
-
-				if ($object->type != 3 && ! empty($conf->global->STOCK_CALCULATE_ON_BILL) && $qualified_for_stock_change)
-				{
-					$langs->load("stocks");
-					require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
-					$formproduct=new FormProduct($db);
-					$label=$object->type==2?$langs->trans("SelectWarehouseForStockIncrease"):$langs->trans("SelectWarehouseForStockDecrease");
-					$formquestion=array(
-					//'text' => $langs->trans("ConfirmClone"),
-					//array('type' => 'checkbox', 'name' => 'clone_content',   'label' => $langs->trans("CloneMainAttributes"),   'value' => 1),
-					//array('type' => 'checkbox', 'name' => 'update_prices',   'label' => $langs->trans("PuttingPricesUpToDate"),   'value' => 1),
-					array('type' => 'other', 'name' => 'idwarehouse',   'label' => $label,   'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse'),'idwarehouse','',1)));
-				}
-				if ($object->type != 2 && $object->total_ttc < 0)    // Can happen only if $conf->global->FACTURE_ENABLE_NEGATIVE is on
-				{
-					$text.='<br>'.img_warning().' '.$langs->trans("ErrorInvoiceOfThisTypeMustBePositive");
-				}
-				$formconfirm=$form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id,$langs->trans('ValidateBill'),$text,'confirm_valid',$formquestion,(($object->type != 2 && $object->total_ttc < 0)?"no":"yes"),($conf->notification->enabled?0:2));
+				$langs->load("stocks");
+				require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
+				$formproduct=new FormProduct($db);
+				$label=$object->type==2?$langs->trans("SelectWarehouseForStockDecrease"):$langs->trans("SelectWarehouseForStockIncrease");
+				$formquestion=array(
+				//'text' => $langs->trans("ConfirmClone"),
+				//array('type' => 'checkbox', 'name' => 'clone_content',   'label' => $langs->trans("CloneMainAttributes"),   'value' => 1),
+				//array('type' => 'checkbox', 'name' => 'update_prices',   'label' => $langs->trans("PuttingPricesUpToDate"),   'value' => 1),
+				array('type' => 'other', 'name' => 'idwarehouse',   'label' => $label,   'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse'),'idwarehouse','',1,0,0,$langs->trans("NoStockAction"))));
+				$formconfirm=$form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id,$langs->trans('DeleteBill'),$text,'confirm_delete',$formquestion,"yes",1);
+			}else {
+				$formconfirm=$form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id,$langs->trans('DeleteBill'),$text,'confirm_delete','','',1);
 			}
+		}
 
-			// Confirm back to draft status
-			if ($action == 'modif')
+		// Confirmation de la validation
+		if ($action == 'valid')
+		{
+			// on verifie si l'objet est en numerotation provisoire
+			$objectref = substr($object->ref, 1, 4);
+			if ($objectref == 'PROV')
 			{
-				$text=$langs->trans('ConfirmUnvalidateBill',$object->ref);
-				$formquestion=array();
-
-				$qualified_for_stock_change=0;
-				if (empty($conf->global->STOCK_SUPPORTS_SERVICES))
-				{
-					$qualified_for_stock_change=$object->hasProductsOrServices(2);
-				}
-				else
-				{
-					$qualified_for_stock_change=$object->hasProductsOrServices(1);
-				}
-				if ($object->type != 3 && ! empty($conf->global->STOCK_CALCULATE_ON_BILL) && $qualified_for_stock_change)
+				$savdate=$object->date;
+				if (! empty($conf->global->FAC_FORCE_DATE_VALIDATION))
 				{
-					$langs->load("stocks");
-					require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
-					$formproduct=new FormProduct($db);
-					$label=$object->type==2?$langs->trans("SelectWarehouseForStockDecrease"):$langs->trans("SelectWarehouseForStockIncrease");
-					$formquestion=array(
-					//'text' => $langs->trans("ConfirmClone"),
-					//array('type' => 'checkbox', 'name' => 'clone_content',   'label' => $langs->trans("CloneMainAttributes"),   'value' => 1),
-					//array('type' => 'checkbox', 'name' => 'update_prices',   'label' => $langs->trans("PuttingPricesUpToDate"),   'value' => 1),
-					array('type' => 'other', 'name' => 'idwarehouse',   'label' => $label,   'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse'),'idwarehouse','',1)));
+					$object->date=dol_now();
+					$object->date_lim_reglement=$object->calculate_date_lim_reglement();
 				}
-
-				$formconfirm=$form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id,$langs->trans('UnvalidateBill'),$text,'confirm_modif',$formquestion,"yes",1);
+				$numref = $object->getNextNumRef($soc);
+				//$object->date=$savdate;
 			}
-
-			// Confirmation du classement paye
-			if ($action == 'paid' && $resteapayer <= 0)
+			else
 			{
-				$formconfirm=$form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id,$langs->trans('ClassifyPaid'),$langs->trans('ConfirmClassifyPaidBill',$object->ref),'confirm_paid','',"yes",1);
+				$numref = $object->ref;
 			}
-			if ($action == 'paid' && $resteapayer > 0)
-			{
-				// Code
-				$i=0;
-				$close[$i]['code']='discount_vat';$i++;
-				$close[$i]['code']='badcustomer';$i++;
-				// Help
-				$i=0;
-				$close[$i]['label']=$langs->trans("HelpEscompte").'<br><br>'.$langs->trans("ConfirmClassifyPaidPartiallyReasonDiscountVatDesc");$i++;
-				$close[$i]['label']=$langs->trans("ConfirmClassifyPaidPartiallyReasonBadCustomerDesc");$i++;
-				// Texte
-				$i=0;
-				$close[$i]['reason']=$form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonDiscountVat",$resteapayer,$langs->trans("Currency".$conf->currency)),$close[$i]['label'],1);$i++;
-				$close[$i]['reason']=$form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer",$resteapayer,$langs->trans("Currency".$conf->currency)),$close[$i]['label'],1);$i++;
-				// arrayreasons[code]=reason
-				foreach($close as $key => $val)
-				{
-					$arrayreasons[$close[$key]['code']]=$close[$key]['reason'];
-				}
 
-				// Cree un tableau formulaire
-				$formquestion=array(
-				'text' => $langs->trans("ConfirmClassifyPaidPartiallyQuestion"),
-				array('type' => 'radio', 'name' => 'close_code', 'label' => $langs->trans("Reason"),  'values' => $arrayreasons),
-				array('type' => 'text',  'name' => 'close_note', 'label' => $langs->trans("Comment"), 'value' => '', 'size' => '100')
-				);
-				// Paiement incomplet. On demande si motif = escompte ou autre
-				$formconfirm=$form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id,$langs->trans('ClassifyPaid'),$langs->trans('ConfirmClassifyPaidPartially',$object->ref),'confirm_paid_partially',$formquestion,"yes");
+			$text=$langs->trans('ConfirmValidateBill',$numref);
+			if (! empty($conf->notification->enabled))
+			{
+				require_once DOL_DOCUMENT_ROOT .'/core/class/notify.class.php';
+				$notify=new Notify($db);
+				$text.='<br>';
+				$text.=$notify->confirmMessage('NOTIFY_VAL_FAC',$object->socid);
 			}
+			$formquestion=array();
 
-			// Confirmation du classement abandonne
-			if ($action == 'canceled')
+			$qualified_for_stock_change=0;
+			if (empty($conf->global->STOCK_SUPPORTS_SERVICES))
 			{
-				// S'il y a une facture de remplacement pas encore validee (etat brouillon),
-				// on ne permet pas de classer abandonner la facture.
-				if ($objectidnext)
-				{
-					$facturereplacement=new Facture($db);
-					$facturereplacement->fetch($objectidnext);
-					$statusreplacement=$facturereplacement->statut;
-				}
-				if ($objectidnext && $statusreplacement == 0)
-				{
-					print '<div class="error">'.$langs->trans("ErrorCantCancelIfReplacementInvoiceNotValidated").'</div>';
-				}
-				else
-				{
-					// Code
-					$close[1]['code']='badcustomer';
-					$close[2]['code']='abandon';
-					// Help
-					$close[1]['label']=$langs->trans("ConfirmClassifyPaidPartiallyReasonBadCustomerDesc");
-					$close[2]['label']=$langs->trans("ConfirmClassifyAbandonReasonOtherDesc");
-					// Texte
-					$close[1]['reason']=$form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer",$object->ref),$close[1]['label'],1);
-					$close[2]['reason']=$form->textwithpicto($langs->transnoentities("ConfirmClassifyAbandonReasonOther"),$close[2]['label'],1);
-					// arrayreasons
-					$arrayreasons[$close[1]['code']]=$close[1]['reason'];
-					$arrayreasons[$close[2]['code']]=$close[2]['reason'];
-
-					// Cree un tableau formulaire
-					$formquestion=array(
-					'text' => $langs->trans("ConfirmCancelBillQuestion"),
-					array('type' => 'radio', 'name' => 'close_code', 'label' => $langs->trans("Reason"),  'values' => $arrayreasons),
-					array('type' => 'text',  'name' => 'close_note', 'label' => $langs->trans("Comment"), 'value' => '', 'size' => '100')
-					);
-
-					$formconfirm=$form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id,$langs->trans('CancelBill'),$langs->trans('ConfirmCancelBill',$object->ref),'confirm_canceled',$formquestion,"yes");
-				}
+				$qualified_for_stock_change=$object->hasProductsOrServices(2);
 			}
-
-			// Confirmation de la suppression d'une ligne produit
-			if ($action == 'ask_deleteline')
+			else
 			{
-				$formconfirm=$form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 'no', 1);
+				$qualified_for_stock_change=$object->hasProductsOrServices(1);
 			}
 
-			// Clone confirmation
-			if ($action == 'clone')
+			if ($object->type != 3 && ! empty($conf->global->STOCK_CALCULATE_ON_BILL) && $qualified_for_stock_change)
 			{
-				// Create an array for form
+				$langs->load("stocks");
+				require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
+				$formproduct=new FormProduct($db);
+				$label=$object->type==2?$langs->trans("SelectWarehouseForStockIncrease"):$langs->trans("SelectWarehouseForStockDecrease");
 				$formquestion=array(
 				//'text' => $langs->trans("ConfirmClone"),
-				//array('type' => 'checkbox', 'name' => 'clone_content',   'label' => $langs->trans("CloneMainAttributes"),   'value' => 1)
-				);
-				// Paiement incomplet. On demande si motif = escompte ou autre
-				$formconfirm=$form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id,$langs->trans('CloneInvoice'),$langs->trans('ConfirmCloneInvoice',$object->ref),'confirm_clone',$formquestion,'yes',1);
+				//array('type' => 'checkbox', 'name' => 'clone_content',   'label' => $langs->trans("CloneMainAttributes"),   'value' => 1),
+				//array('type' => 'checkbox', 'name' => 'update_prices',   'label' => $langs->trans("PuttingPricesUpToDate"),   'value' => 1),
+				array('type' => 'other', 'name' => 'idwarehouse',   'label' => $label,   'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse'),'idwarehouse','',1)));
 			}
-
-			if (! $formconfirm)
+			if ($object->type != 2 && $object->total_ttc < 0)    // Can happen only if $conf->global->FACTURE_ENABLE_NEGATIVE is on
 			{
-				$parameters=array('lineid'=>$lineid);
-				$formconfirm=$hookmanager->executeHooks('formConfirm',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
+				$text.='<br>'.img_warning().' '.$langs->trans("ErrorInvoiceOfThisTypeMustBePositive");
 			}
+			$formconfirm=$form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id,$langs->trans('ValidateBill'),$text,'confirm_valid',$formquestion,(($object->type != 2 && $object->total_ttc < 0)?"no":"yes"),($conf->notification->enabled?0:2));
+		}
 
-			// Print form confirm
-			print $formconfirm;
-
-
-			// Invoice content
-
-			print '<table class="border" width="100%">';
-
-			$linkback = '<a href="'.DOL_URL_ROOT.'/compta/facture/list.php'.(! empty($socid)?'?socid='.$socid:'').'">'.$langs->trans("BackToList").'</a>';
-
-			// Ref
-			print '<tr><td width="20%">'.$langs->trans('Ref').'</td>';
-			print '<td colspan="5">';
-			$morehtmlref='';
-			$discount=new DiscountAbsolute($db);
-			$result=$discount->fetch(0,$object->id);
-			if ($result > 0)
-			{
-				$morehtmlref=' ('.$langs->trans("CreditNoteConvertedIntoDiscount",$discount->getNomUrl(1,'discount')).')';
-			}
-			if ($result < 0)
-			{
-				dol_print_error('',$discount->error);
-			}
-			print $form->showrefnav($object, 'ref', $linkback, 1, 'facnumber', 'ref', $morehtmlref);
-			print '</td></tr>';
+		// Confirm back to draft status
+		if ($action == 'modif')
+		{
+			$text=$langs->trans('ConfirmUnvalidateBill',$object->ref);
+			$formquestion=array();
 
-			// Ref customer
-			print '<tr><td width="20%">';
-			print '<table class="nobordernopadding" width="100%"><tr><td>';
-			print $langs->trans('RefCustomer');
-			print '</td>';
-			if ($action != 'refclient' && ! empty($object->brouillon)) print '<td align="right"><a href="'.$_SERVER['PHP_SELF'].'?action=refclient&amp;id='.$object->id.'">'.img_edit($langs->trans('Modify')).'</a></td>';
-			print '</tr></table>';
-			print '</td>';
-			print '<td colspan="5">';
-			if ($user->rights->facture->creer && $action == 'refclient')
+			$qualified_for_stock_change=0;
+			if (empty($conf->global->STOCK_SUPPORTS_SERVICES))
 			{
-				print '<form action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post">';
-				print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
-				print '<input type="hidden" name="action" value="set_ref_client">';
-				print '<input type="text" class="flat" size="20" name="ref_client" value="'.$object->ref_client.'">';
-				print ' <input type="submit" class="button" value="'.$langs->trans('Modify').'">';
-				print '</form>';
+				$qualified_for_stock_change=$object->hasProductsOrServices(2);
 			}
 			else
 			{
-				print $object->ref_client;
+				$qualified_for_stock_change=$object->hasProductsOrServices(1);
 			}
-			print '</td></tr>';
-
-			// Third party
-			print '<tr><td>';
-			print '<table class="nobordernopadding" width="100%">';
-			print '<tr><td>'.$langs->trans('Company').'</td>';
-			print '</td><td colspan="5">';
-			if (! empty($conf->global->FACTURE_CHANGE_THIRDPARTY) && $action != 'editthirdparty' && $object->brouillon && $user->rights->facture->creer)
-				print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editthirdparty&amp;facid='.$object->id.'">'.img_edit($langs->trans('SetLinkToThirdParty'),1).'</a></td>';
-			print '</tr></table>';
-			print '</td><td colspan="5">';
-			if ($action == 'editthirdparty')
+			if ($object->type != 3 && ! empty($conf->global->STOCK_CALCULATE_ON_BILL) && $qualified_for_stock_change)
 			{
-				$form->form_thirdparty($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->socid,'socid');
+				$langs->load("stocks");
+				require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
+				$formproduct=new FormProduct($db);
+				$label=$object->type==2?$langs->trans("SelectWarehouseForStockDecrease"):$langs->trans("SelectWarehouseForStockIncrease");
+				$formquestion=array(
+				//'text' => $langs->trans("ConfirmClone"),
+				//array('type' => 'checkbox', 'name' => 'clone_content',   'label' => $langs->trans("CloneMainAttributes"),   'value' => 1),
+				//array('type' => 'checkbox', 'name' => 'update_prices',   'label' => $langs->trans("PuttingPricesUpToDate"),   'value' => 1),
+				array('type' => 'other', 'name' => 'idwarehouse',   'label' => $label,   'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse'),'idwarehouse','',1)));
 			}
-			else
+
+			$formconfirm=$form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id,$langs->trans('UnvalidateBill'),$text,'confirm_modif',$formquestion,"yes",1);
+		}
+
+		// Confirmation du classement paye
+		if ($action == 'paid' && $resteapayer <= 0)
+		{
+			$formconfirm=$form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id,$langs->trans('ClassifyPaid'),$langs->trans('ConfirmClassifyPaidBill',$object->ref),'confirm_paid','',"yes",1);
+		}
+		if ($action == 'paid' && $resteapayer > 0)
+		{
+			// Code
+			$i=0;
+			$close[$i]['code']='discount_vat';$i++;
+			$close[$i]['code']='badcustomer';$i++;
+			// Help
+			$i=0;
+			$close[$i]['label']=$langs->trans("HelpEscompte").'<br><br>'.$langs->trans("ConfirmClassifyPaidPartiallyReasonDiscountVatDesc");$i++;
+			$close[$i]['label']=$langs->trans("ConfirmClassifyPaidPartiallyReasonBadCustomerDesc");$i++;
+			// Texte
+			$i=0;
+			$close[$i]['reason']=$form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonDiscountVat",$resteapayer,$langs->trans("Currency".$conf->currency)),$close[$i]['label'],1);$i++;
+			$close[$i]['reason']=$form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer",$resteapayer,$langs->trans("Currency".$conf->currency)),$close[$i]['label'],1);$i++;
+			// arrayreasons[code]=reason
+			foreach($close as $key => $val)
 			{
-				print ' &nbsp;'.$soc->getNomUrl(1,'compta');
-				print ' &nbsp; (<a href="'.DOL_URL_ROOT.'/compta/facture/list.php?socid='.$object->socid.'">'.$langs->trans('OtherBills').'</a>)';
+				$arrayreasons[$close[$key]['code']]=$close[$key]['reason'];
 			}
-			print '</tr>';
 
-			// Type
-			print '<tr><td>'.$langs->trans('Type').'</td><td colspan="5">';
-			print $object->getLibType();
-			if ($object->type == 1)
+			// Cree un tableau formulaire
+			$formquestion=array(
+			'text' => $langs->trans("ConfirmClassifyPaidPartiallyQuestion"),
+			array('type' => 'radio', 'name' => 'close_code', 'label' => $langs->trans("Reason"),  'values' => $arrayreasons),
+			array('type' => 'text',  'name' => 'close_note', 'label' => $langs->trans("Comment"), 'value' => '', 'size' => '100')
+			);
+			// Paiement incomplet. On demande si motif = escompte ou autre
+			$formconfirm=$form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id,$langs->trans('ClassifyPaid'),$langs->trans('ConfirmClassifyPaidPartially',$object->ref),'confirm_paid_partially',$formquestion,"yes");
+		}
+
+		// Confirmation du classement abandonne
+		if ($action == 'canceled')
+		{
+			// S'il y a une facture de remplacement pas encore validee (etat brouillon),
+			// on ne permet pas de classer abandonner la facture.
+			if ($objectidnext)
 			{
-				$facreplaced=new Facture($db);
-				$facreplaced->fetch($object->fk_facture_source);
-				print ' ('.$langs->transnoentities("ReplaceInvoice",$facreplaced->getNomUrl(1)).')';
+				$facturereplacement=new Facture($db);
+				$facturereplacement->fetch($objectidnext);
+				$statusreplacement=$facturereplacement->statut;
 			}
-			if ($object->type == 2)
+			if ($objectidnext && $statusreplacement == 0)
 			{
-				$facusing=new Facture($db);
-				$facusing->fetch($object->fk_facture_source);
-				print ' ('.$langs->transnoentities("CorrectInvoice",$facusing->getNomUrl(1)).')';
+				print '<div class="error">'.$langs->trans("ErrorCantCancelIfReplacementInvoiceNotValidated").'</div>';
 			}
-
-			$facidavoir=$object->getListIdAvoirFromInvoice();
-			if (count($facidavoir) > 0)
+			else
 			{
-				print ' ('.$langs->transnoentities("InvoiceHasAvoir");
-				$i=0;
-				foreach($facidavoir as $id)
-				{
-					if ($i==0) print ' ';
-					else print ',';
-					$facavoir=new Facture($db);
-					$facavoir->fetch($id);
-					print $facavoir->getNomUrl(1);
-				}
-				print ')';
+				// Code
+				$close[1]['code']='badcustomer';
+				$close[2]['code']='abandon';
+				// Help
+				$close[1]['label']=$langs->trans("ConfirmClassifyPaidPartiallyReasonBadCustomerDesc");
+				$close[2]['label']=$langs->trans("ConfirmClassifyAbandonReasonOtherDesc");
+				// Texte
+				$close[1]['reason']=$form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer",$object->ref),$close[1]['label'],1);
+				$close[2]['reason']=$form->textwithpicto($langs->transnoentities("ConfirmClassifyAbandonReasonOther"),$close[2]['label'],1);
+				// arrayreasons
+				$arrayreasons[$close[1]['code']]=$close[1]['reason'];
+				$arrayreasons[$close[2]['code']]=$close[2]['reason'];
+
+				// Cree un tableau formulaire
+				$formquestion=array(
+				'text' => $langs->trans("ConfirmCancelBillQuestion"),
+				array('type' => 'radio', 'name' => 'close_code', 'label' => $langs->trans("Reason"),  'values' => $arrayreasons),
+				array('type' => 'text',  'name' => 'close_note', 'label' => $langs->trans("Comment"), 'value' => '', 'size' => '100')
+				);
+
+				$formconfirm=$form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id,$langs->trans('CancelBill'),$langs->trans('ConfirmCancelBill',$object->ref),'confirm_canceled',$formquestion,"yes");
 			}
-			if ($objectidnext > 0)
+		}
+
+		// Confirmation de la suppression d'une ligne produit
+		if ($action == 'ask_deleteline')
+		{
+			$formconfirm=$form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 'no', 1);
+		}
+
+		// Clone confirmation
+		if ($action == 'clone')
+		{
+			// Create an array for form
+			$formquestion=array(
+			//'text' => $langs->trans("ConfirmClone"),
+			//array('type' => 'checkbox', 'name' => 'clone_content',   'label' => $langs->trans("CloneMainAttributes"),   'value' => 1)
+			);
+			// Paiement incomplet. On demande si motif = escompte ou autre
+			$formconfirm=$form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id,$langs->trans('CloneInvoice'),$langs->trans('ConfirmCloneInvoice',$object->ref),'confirm_clone',$formquestion,'yes',1);
+		}
+
+		if (! $formconfirm)
+		{
+			$parameters=array('lineid'=>$lineid);
+			$formconfirm=$hookmanager->executeHooks('formConfirm',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
+		}
+
+		// Print form confirm
+		print $formconfirm;
+
+
+		// Invoice content
+
+		print '<table class="border" width="100%">';
+
+		$linkback = '<a href="'.DOL_URL_ROOT.'/compta/facture/list.php'.(! empty($socid)?'?socid='.$socid:'').'">'.$langs->trans("BackToList").'</a>';
+
+		// Ref
+		print '<tr><td width="20%">'.$langs->trans('Ref').'</td>';
+		print '<td colspan="5">';
+		$morehtmlref='';
+		$discount=new DiscountAbsolute($db);
+		$result=$discount->fetch(0,$object->id);
+		if ($result > 0)
+		{
+			$morehtmlref=' ('.$langs->trans("CreditNoteConvertedIntoDiscount",$discount->getNomUrl(1,'discount')).')';
+		}
+		if ($result < 0)
+		{
+			dol_print_error('',$discount->error);
+		}
+		print $form->showrefnav($object, 'ref', $linkback, 1, 'facnumber', 'ref', $morehtmlref);
+		print '</td></tr>';
+
+		// Ref customer
+		print '<tr><td width="20%">';
+		print '<table class="nobordernopadding" width="100%"><tr><td>';
+		print $langs->trans('RefCustomer');
+		print '</td>';
+		if ($action != 'refclient' && ! empty($object->brouillon)) print '<td align="right"><a href="'.$_SERVER['PHP_SELF'].'?action=refclient&amp;id='.$object->id.'">'.img_edit($langs->trans('Modify')).'</a></td>';
+		print '</tr></table>';
+		print '</td>';
+		print '<td colspan="5">';
+		if ($user->rights->facture->creer && $action == 'refclient')
+		{
+			print '<form action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post">';
+			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
+			print '<input type="hidden" name="action" value="set_ref_client">';
+			print '<input type="text" class="flat" size="20" name="ref_client" value="'.$object->ref_client.'">';
+			print ' <input type="submit" class="button" value="'.$langs->trans('Modify').'">';
+			print '</form>';
+		}
+		else
+		{
+			print $object->ref_client;
+		}
+		print '</td></tr>';
+
+		// Third party
+		print '<tr><td>';
+		print '<table class="nobordernopadding" width="100%">';
+		print '<tr><td>'.$langs->trans('Company').'</td>';
+		print '</td><td colspan="5">';
+		if (! empty($conf->global->FACTURE_CHANGE_THIRDPARTY) && $action != 'editthirdparty' && $object->brouillon && $user->rights->facture->creer)
+			print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editthirdparty&amp;facid='.$object->id.'">'.img_edit($langs->trans('SetLinkToThirdParty'),1).'</a></td>';
+		print '</tr></table>';
+		print '</td><td colspan="5">';
+		if ($action == 'editthirdparty')
+		{
+			$form->form_thirdparty($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->socid,'socid');
+		}
+		else
+		{
+			print ' &nbsp;'.$soc->getNomUrl(1,'compta');
+			print ' &nbsp; (<a href="'.DOL_URL_ROOT.'/compta/facture/list.php?socid='.$object->socid.'">'.$langs->trans('OtherBills').'</a>)';
+		}
+		print '</tr>';
+
+		// Type
+		print '<tr><td>'.$langs->trans('Type').'</td><td colspan="5">';
+		print $object->getLibType();
+		if ($object->type == 1)
+		{
+			$facreplaced=new Facture($db);
+			$facreplaced->fetch($object->fk_facture_source);
+			print ' ('.$langs->transnoentities("ReplaceInvoice",$facreplaced->getNomUrl(1)).')';
+		}
+		if ($object->type == 2)
+		{
+			$facusing=new Facture($db);
+			$facusing->fetch($object->fk_facture_source);
+			print ' ('.$langs->transnoentities("CorrectInvoice",$facusing->getNomUrl(1)).')';
+		}
+
+		$facidavoir=$object->getListIdAvoirFromInvoice();
+		if (count($facidavoir) > 0)
+		{
+			print ' ('.$langs->transnoentities("InvoiceHasAvoir");
+			$i=0;
+			foreach($facidavoir as $id)
 			{
-				$facthatreplace=new Facture($db);
-				$facthatreplace->fetch($objectidnext);
-				print ' ('.$langs->transnoentities("ReplacedByInvoice",$facthatreplace->getNomUrl(1)).')';
+				if ($i==0) print ' ';
+				else print ',';
+				$facavoir=new Facture($db);
+				$facavoir->fetch($id);
+				print $facavoir->getNomUrl(1);
 			}
-			print '</td></tr>';
+			print ')';
+		}
+		if ($objectidnext > 0)
+		{
+			$facthatreplace=new Facture($db);
+			$facthatreplace->fetch($objectidnext);
+			print ' ('.$langs->transnoentities("ReplacedByInvoice",$facthatreplace->getNomUrl(1)).')';
+		}
+		print '</td></tr>';
 
-			// Relative and absolute discounts
-			$addrelativediscount='<a href="'.DOL_URL_ROOT.'/comm/remise.php?id='.$soc->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"]).'?facid='.$object->id.'">'.$langs->trans("EditRelativeDiscounts").'</a>';
-			$addabsolutediscount='<a href="'.DOL_URL_ROOT.'/comm/remx.php?id='.$soc->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"]).'?facid='.$object->id.'">'.$langs->trans("EditGlobalDiscounts").'</a>';
-			$addcreditnote='<a href="'.DOL_URL_ROOT.'/compta/facture.php?action=create&socid='.$soc->id.'&type=2&backtopage='.urlencode($_SERVER["PHP_SELF"]).'?facid='.$object->id.'">'.$langs->trans("AddCreditNote").'</a>';
+		// Relative and absolute discounts
+		$addrelativediscount='<a href="'.DOL_URL_ROOT.'/comm/remise.php?id='.$soc->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"]).'?facid='.$object->id.'">'.$langs->trans("EditRelativeDiscounts").'</a>';
+		$addabsolutediscount='<a href="'.DOL_URL_ROOT.'/comm/remx.php?id='.$soc->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"]).'?facid='.$object->id.'">'.$langs->trans("EditGlobalDiscounts").'</a>';
+		$addcreditnote='<a href="'.DOL_URL_ROOT.'/compta/facture.php?action=create&socid='.$soc->id.'&type=2&backtopage='.urlencode($_SERVER["PHP_SELF"]).'?facid='.$object->id.'">'.$langs->trans("AddCreditNote").'</a>';
 
-			print '<tr><td>'.$langs->trans('Discounts');
-			print '</td><td colspan="5">';
-			if ($soc->remise_client) print $langs->trans("CompanyHasRelativeDiscount",$soc->remise_client);
-			else print $langs->trans("CompanyHasNoRelativeDiscount");
-			//print ' ('.$addrelativediscount.')';
+		print '<tr><td>'.$langs->trans('Discounts');
+		print '</td><td colspan="5">';
+		if ($soc->remise_client) print $langs->trans("CompanyHasRelativeDiscount",$soc->remise_client);
+		else print $langs->trans("CompanyHasNoRelativeDiscount");
+		//print ' ('.$addrelativediscount.')';
 
-			if ($absolute_discount > 0)
+		if ($absolute_discount > 0)
+		{
+			print '. ';
+			if ($object->statut > 0 || $object->type == 2 || $object->type == 3)
 			{
-				print '. ';
-				if ($object->statut > 0 || $object->type == 2 || $object->type == 3)
+				if ($object->statut == 0)
+				{
+					print $langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->transnoentities("Currency".$conf->currency));
+					print '. ';
+				}
+				else
 				{
-					if ($object->statut == 0)
+					if ($object->statut < 1 || $object->type == 2 || $object->type == 3)
 					{
-						print $langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->transnoentities("Currency".$conf->currency));
-						print '. ';
+						$text=$langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->transnoentities("Currency".$conf->currency));
+						print '<br>'.$text.'.<br>';
 					}
 					else
 					{
-						if ($object->statut < 1 || $object->type == 2 || $object->type == 3)
-						{
-							$text=$langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->transnoentities("Currency".$conf->currency));
-							print '<br>'.$text.'.<br>';
-						}
-						else
-						{
-							$text=$langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->transnoentities("Currency".$conf->currency));
-							$text2=$langs->trans("AbsoluteDiscountUse");
-							print $form->textwithpicto($text,$text2);
-						}
+						$text=$langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->transnoentities("Currency".$conf->currency));
+						$text2=$langs->trans("AbsoluteDiscountUse");
+						print $form->textwithpicto($text,$text2);
 					}
 				}
-				else
-				{
-					// Remise dispo de type remise fixe (not credit note)
-					print '<br>';
-					$form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, GETPOST('discountid'), 'remise_id', $soc->id, $absolute_discount, $filterabsolutediscount, $resteapayer, ' ('.$addabsolutediscount.')');
-				}
 			}
 			else
 			{
-				if ($absolute_creditnote > 0)    // If not, link will be added later
-				{
-					if ($object->statut == 0 && $object->type != 2 && $object->type != 3) print ' ('.$addabsolutediscount.')<br>';
-					else print '. ';
-				}
+				// Remise dispo de type remise fixe (not credit note)
+				print '<br>';
+				$form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, GETPOST('discountid'), 'remise_id', $soc->id, $absolute_discount, $filterabsolutediscount, $resteapayer, ' ('.$addabsolutediscount.')');
+			}
+		}
+		else
+		{
+			if ($absolute_creditnote > 0)    // If not, link will be added later
+			{
+				if ($object->statut == 0 && $object->type != 2 && $object->type != 3) print ' ('.$addabsolutediscount.')<br>';
 				else print '. ';
 			}
-			if ($absolute_creditnote > 0)
+			else print '. ';
+		}
+		if ($absolute_creditnote > 0)
+		{
+			// If validated, we show link "add credit note to payment"
+			if ($object->statut != 1 || $object->type == 2 || $object->type == 3)
 			{
-				// If validated, we show link "add credit note to payment"
-				if ($object->statut != 1 || $object->type == 2 || $object->type == 3)
+				if ($object->statut == 0 && $object->type != 3)
 				{
-					if ($object->statut == 0 && $object->type != 3)
-					{
-						$text=$langs->trans("CompanyHasCreditNote",price($absolute_creditnote),$langs->transnoentities("Currency".$conf->currency));
-						print $form->textwithpicto($text,$langs->trans("CreditNoteDepositUse"));
-					}
-					else
-					{
-						print $langs->trans("CompanyHasCreditNote",price($absolute_creditnote),$langs->transnoentities("Currency".$conf->currency)).'.';
-					}
+					$text=$langs->trans("CompanyHasCreditNote",price($absolute_creditnote),$langs->transnoentities("Currency".$conf->currency));
+					print $form->textwithpicto($text,$langs->trans("CreditNoteDepositUse"));
 				}
 				else
 				{
-					// Remise dispo de type avoir
-					if (! $absolute_discount) print '<br>';
-					//$form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, 0, 'remise_id_for_payment', $soc->id, $absolute_creditnote, $filtercreditnote, $resteapayer);
-					$form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, 0, 'remise_id_for_payment', $soc->id, $absolute_creditnote, $filtercreditnote, 0);    // We must allow credit not even if amount is higher
+					print $langs->trans("CompanyHasCreditNote",price($absolute_creditnote),$langs->transnoentities("Currency".$conf->currency)).'.';
 				}
 			}
-			if (! $absolute_discount && ! $absolute_creditnote)
+			else
 			{
-				print $langs->trans("CompanyHasNoAbsoluteDiscount");
-				if ($object->statut == 0 && $object->type != 2 && $object->type != 3) print ' ('.$addabsolutediscount.')<br>';
-				else print '. ';
+				// Remise dispo de type avoir
+				if (! $absolute_discount) print '<br>';
+				//$form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, 0, 'remise_id_for_payment', $soc->id, $absolute_creditnote, $filtercreditnote, $resteapayer);
+				$form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, 0, 'remise_id_for_payment', $soc->id, $absolute_creditnote, $filtercreditnote, 0);    // We must allow credit not even if amount is higher
 			}
-			/*if ($object->statut == 0 && $object->type != 2 && $object->type != 3)
-			 {
-			if (! $absolute_discount && ! $absolute_creditnote) print '<br>';
-			//print ' &nbsp; - &nbsp; ';
-			print $addabsolutediscount;
-			//print ' &nbsp; - &nbsp; '.$addcreditnote;      // We disbale link to credit note
-			}*/
-			print '</td></tr>';
+		}
+		if (! $absolute_discount && ! $absolute_creditnote)
+		{
+			print $langs->trans("CompanyHasNoAbsoluteDiscount");
+			if ($object->statut == 0 && $object->type != 2 && $object->type != 3) print ' ('.$addabsolutediscount.')<br>';
+			else print '. ';
+		}
+		/*if ($object->statut == 0 && $object->type != 2 && $object->type != 3)
+		 {
+		if (! $absolute_discount && ! $absolute_creditnote) print '<br>';
+		//print ' &nbsp; - &nbsp; ';
+		print $addabsolutediscount;
+		//print ' &nbsp; - &nbsp; '.$addcreditnote;      // We disbale link to credit note
+		}*/
+		print '</td></tr>';
 
-			// Date invoice
-			print '<tr><td>';
-			print '<table class="nobordernopadding" width="100%"><tr><td>';
-			print $langs->trans('Date');
-			print '</td>';
-			if ($object->type != 2 && $action != 'editinvoicedate' && ! empty($object->brouillon) && $user->rights->facture->creer) print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editinvoicedate&amp;facid='.$object->id.'">'.img_edit($langs->trans('SetDate'),1).'</a></td>';
-			print '</tr></table>';
-			print '</td><td colspan="3">';
+		// Date invoice
+		print '<tr><td>';
+		print '<table class="nobordernopadding" width="100%"><tr><td>';
+		print $langs->trans('Date');
+		print '</td>';
+		if ($object->type != 2 && $action != 'editinvoicedate' && ! empty($object->brouillon) && $user->rights->facture->creer) print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editinvoicedate&amp;facid='.$object->id.'">'.img_edit($langs->trans('SetDate'),1).'</a></td>';
+		print '</tr></table>';
+		print '</td><td colspan="3">';
 
-			if ($object->type != 2)
+		if ($object->type != 2)
+		{
+			if ($action == 'editinvoicedate')
 			{
-				if ($action == 'editinvoicedate')
-				{
-					$form->form_date($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->date,'invoicedate');
-				}
-				else
-				{
-					print dol_print_date($object->date,'daytext');
-				}
+				$form->form_date($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->date,'invoicedate');
 			}
 			else
 			{
 				print dol_print_date($object->date,'daytext');
 			}
-			print '</td>';
-
-
-			/*
-			 * List of payments
-			*/
-
-			$sign=1;
-			if ($object->type == 2) $sign=-1;
-
-			$nbrows=8; $nbcols=2;
-			if (! empty($conf->projet->enabled)) $nbrows++;
-			if (! empty($conf->banque->enabled)) $nbcols++;
-			if($mysoc->localtax1_assuj=="1") $nbrows++;
-			if($mysoc->localtax2_assuj=="1") $nbrows++;
-			if ($selleruserevenustamp) $nbrows++;
-
-			print '<td rowspan="'.$nbrows.'" colspan="2" valign="top">';
+		}
+		else
+		{
+			print dol_print_date($object->date,'daytext');
+		}
+		print '</td>';
 
-			print '<table class="nobordernopadding" width="100%">';
 
-			// List of payments already done
-			print '<tr class="liste_titre">';
-			print '<td>'.($object->type == 2 ? $langs->trans("PaymentsBack") : $langs->trans('Payments')).'</td>';
-			print '<td>'.$langs->trans('Type').'</td>';
-			if (! empty($conf->banque->enabled)) print '<td align="right">'.$langs->trans('BankAccount').'</td>';
-			print '<td align="right">'.$langs->trans('Amount').'</td>';
-			print '<td width="18">&nbsp;</td>';
-			print '</tr>';
+		/*
+		 * List of payments
+		*/
 
-			$var=true;
+		$sign=1;
+		if ($object->type == 2) $sign=-1;
+
+		$nbrows=8; $nbcols=2;
+		if (! empty($conf->projet->enabled)) $nbrows++;
+		if (! empty($conf->banque->enabled)) $nbcols++;
+		if($mysoc->localtax1_assuj=="1") $nbrows++;
+		if($mysoc->localtax2_assuj=="1") $nbrows++;
+		if ($selleruserevenustamp) $nbrows++;
+
+		print '<td rowspan="'.$nbrows.'" colspan="2" valign="top">';
+
+		print '<table class="nobordernopadding" width="100%">';
+
+		// List of payments already done
+		print '<tr class="liste_titre">';
+		print '<td>'.($object->type == 2 ? $langs->trans("PaymentsBack") : $langs->trans('Payments')).'</td>';
+		print '<td>'.$langs->trans('Type').'</td>';
+		if (! empty($conf->banque->enabled)) print '<td align="right">'.$langs->trans('BankAccount').'</td>';
+		print '<td align="right">'.$langs->trans('Amount').'</td>';
+		print '<td width="18">&nbsp;</td>';
+		print '</tr>';
+
+		$var=true;
+
+		// Payments already done (from payment on this invoice)
+		$sql = 'SELECT p.datep as dp, p.num_paiement, p.rowid, p.fk_bank,';
+		$sql.= ' c.code as payment_code, c.libelle as payment_label,';
+		$sql.= ' pf.amount,';
+		$sql.= ' ba.rowid as baid, ba.ref, ba.label';
+		$sql.= ' FROM '.MAIN_DB_PREFIX.'c_paiement as c, '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p';
+		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid';
+		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON b.fk_account = ba.rowid';
+		$sql.= ' WHERE pf.fk_facture = '.$object->id.' AND p.fk_paiement = c.id AND pf.fk_paiement = p.rowid';
+		$sql.= ' ORDER BY p.datep, p.tms';
 
-			// Payments already done (from payment on this invoice)
-			$sql = 'SELECT p.datep as dp, p.num_paiement, p.rowid, p.fk_bank,';
-			$sql.= ' c.code as payment_code, c.libelle as payment_label,';
-			$sql.= ' pf.amount,';
-			$sql.= ' ba.rowid as baid, ba.ref, ba.label';
-			$sql.= ' FROM '.MAIN_DB_PREFIX.'c_paiement as c, '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p';
-			$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid';
-			$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON b.fk_account = ba.rowid';
-			$sql.= ' WHERE pf.fk_facture = '.$object->id.' AND p.fk_paiement = c.id AND pf.fk_paiement = p.rowid';
-			$sql.= ' ORDER BY p.datep, p.tms';
+		$result = $db->query($sql);
+		if ($result)
+		{
+			$num = $db->num_rows($result);
+			$i = 0;
 
-			$result = $db->query($sql);
-			if ($result)
+			//if ($object->type != 2)
+			//{
+			if ($num > 0)
 			{
-				$num = $db->num_rows($result);
-				$i = 0;
-
-				//if ($object->type != 2)
-				//{
-				if ($num > 0)
+				while ($i < $num)
 				{
+					$objp = $db->fetch_object($result);
+					$var=!$var;
+					print '<tr '.$bc[$var].'><td>';
+					print '<a href="'.DOL_URL_ROOT.'/compta/paiement/fiche.php?id='.$objp->rowid.'">'.img_object($langs->trans('ShowPayment'),'payment').' ';
+					print dol_print_date($db->jdate($objp->dp),'day').'</a></td>';
+					$label=($langs->trans("PaymentType".$objp->payment_code)!=("PaymentType".$objp->payment_code))?$langs->trans("PaymentType".$objp->payment_code):$objp->payment_label;
+					print '<td>'.$label.' '.$objp->num_paiement.'</td>';
+					if (! empty($conf->banque->enabled))
+					{
+						$bankaccountstatic->id=$objp->baid;
+						$bankaccountstatic->ref=$objp->ref;
+						$bankaccountstatic->label=$objp->ref;
+						print '<td align="right">';
+						if ($bankaccountstatic->id) print $bankaccountstatic->getNomUrl(1,'transactions');
+						print '</td>';
+					}
+					print '<td align="right">'.price($sign * $objp->amount).'</td>';
+					print '<td>&nbsp;</td>';
+					print '</tr>';
+					$i++;
+				}
+			}
+			else
+			{
+				print '<tr '.$bc[$var].'><td colspan="'.$nbcols.'">'.$langs->trans("None").'</td><td></td><td></td></tr>';
+			}
+			//}
+			$db->free($result);
+			}
+			else
+			{
+				dol_print_error($db);
+			}
+
+			if ($object->type != 2)
+			{
+				// Total already paid
+				print '<tr><td colspan="'.$nbcols.'" align="right">';
+				if ($object->type != 3) print $langs->trans('AlreadyPaidNoCreditNotesNoDeposits');
+				else print $langs->trans('AlreadyPaid');
+				print ' :</td><td align="right">'.price($totalpaye).'</td><td>&nbsp;</td></tr>';
+
+				$resteapayeraffiche=$resteapayer;
+
+				// Loop on each credit note or deposit amount applied
+				$creditnoteamount=0;
+				$depositamount=0;
+				$sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
+				$sql.= " re.description, re.fk_facture_source";
+				$sql.= " FROM ".MAIN_DB_PREFIX ."societe_remise_except as re";
+				$sql.= " WHERE fk_facture = ".$object->id;
+				$resql=$db->query($sql);
+				if ($resql)
+				{
+					$num = $db->num_rows($resql);
+					$i = 0;
+					$invoice=new Facture($db);
 					while ($i < $num)
 					{
-						$objp = $db->fetch_object($result);
-						$var=!$var;
-						print '<tr '.$bc[$var].'><td>';
-						print '<a href="'.DOL_URL_ROOT.'/compta/paiement/fiche.php?id='.$objp->rowid.'">'.img_object($langs->trans('ShowPayment'),'payment').' ';
-						print dol_print_date($db->jdate($objp->dp),'day').'</a></td>';
-						$label=($langs->trans("PaymentType".$objp->payment_code)!=("PaymentType".$objp->payment_code))?$langs->trans("PaymentType".$objp->payment_code):$objp->payment_label;
-						print '<td>'.$label.' '.$objp->num_paiement.'</td>';
-						if (! empty($conf->banque->enabled))
-						{
-							$bankaccountstatic->id=$objp->baid;
-							$bankaccountstatic->ref=$objp->ref;
-							$bankaccountstatic->label=$objp->ref;
-							print '<td align="right">';
-							if ($bankaccountstatic->id) print $bankaccountstatic->getNomUrl(1,'transactions');
-							print '</td>';
-						}
-						print '<td align="right">'.price($sign * $objp->amount).'</td>';
-						print '<td>&nbsp;</td>';
-						print '</tr>';
+						$obj = $db->fetch_object($resql);
+						$invoice->fetch($obj->fk_facture_source);
+						print '<tr><td colspan="'.$nbcols.'" align="right">';
+						if ($invoice->type == 2) print $langs->trans("CreditNote").' ';
+						if ($invoice->type == 3) print $langs->trans("Deposit").' ';
+						print $invoice->getNomUrl(0);
+						print ' :</td>';
+						print '<td align="right">'.price($obj->amount_ttc).'</td>';
+						print '<td align="right">';
+						print '<a href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&action=unlinkdiscount&discountid='.$obj->rowid.'">'.img_delete().'</a>';
+						print '</td></tr>';
 						$i++;
+						if ($invoice->type == 2) $creditnoteamount += $obj->amount_ttc;
+						if ($invoice->type == 3) $depositamount += $obj->amount_ttc;
 					}
 				}
 				else
 				{
-					print '<tr '.$bc[$var].'><td colspan="'.$nbcols.'">'.$langs->trans("None").'</td><td></td><td></td></tr>';
+					dol_print_error($db);
 				}
-				//}
-				$db->free($result);
+
+				// Paye partiellement 'escompte'
+				if (($object->statut == 2 || $object->statut == 3) && $object->close_code == 'discount_vat')
+				{
+					print '<tr><td colspan="'.$nbcols.'" align="right" nowrap="1">';
+					print $form->textwithpicto($langs->trans("Discount").':',$langs->trans("HelpEscompte"),-1);
+					print '</td><td align="right">'.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye).'</td><td>&nbsp;</td></tr>';
+					$resteapayeraffiche=0;
 				}
-				else
+				// Paye partiellement ou Abandon 'badcustomer'
+				if (($object->statut == 2 || $object->statut == 3) && $object->close_code == 'badcustomer')
 				{
-					dol_print_error($db);
+					print '<tr><td colspan="'.$nbcols.'" align="right" nowrap="1">';
+					print $form->textwithpicto($langs->trans("Abandoned").':',$langs->trans("HelpAbandonBadCustomer"),-1);
+					print '</td><td align="right">'.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye).'</td><td>&nbsp;</td></tr>';
+					//$resteapayeraffiche=0;
 				}
-
-				if ($object->type != 2)
+				// Paye partiellement ou Abandon 'product_returned'
+				if (($object->statut == 2 || $object->statut == 3) && $object->close_code == 'product_returned')
 				{
-					// Total already paid
-					print '<tr><td colspan="'.$nbcols.'" align="right">';
-					if ($object->type != 3) print $langs->trans('AlreadyPaidNoCreditNotesNoDeposits');
-					else print $langs->trans('AlreadyPaid');
-					print ' :</td><td align="right">'.price($totalpaye).'</td><td>&nbsp;</td></tr>';
-
-					$resteapayeraffiche=$resteapayer;
-
-					// Loop on each credit note or deposit amount applied
-					$creditnoteamount=0;
-					$depositamount=0;
-					$sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
-					$sql.= " re.description, re.fk_facture_source";
-					$sql.= " FROM ".MAIN_DB_PREFIX ."societe_remise_except as re";
-					$sql.= " WHERE fk_facture = ".$object->id;
-					$resql=$db->query($sql);
-					if ($resql)
-					{
-						$num = $db->num_rows($resql);
-						$i = 0;
-						$invoice=new Facture($db);
-						while ($i < $num)
-						{
-							$obj = $db->fetch_object($resql);
-							$invoice->fetch($obj->fk_facture_source);
-							print '<tr><td colspan="'.$nbcols.'" align="right">';
-							if ($invoice->type == 2) print $langs->trans("CreditNote").' ';
-							if ($invoice->type == 3) print $langs->trans("Deposit").' ';
-							print $invoice->getNomUrl(0);
-							print ' :</td>';
-							print '<td align="right">'.price($obj->amount_ttc).'</td>';
-							print '<td align="right">';
-							print '<a href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&action=unlinkdiscount&discountid='.$obj->rowid.'">'.img_delete().'</a>';
-							print '</td></tr>';
-							$i++;
-							if ($invoice->type == 2) $creditnoteamount += $obj->amount_ttc;
-							if ($invoice->type == 3) $depositamount += $obj->amount_ttc;
-						}
-					}
-					else
-					{
-						dol_print_error($db);
-					}
-
-					// Paye partiellement 'escompte'
-					if (($object->statut == 2 || $object->statut == 3) && $object->close_code == 'discount_vat')
-					{
-						print '<tr><td colspan="'.$nbcols.'" align="right" nowrap="1">';
-						print $form->textwithpicto($langs->trans("Discount").':',$langs->trans("HelpEscompte"),-1);
-						print '</td><td align="right">'.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye).'</td><td>&nbsp;</td></tr>';
-						$resteapayeraffiche=0;
-					}
-					// Paye partiellement ou Abandon 'badcustomer'
-					if (($object->statut == 2 || $object->statut == 3) && $object->close_code == 'badcustomer')
-					{
-						print '<tr><td colspan="'.$nbcols.'" align="right" nowrap="1">';
-						print $form->textwithpicto($langs->trans("Abandoned").':',$langs->trans("HelpAbandonBadCustomer"),-1);
-						print '</td><td align="right">'.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye).'</td><td>&nbsp;</td></tr>';
-						//$resteapayeraffiche=0;
-					}
-					// Paye partiellement ou Abandon 'product_returned'
-					if (($object->statut == 2 || $object->statut == 3) && $object->close_code == 'product_returned')
-					{
-						print '<tr><td colspan="'.$nbcols.'" align="right" nowrap="1">';
-						print $form->textwithpicto($langs->trans("ProductReturned").':',$langs->trans("HelpAbandonProductReturned"),-1);
-						print '</td><td align="right">'.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye).'</td><td>&nbsp;</td></tr>';
-						$resteapayeraffiche=0;
-					}
-					// Paye partiellement ou Abandon 'abandon'
-					if (($object->statut == 2 || $object->statut == 3) && $object->close_code == 'abandon')
-					{
-						print '<tr><td colspan="'.$nbcols.'" align="right" nowrap="1">';
-						$text=$langs->trans("HelpAbandonOther");
-						if ($object->close_note) $text.='<br><br><b>'.$langs->trans("Reason").'</b>:'.$object->close_note;
-						print $form->textwithpicto($langs->trans("Abandoned").':',$text,-1);
-						print '</td><td align="right">'.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye).'</td><td>&nbsp;</td></tr>';
-						$resteapayeraffiche=0;
-					}
-
-					// Billed
-					print '<tr><td colspan="'.$nbcols.'" align="right">'.$langs->trans("Billed").' :</td><td align="right" style="border: 1px solid;">'.price($object->total_ttc).'</td><td>&nbsp;</td></tr>';
-
-					// Remainder to pay
-					print '<tr><td colspan="'.$nbcols.'" align="right">';
-					if ($resteapayeraffiche >= 0) print $langs->trans('RemainderToPay');
-					else print $langs->trans('ExcessReceived');
-					print ' :</td>';
-					print '<td align="right" style="border: 1px solid;" bgcolor="#f0f0f0"><b>'.price($resteapayeraffiche).'</b></td>';
-					print '<td nowrap="nowrap">&nbsp;</td></tr>';
+					print '<tr><td colspan="'.$nbcols.'" align="right" nowrap="1">';
+					print $form->textwithpicto($langs->trans("ProductReturned").':',$langs->trans("HelpAbandonProductReturned"),-1);
+					print '</td><td align="right">'.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye).'</td><td>&nbsp;</td></tr>';
+					$resteapayeraffiche=0;
 				}
-				else	// Credit note
+				// Paye partiellement ou Abandon 'abandon'
+				if (($object->statut == 2 || $object->statut == 3) && $object->close_code == 'abandon')
 				{
-					// Total already paid back
-					print '<tr><td colspan="'.$nbcols.'" align="right">';
-					print $langs->trans('AlreadyPaidBack');
-					print ' :</td><td align="right">'.price($sign * $totalpaye).'</td><td>&nbsp;</td></tr>';
-
-					// Billed
-					print '<tr><td colspan="'.$nbcols.'" align="right">'.$langs->trans("Billed").' :</td><td align="right" style="border: 1px solid;">'.price($sign * $object->total_ttc).'</td><td>&nbsp;</td></tr>';
-
-					// Remainder to pay back
-					print '<tr><td colspan="'.$nbcols.'" align="right">';
-					if ($resteapayeraffiche <= 0) print $langs->trans('RemainderToPayBack');
-					else print $langs->trans('ExcessPaydBack');
-					print ' :</td>';
-					print '<td align="right" style="border: 1px solid;" bgcolor="#f0f0f0"><b>'.price($sign * $resteapayeraffiche).'</b></td>';
-					print '<td nowrap="nowrap">&nbsp;</td></tr>';
-
-					// Sold credit note
-					//print '<tr><td colspan="'.$nbcols.'" align="right">'.$langs->trans('TotalTTC').' :</td>';
-					//print '<td align="right" style="border: 1px solid;" bgcolor="#f0f0f0"><b>'.price($sign * $object->total_ttc).'</b></td><td>&nbsp;</td></tr>';
+					print '<tr><td colspan="'.$nbcols.'" align="right" nowrap="1">';
+					$text=$langs->trans("HelpAbandonOther");
+					if ($object->close_note) $text.='<br><br><b>'.$langs->trans("Reason").'</b>:'.$object->close_note;
+					print $form->textwithpicto($langs->trans("Abandoned").':',$text,-1);
+					print '</td><td align="right">'.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye).'</td><td>&nbsp;</td></tr>';
+					$resteapayeraffiche=0;
 				}
 
-				print '</table>';
+				// Billed
+				print '<tr><td colspan="'.$nbcols.'" align="right">'.$langs->trans("Billed").' :</td><td align="right" style="border: 1px solid;">'.price($object->total_ttc).'</td><td>&nbsp;</td></tr>';
 
-				// Margin Infos
-				if (! empty($conf->margin->enabled))
-				{
-			  print '<br>';
-			  $object->displayMarginInfos($object->statut > 0);
-				}
+				// Remainder to pay
+				print '<tr><td colspan="'.$nbcols.'" align="right">';
+				if ($resteapayeraffiche >= 0) print $langs->trans('RemainderToPay');
+				else print $langs->trans('ExcessReceived');
+				print ' :</td>';
+				print '<td align="right" style="border: 1px solid;" bgcolor="#f0f0f0"><b>'.price($resteapayeraffiche).'</b></td>';
+				print '<td nowrap="nowrap">&nbsp;</td></tr>';
+			}
+			else	// Credit note
+			{
+				// Total already paid back
+				print '<tr><td colspan="'.$nbcols.'" align="right">';
+				print $langs->trans('AlreadyPaidBack');
+				print ' :</td><td align="right">'.price($sign * $totalpaye).'</td><td>&nbsp;</td></tr>';
 
-				print '</td></tr>';
+				// Billed
+				print '<tr><td colspan="'.$nbcols.'" align="right">'.$langs->trans("Billed").' :</td><td align="right" style="border: 1px solid;">'.price($sign * $object->total_ttc).'</td><td>&nbsp;</td></tr>';
 
-				// Conditions de reglement
-				print '<tr><td>';
-				print '<table class="nobordernopadding" width="100%"><tr><td>';
-				print $langs->trans('PaymentConditionsShort');
-				print '</td>';
-				if ($object->type != 2 && $action != 'editconditions' && ! empty($object->brouillon) && $user->rights->facture->creer) print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editconditions&amp;facid='.$object->id.'">'.img_edit($langs->trans('SetConditions'),1).'</a></td>';
-				print '</tr></table>';
-				print '</td><td colspan="3">';
-				if ($object->type != 2)
+				// Remainder to pay back
+				print '<tr><td colspan="'.$nbcols.'" align="right">';
+				if ($resteapayeraffiche <= 0) print $langs->trans('RemainderToPayBack');
+				else print $langs->trans('ExcessPaydBack');
+				print ' :</td>';
+				print '<td align="right" style="border: 1px solid;" bgcolor="#f0f0f0"><b>'.price($sign * $resteapayeraffiche).'</b></td>';
+				print '<td nowrap="nowrap">&nbsp;</td></tr>';
+
+				// Sold credit note
+				//print '<tr><td colspan="'.$nbcols.'" align="right">'.$langs->trans('TotalTTC').' :</td>';
+				//print '<td align="right" style="border: 1px solid;" bgcolor="#f0f0f0"><b>'.price($sign * $object->total_ttc).'</b></td><td>&nbsp;</td></tr>';
+			}
+
+			print '</table>';
+
+			// Margin Infos
+			if (! empty($conf->margin->enabled))
+			{
+				print '<br>';
+				$object->displayMarginInfos($object->statut > 0);
+			}
+
+			print '</td></tr>';
+
+			// Conditions de reglement
+			print '<tr><td>';
+			print '<table class="nobordernopadding" width="100%"><tr><td>';
+			print $langs->trans('PaymentConditionsShort');
+			print '</td>';
+			if ($object->type != 2 && $action != 'editconditions' && ! empty($object->brouillon) && $user->rights->facture->creer) print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editconditions&amp;facid='.$object->id.'">'.img_edit($langs->trans('SetConditions'),1).'</a></td>';
+			print '</tr></table>';
+			print '</td><td colspan="3">';
+			if ($object->type != 2)
+			{
+				if ($action == 'editconditions')
 				{
-					if ($action == 'editconditions')
-					{
-						$form->form_conditions_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->cond_reglement_id,'cond_reglement_id');
-					}
-					else
-					{
-						$form->form_conditions_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->cond_reglement_id,'none');
-					}
+					$form->form_conditions_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->cond_reglement_id,'cond_reglement_id');
 				}
 				else
 				{
-					print '&nbsp;';
+					$form->form_conditions_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->cond_reglement_id,'none');
 				}
-				print '</td></tr>';
+			}
+			else
+			{
+				print '&nbsp;';
+			}
+			print '</td></tr>';
 
-				// Date payment term
-				print '<tr><td>';
-				print '<table class="nobordernopadding" width="100%"><tr><td>';
-				print $langs->trans('DateMaxPayment');
-				print '</td>';
-				if ($object->type != 2 && $action != 'editpaymentterm' && ! empty($object->brouillon) && $user->rights->facture->creer) print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editpaymentterm&amp;facid='.$object->id.'">'.img_edit($langs->trans('SetDate'),1).'</a></td>';
-				print '</tr></table>';
-				print '</td><td colspan="3">';
-				if ($object->type != 2)
+			// Date payment term
+			print '<tr><td>';
+			print '<table class="nobordernopadding" width="100%"><tr><td>';
+			print $langs->trans('DateMaxPayment');
+			print '</td>';
+			if ($object->type != 2 && $action != 'editpaymentterm' && ! empty($object->brouillon) && $user->rights->facture->creer) print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editpaymentterm&amp;facid='.$object->id.'">'.img_edit($langs->trans('SetDate'),1).'</a></td>';
+			print '</tr></table>';
+			print '</td><td colspan="3">';
+			if ($object->type != 2)
+			{
+				if ($action == 'editpaymentterm')
 				{
-					if ($action == 'editpaymentterm')
-					{
-						$form->form_date($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->date_lim_reglement,'paymentterm');
-					}
-					else
-					{
-						print dol_print_date($object->date_lim_reglement,'daytext');
-						if ($object->date_lim_reglement < ($now - $conf->facture->client->warning_delay) && ! $object->paye && $object->statut == 1 && ! isset($object->am)) print img_warning($langs->trans('Late'));
-					}
+					$form->form_date($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->date_lim_reglement,'paymentterm');
 				}
 				else
 				{
-					print '&nbsp;';
+					print dol_print_date($object->date_lim_reglement,'daytext');
+					if ($object->date_lim_reglement < ($now - $conf->facture->client->warning_delay) && ! $object->paye && $object->statut == 1 && ! isset($object->am)) print img_warning($langs->trans('Late'));
 				}
-				print '</td></tr>';
+			}
+			else
+			{
+				print '&nbsp;';
+			}
+			print '</td></tr>';
 
-				// Payment mode
+			// Payment mode
+			print '<tr><td>';
+			print '<table class="nobordernopadding" width="100%"><tr><td>';
+			print $langs->trans('PaymentMode');
+			print '</td>';
+			if ($action != 'editmode' && ! empty($object->brouillon) && $user->rights->facture->creer) print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editmode&amp;facid='.$object->id.'">'.img_edit($langs->trans('SetMode'),1).'</a></td>';
+			print '</tr></table>';
+			print '</td><td colspan="3">';
+			if ($action == 'editmode')
+			{
+				$form->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->mode_reglement_id,'mode_reglement_id');
+			}
+			else
+			{
+				$form->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->mode_reglement_id,'none');
+			}
+			print '</td></tr>';
+
+			// Amount
+			print '<tr><td>'.$langs->trans('AmountHT').'</td>';
+			print '<td align="right" colspan="3" nowrap>'.price($object->total_ht,1,'',1,-1,-1,$conf->currency).'</td></tr>';
+			print '<tr><td>'.$langs->trans('AmountVAT').'</td><td align="right" colspan="3" nowrap>'.price($object->total_tva,1,'',1,-1,-1,$conf->currency).'</td></tr>';
+			print '</tr>';
+
+			// Amount Local Taxes
+			if ($mysoc->localtax1_assuj=="1" && $mysoc->useLocalTax(1)) //Localtax1 (example RE)
+			{
+				print '<tr><td>'.$langs->transcountry("AmountLT1",$mysoc->country_code).'</td>';
+				print '<td align="right" colspan="3" nowrap>'.price($object->total_localtax1,1,'',1,-1,-1,$conf->currency).'</td></tr>';
+			}
+			if ($mysoc->localtax2_assuj=="1" && $mysoc->useLocalTax(2)) //Localtax2 (example IRPF)
+			{
+				print '<tr><td>'.$langs->transcountry("AmountLT2",$mysoc->country_code).'</td>';
+				print '<td align="right" colspan="3" nowrap>'.price($object->total_localtax2,1,'',1,-1,-1,$conf->currency).'</td></tr>';
+			}
+
+			// Revenue stamp
+			if ($selleruserevenustamp)		// Test company use revenue stamp
+			{
 				print '<tr><td>';
 				print '<table class="nobordernopadding" width="100%"><tr><td>';
-				print $langs->trans('PaymentMode');
+				print $langs->trans('RevenueStamp');
 				print '</td>';
-				if ($action != 'editmode' && ! empty($object->brouillon) && $user->rights->facture->creer) print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editmode&amp;facid='.$object->id.'">'.img_edit($langs->trans('SetMode'),1).'</a></td>';
+				if ($action != 'editrevenuestamp' && ! empty($object->brouillon) && $user->rights->facture->creer) print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editrevenuestamp&amp;facid='.$object->id.'">'.img_edit($langs->trans('SetRevenuStamp'),1).'</a></td>';
 				print '</tr></table>';
-				print '</td><td colspan="3">';
-				if ($action == 'editmode')
+				print '</td><td colspan="3" align="right">';
+				if ($action == 'editrevenuestamp')
 				{
-					$form->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->mode_reglement_id,'mode_reglement_id');
+					print '<form action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post">';
+					print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
+					print '<input type="hidden" name="action" value="setrevenuestamp">';
+					print $formother->select_revenue_stamp(GETPOST('revenuestamp'), 'revenuestamp', $mysoc->country_code);
+					//print '<input type="text" class="flat" size="4" name="revenuestamp" value="'.price2num($object->revenuestamp).'">';
+					print ' <input type="submit" class="button" value="'.$langs->trans('Modify').'">';
+					print '</form>';
 				}
 				else
 				{
-					$form->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->mode_reglement_id,'none');
+					print price($object->revenuestamp,1,'',1,-1,-1,$conf->currency);
 				}
 				print '</td></tr>';
+			}
 
-				// Amount
-				print '<tr><td>'.$langs->trans('AmountHT').'</td>';
-				print '<td align="right" colspan="3" nowrap>'.price($object->total_ht,1,'',1,-1,-1,$conf->currency).'</td></tr>';
-				print '<tr><td>'.$langs->trans('AmountVAT').'</td><td align="right" colspan="3" nowrap>'.price($object->total_tva,1,'',1,-1,-1,$conf->currency).'</td></tr>';
-				print '</tr>';
+			// Total with tax
+			print '<tr><td>'.$langs->trans('AmountTTC').'</td><td align="right" colspan="3" nowrap>'.price($object->total_ttc,1,'',1,-1,-1,$conf->currency).'</td></tr>';
+
+			// Statut
+			print '<tr><td>'.$langs->trans('Status').'</td>';
+			print '<td align="left" colspan="3">'.($object->getLibStatut(4,$totalpaye)).'</td></tr>';
 
-				// Amount Local Taxes
-				if ($mysoc->localtax1_assuj=="1" && $mysoc->useLocalTax(1)) //Localtax1 (example RE)
+			// Project
+			if (! empty($conf->projet->enabled))
+			{
+				$langs->load('projects');
+				print '<tr>';
+				print '<td>';
+
+				print '<table class="nobordernopadding" width="100%"><tr><td>';
+				print $langs->trans('Project');
+				print '</td>';
+				if ($action != 'classify')
 				{
-					print '<tr><td>'.$langs->transcountry("AmountLT1",$mysoc->country_code).'</td>';
-					print '<td align="right" colspan="3" nowrap>'.price($object->total_localtax1,1,'',1,-1,-1,$conf->currency).'</td></tr>';
+					print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=classify&amp;facid='.$object->id.'">';
+					print img_edit($langs->trans('SetProject'),1);
+					print '</a></td>';
 				}
-				if ($mysoc->localtax2_assuj=="1" && $mysoc->useLocalTax(2)) //Localtax2 (example IRPF)
+				print '</tr></table>';
+
+				print '</td><td colspan="3">';
+				if ($action == 'classify')
+				{
+					$form->form_project($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->socid,$object->fk_project,'projectid');
+				}
+				else
 				{
-					print '<tr><td>'.$langs->transcountry("AmountLT2",$mysoc->country_code).'</td>';
-					print '<td align="right" colspan="3" nowrap>'.price($object->total_localtax2,1,'',1,-1,-1,$conf->currency).'</td></tr>';
+					$form->form_project($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->socid,$object->fk_project,'none');
 				}
+				print '</td>';
+				print '</tr>';
+			}
+
+			// Other attributes
+			$res=$object->fetch_optionals($object->id,$extralabels);
+			$parameters=array('colspan' => ' colspan="2"');
+			$reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook
+			if (empty($reshook) && ! empty($extrafields->attribute_label))
+			{
 
-				// Revenue stamp
-				if ($selleruserevenustamp)		// Test company use revenue stamp
+				if ($action == 'edit_extras')
 				{
-					print '<tr><td>';
-					print '<table class="nobordernopadding" width="100%"><tr><td>';
-					print $langs->trans('RevenueStamp');
-					print '</td>';
-					if ($action != 'editrevenuestamp' && ! empty($object->brouillon) && $user->rights->facture->creer) print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editrevenuestamp&amp;facid='.$object->id.'">'.img_edit($langs->trans('SetRevenuStamp'),1).'</a></td>';
-					print '</tr></table>';
-					print '</td><td colspan="3" align="right">';
-					if ($action == 'editrevenuestamp')
-					{
-						print '<form action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post">';
-						print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
-						print '<input type="hidden" name="action" value="setrevenuestamp">';
-						print $formother->select_revenue_stamp(GETPOST('revenuestamp'), 'revenuestamp', $mysoc->country_code);
-						//print '<input type="text" class="flat" size="4" name="revenuestamp" value="'.price2num($object->revenuestamp).'">';
-						print ' <input type="submit" class="button" value="'.$langs->trans('Modify').'">';
-						print '</form>';
-					}
-					else
-					{
-						print price($object->revenuestamp,1,'',1,-1,-1,$conf->currency);
-					}
-					print '</td></tr>';
+					print '<form enctype="multipart/form-data" action="'.$_SERVER["PHP_SELF"].'" method="post" name="formsoc">';
+					print '<input type="hidden" name="action" value="update_extras">';
+					print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
+					print '<input type="hidden" name="id" value="'.$object->id.'">';
 				}
 
-				// Total with tax
-				print '<tr><td>'.$langs->trans('AmountTTC').'</td><td align="right" colspan="3" nowrap>'.price($object->total_ttc,1,'',1,-1,-1,$conf->currency).'</td></tr>';
-
-				// Statut
-				print '<tr><td>'.$langs->trans('Status').'</td>';
-				print '<td align="left" colspan="3">'.($object->getLibStatut(4,$totalpaye)).'</td></tr>';
-
-				// Project
-				if (! empty($conf->projet->enabled))
+				foreach($extrafields->attribute_label as $key=>$label)
 				{
-					$langs->load('projects');
-					print '<tr>';
-					print '<td>';
-
-					print '<table class="nobordernopadding" width="100%"><tr><td>';
-					print $langs->trans('Project');
-					print '</td>';
-					if ($action != 'classify')
-					{
-						print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=classify&amp;facid='.$object->id.'">';
-						print img_edit($langs->trans('SetProject'),1);
-						print '</a></td>';
-					}
-					print '</tr></table>';
-
-					print '</td><td colspan="3">';
-					if ($action == 'classify')
+					$value=(isset($_POST["options_".$key])?$_POST["options_".$key]:$object->array_options["options_".$key]);
+					if ($extrafields->attribute_type[$key] == 'separate')
 					{
-						$form->form_project($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->socid,$object->fk_project,'projectid');
+						print $extrafields->showSeparator($key);
 					}
 					else
 					{
-						$form->form_project($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->socid,$object->fk_project,'none');
-					}
-					print '</td>';
-					print '</tr>';
-				}
-
-				// Other attributes
-				$res=$object->fetch_optionals($object->id,$extralabels);
-				$parameters=array('colspan' => ' colspan="2"');
-				$reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook
-				if (empty($reshook) && ! empty($extrafields->attribute_label))
-				{
-
-					if ($action == 'edit_extras')
-					{
-						print '<form enctype="multipart/form-data" action="'.$_SERVER["PHP_SELF"].'" method="post" name="formsoc">';
-						print '<input type="hidden" name="action" value="update_extras">';
-						print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
-						print '<input type="hidden" name="id" value="'.$object->id.'">';
-					}
+						print '<tr><td';
+						if (! empty($extrafields->attribute_required[$key])) print ' class="fieldrequired"';
+						print '>'.$label.'</td><td colspan="5">';
+						// Convert date into timestamp format
+						if (in_array($extrafields->attribute_type[$key],array('date','datetime')))
+						{
+							$value = isset($_POST["options_".$key])?dol_mktime($_POST["options_".$key."hour"], $_POST["options_".$key."min"], 0, $_POST["options_".$key."month"], $_POST["options_".$key."day"], $_POST["options_".$key."year"]):$object->array_options['options_'.$key];
+						}
 
-					foreach($extrafields->attribute_label as $key=>$label)
-					{
-						$value=(isset($_POST["options_".$key])?$_POST["options_".$key]:$object->array_options["options_".$key]);
-						if ($extrafields->attribute_type[$key] == 'separate')
+						if ($action == 'edit_extras' && $user->rights->facture->creer)
 						{
-							print $extrafields->showSeparator($key);
+							print $extrafields->showInputField($key,$value);
 						}
 						else
 						{
-							print '<tr><td';
-							if (! empty($extrafields->attribute_required[$key])) print ' class="fieldrequired"';
-							print '>'.$label.'</td><td colspan="5">';
-							// Convert date into timestamp format
-							if (in_array($extrafields->attribute_type[$key],array('date','datetime')))
-							{
-								$value = isset($_POST["options_".$key])?dol_mktime($_POST["options_".$key."hour"], $_POST["options_".$key."min"], 0, $_POST["options_".$key."month"], $_POST["options_".$key."day"], $_POST["options_".$key."year"]):$object->array_options['options_'.$key];
-							}
-
-							if ($action == 'edit_extras' && $user->rights->facture->creer)
-							{
-								print $extrafields->showInputField($key,$value);
-							}
-							else
-							{
-								print $extrafields->showOutputField($key,$value);
-							}
-							print '</td></tr>'."\n";
+							print $extrafields->showOutputField($key,$value);
 						}
+						print '</td></tr>'."\n";
 					}
+				}
 
-					if(count($extrafields->attribute_label) > 0) {
+				if(count($extrafields->attribute_label) > 0) {
 
-						if ($action == 'edit_extras' && $user->rights->facture->creer)
-						{
-							print '<tr><td></td><td colspan="5">';
-							print '<input type="submit" class="button" value="'.$langs->trans('Modify').'">';
-							print '</form>';
-							print '</td></tr>';
+					if ($action == 'edit_extras' && $user->rights->facture->creer)
+					{
+						print '<tr><td></td><td colspan="5">';
+						print '<input type="submit" class="button" value="'.$langs->trans('Modify').'">';
+						print '</form>';
+						print '</td></tr>';
 
-						}
-						else {
-							if ($object->statut == 0 && $user->rights->facture->creer)
-							{
-								print '<tr><td></td><td><a href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=edit_extras">'.img_picto('','edit').' '.$langs->trans('Modify').'</a></td></tr>';
-							}
+					}
+					else {
+						if ($object->statut == 0 && $user->rights->facture->creer)
+						{
+							print '<tr><td></td><td><a href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=edit_extras">'.img_picto('','edit').' '.$langs->trans('Modify').'</a></td></tr>';
 						}
 					}
 				}
+			}
 
-				print '</table><br>';
+			print '</table><br>';
 
-				if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB))
-				{
-					$blocname = 'contacts';
-					$title = $langs->trans('ContactsAddresses');
-					include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
-				}
+			if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB))
+			{
+				$blocname = 'contacts';
+				$title = $langs->trans('ContactsAddresses');
+				include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
+			}
 
-				if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB))
-				{
-					$blocname = 'notes';
-					$title = $langs->trans('Notes');
-					include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
-				}
+			if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB))
+			{
+				$blocname = 'notes';
+				$title = $langs->trans('Notes');
+				include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
+			}
 
-				/*
-				 * Lines
-				*/
-				$result = $object->getLinesArray();
+			/*
+			 * Lines
+			*/
+			$result = $object->getLinesArray();
 
-				if (! empty($conf->use_javascript_ajax) && $object->statut == 0)
-				{
-					include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php';
-				}
+			if (! empty($conf->use_javascript_ajax) && $object->statut == 0)
+			{
+				include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php';
+			}
 
-				print '<table id="tablelines" class="noborder noshadow" width="100%">';
+			print '<table id="tablelines" class="noborder noshadow" width="100%">';
 
-				// Show object lines
-				if (! empty($object->lines))
-					$ret=$object->printObjectLines($action,$mysoc,$soc,$lineid,1);
+			// Show object lines
+			if (! empty($object->lines))
+				$ret=$object->printObjectLines($action,$mysoc,$soc,$lineid,1);
 
-				/*
-				 * Form to add new line
-				*/
-				if ($object->statut == 0 && $user->rights->facture->creer && $action <> 'valid' && $action <> 'editline')
+			/*
+			 * Form to add new line
+			*/
+			if ($object->statut == 0 && $user->rights->facture->creer && $action <> 'valid' && $action <> 'editline')
+			{
+				$var=true;
+
+				if ($conf->global->MAIN_FEATURES_LEVEL > 1)
+				{
+					// Add free or predefined products/services
+					$object->formAddObjectLine(1,$mysoc,$soc);
+				}
+				else
 				{
-					$var=true;
+					// Add free products/services
+					$object->formAddFreeProduct(1,$mysoc,$soc);
 
-					if ($conf->global->MAIN_FEATURES_LEVEL > 1)
-					{
-						// Add free or predefined products/services
-						$object->formAddObjectLine(1,$mysoc,$soc);
-					}
-					else
+					// Add predefined products/services
+					if (! empty($conf->product->enabled) || ! empty($conf->service->enabled))
 					{
-						// Add free products/services
-						$object->formAddFreeProduct(1,$mysoc,$soc);
-
-						// Add predefined products/services
-						if (! empty($conf->product->enabled) || ! empty($conf->service->enabled))
-						{
-							$var=!$var;
-							$object->formAddPredefinedProduct(1,$mysoc,$soc);
-						}
+						$var=!$var;
+						$object->formAddPredefinedProduct(1,$mysoc,$soc);
 					}
-
-					$parameters=array();
-					$reshook=$hookmanager->executeHooks('formAddObjectLine',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
 				}
 
-				print "</table>\n";
+				$parameters=array();
+				$reshook=$hookmanager->executeHooks('formAddObjectLine',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
+			}
 
-				print "</div>\n";
+			print "</table>\n";
 
+			print "</div>\n";
 
-				/*
-				 * Boutons actions
-				*/
 
-				if ($action != 'prerelance' && $action != 'presend')
+			/*
+			 * Boutons actions
+			*/
+
+			if ($action != 'prerelance' && $action != 'presend')
+			{
+				if ($user->societe_id == 0 && $action <> 'valid' && $action <> 'editline')
 				{
-					if ($user->societe_id == 0 && $action <> 'valid' && $action <> 'editline')
+					print '<div class="tabsAction">';
+
+					// Editer une facture deja validee, sans paiement effectue et pas exporte en compta
+					if ($object->statut == 1)
 					{
-						print '<div class="tabsAction">';
+						// On verifie si les lignes de factures ont ete exportees en compta et/ou ventilees
+						$ventilExportCompta = $object->getVentilExportCompta();
 
-						// Editer une facture deja validee, sans paiement effectue et pas exporte en compta
-						if ($object->statut == 1)
+						if ($resteapayer == $object->total_ttc	&& $object->paye == 0 && $ventilExportCompta == 0)
 						{
-							// On verifie si les lignes de factures ont ete exportees en compta et/ou ventilees
-							$ventilExportCompta = $object->getVentilExportCompta();
-
-							if ($resteapayer == $object->total_ttc	&& $object->paye == 0 && $ventilExportCompta == 0)
+							if (! $objectidnext)
 							{
-								if (! $objectidnext)
+								if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->facture->valider) || $user->rights->facture->invoice_advance->unvalidate)
 								{
-									if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->facture->valider) || $user->rights->facture->invoice_advance->unvalidate)
-									{
-										print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=modif">'.$langs->trans('Modify').'</a></div>';
-									}
-									else
-									{
-										print '<div class="inline-block divButAction"><span class="butActionRefused" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans('Modify').'</span></div>';
-									}
+									print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=modif">'.$langs->trans('Modify').'</a></div>';
 								}
 								else
 								{
-									print '<div class="inline-block divButAction"><span class="butActionRefused" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('Modify').'</span></div>';
+									print '<div class="inline-block divButAction"><span class="butActionRefused" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans('Modify').'</span></div>';
 								}
 							}
-						}
-
-						// Reopen a standard paid invoice
-						if (($object->type == 0 || $object->type == 1) && ($object->statut == 2 || $object->statut == 3))				// A paid invoice (partially or completely)
-						{
-							if (! $objectidnext && $object->close_code != 'replaced')	// Not replaced by another invoice
-							{
-								print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=reopen">'.$langs->trans('ReOpen').'</a></div>';
-							}
 							else
 							{
-								print '<div class="inline-block divButAction"><span class="butActionRefused" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('ReOpen').'</span></div>';
+								print '<div class="inline-block divButAction"><span class="butActionRefused" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('Modify').'</span></div>';
 							}
 						}
+					}
 
-						// Validate
-						if ($object->statut == 0 && count($object->lines) > 0 &&
-							(
-								(($object->type == 0 || $object->type == 1 || $object->type == 3 || $object->type == 4) && (! empty($conf->global->FACTURE_ENABLE_NEGATIVE) || $object->total_ttc >= 0))
-								|| ($object->type == 2 && $object->total_ttc <= 0))
-						)
+					// Reopen a standard paid invoice
+					if (($object->type == 0 || $object->type == 1) && ($object->statut == 2 || $object->statut == 3))				// A paid invoice (partially or completely)
+					{
+						if (! $objectidnext && $object->close_code != 'replaced')	// Not replaced by another invoice
 						{
-							if ($user->rights->facture->valider)
-							{
-								print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=valid">'.$langs->trans('Validate').'</a></div>';
-							}
+							print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=reopen">'.$langs->trans('ReOpen').'</a></div>';
+						}
+						else
+						{
+							print '<div class="inline-block divButAction"><span class="butActionRefused" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('ReOpen').'</span></div>';
 						}
+					}
 
-						// Send by mail
-						if (($object->statut == 1 || $object->statut == 2))
+					// Validate
+					if ($object->statut == 0 && count($object->lines) > 0 &&
+						(
+							(($object->type == 0 || $object->type == 1 || $object->type == 3 || $object->type == 4) && (! empty($conf->global->FACTURE_ENABLE_NEGATIVE) || $object->total_ttc >= 0))
+							|| ($object->type == 2 && $object->total_ttc <= 0))
+					)
+					{
+						if ($user->rights->facture->valider)
 						{
-							if ($objectidnext)
-							{
-								print '<div class="inline-block divButAction"><span class="butActionRefused" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('SendByMail').'</span></div>';
-							}
-							else
-							{
-								if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->facture->invoice_advance->send)
-								{
-									print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=presend&amp;mode=init">'.$langs->trans('SendByMail').'</a></div>';
-								}
-								else print '<div class="inline-block divButAction"><a class="butActionRefused" href="#">'.$langs->trans('SendByMail').'</a></div>';
-							}
+							print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=valid">'.$langs->trans('Validate').'</a></div>';
 						}
+					}
 
-						if (! empty($conf->global->FACTURE_SHOW_SEND_REMINDER))	// For backward compatibility
+					// Send by mail
+					if (($object->statut == 1 || $object->statut == 2))
+					{
+						if ($objectidnext)
+						{
+							print '<div class="inline-block divButAction"><span class="butActionRefused" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('SendByMail').'</span></div>';
+						}
+						else
 						{
-							if (($object->statut == 1 || $object->statut == 2) && $resteapayer > 0)
+							if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->facture->invoice_advance->send)
 							{
-								if ($objectidnext)
-								{
-									print '<div class="inline-block divButAction"><span class="butActionRefused" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('SendRemindByMail').'</span></div>';
-								}
-								else
-								{
-									if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->facture->invoice_advance->send)
-									{
-										print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=prerelance&amp;mode=init">'.$langs->trans('SendRemindByMail').'</a></div>';
-									}
-									else print '<div class="inline-block divButAction"><a class="butActionRefused" href="#">'.$langs->trans('SendRemindByMail').'</a></div>';
-								}
+								print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=presend&amp;mode=init">'.$langs->trans('SendByMail').'</a></div>';
 							}
+							else print '<div class="inline-block divButAction"><a class="butActionRefused" href="#">'.$langs->trans('SendByMail').'</a></div>';
 						}
+					}
 
-						// Create payment
-						if ($object->type != 2 && $object->statut == 1 && $object->paye == 0 && $user->rights->facture->paiement)
+					if (! empty($conf->global->FACTURE_SHOW_SEND_REMINDER))	// For backward compatibility
+					{
+						if (($object->statut == 1 || $object->statut == 2) && $resteapayer > 0)
 						{
 							if ($objectidnext)
 							{
-								print '<div class="inline-block divButAction"><span class="butActionRefused" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('DoPayment').'</span></div>';
+								print '<div class="inline-block divButAction"><span class="butActionRefused" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('SendRemindByMail').'</span></div>';
 							}
 							else
 							{
-								if ($resteapayer == 0)
-								{
-									print '<div class="inline-block divButAction"><span class="butActionRefused" title="'.$langs->trans("DisabledBecauseRemainderToPayIsZero").'">'.$langs->trans('DoPayment').'</span></div>';
-								}
-								else
+								if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->facture->invoice_advance->send)
 								{
-									print '<div class="inline-block divButAction"><a class="butAction" href="paiement.php?facid='.$object->id.'&amp;action=create">'.$langs->trans('DoPayment').'</a></div>';
+									print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=prerelance&amp;mode=init">'.$langs->trans('SendRemindByMail').'</a></div>';
 								}
+								else print '<div class="inline-block divButAction"><a class="butActionRefused" href="#">'.$langs->trans('SendRemindByMail').'</a></div>';
 							}
 						}
+					}
 
-						// Reverse back money or convert to reduction
-						if ($object->type == 2 || $object->type == 3)
+					// Create payment
+					if ($object->type != 2 && $object->statut == 1 && $object->paye == 0 && $user->rights->facture->paiement)
+					{
+						if ($objectidnext)
 						{
-							// For credit note only
-							if ($object->type == 2 && $object->statut == 1 && $object->paye == 0 && $user->rights->facture->paiement)
-							{
-								print '<div class="inline-block divButAction"><a class="butAction" href="paiement.php?facid='.$object->id.'&amp;action=create">'.$langs->trans('DoPaymentBack').'</a></div>';
-							}
-							// For credit note
-							if ($object->type == 2 && $object->statut == 1 && $object->paye == 0 && $user->rights->facture->creer && $object->getSommePaiement() == 0)
+							print '<div class="inline-block divButAction"><span class="butActionRefused" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('DoPayment').'</span></div>';
+						}
+						else
+						{
+							if ($resteapayer == 0)
 							{
-								print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=converttoreduc">'.$langs->trans('ConvertToReduc').'</a></div>';
+								print '<div class="inline-block divButAction"><span class="butActionRefused" title="'.$langs->trans("DisabledBecauseRemainderToPayIsZero").'">'.$langs->trans('DoPayment').'</span></div>';
 							}
-							// For deposit invoice
-							if ($object->type == 3 && $object->statut == 1 && $resteapayer == 0 && $user->rights->facture->creer)
+							else
 							{
-								print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=converttoreduc">'.$langs->trans('ConvertToReduc').'</a></div>';
+								print '<div class="inline-block divButAction"><a class="butAction" href="paiement.php?facid='.$object->id.'&amp;action=create">'.$langs->trans('DoPayment').'</a></div>';
 							}
 						}
+					}
 
-						// Classify paid (if not deposit and not credit note. Such invoice are "converted")
-						if ($object->statut == 1 && $object->paye == 0 && $user->rights->facture->paiement &&
-							(($object->type != 2 && $object->type != 3 && $resteapayer <= 0) || ($object->type == 2 && $resteapayer >= 0)) )
+					// Reverse back money or convert to reduction
+					if ($object->type == 2 || $object->type == 3)
+					{
+						// For credit note only
+						if ($object->type == 2 && $object->statut == 1 && $object->paye == 0 && $user->rights->facture->paiement)
 						{
-							print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=paid">'.$langs->trans('ClassifyPaid').'</a></div>';
+							print '<div class="inline-block divButAction"><a class="butAction" href="paiement.php?facid='.$object->id.'&amp;action=create">'.$langs->trans('DoPaymentBack').'</a></div>';
 						}
+						// For credit note
+						if ($object->type == 2 && $object->statut == 1 && $object->paye == 0 && $user->rights->facture->creer && $object->getSommePaiement() == 0)
+						{
+							print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=converttoreduc">'.$langs->trans('ConvertToReduc').'</a></div>';
+						}
+						// For deposit invoice
+						if ($object->type == 3 && $object->statut == 1 && $resteapayer == 0 && $user->rights->facture->creer)
+						{
+							print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=converttoreduc">'.$langs->trans('ConvertToReduc').'</a></div>';
+						}
+					}
+
+					// Classify paid (if not deposit and not credit note. Such invoice are "converted")
+					if ($object->statut == 1 && $object->paye == 0 && $user->rights->facture->paiement &&
+						(($object->type != 2 && $object->type != 3 && $resteapayer <= 0) || ($object->type == 2 && $resteapayer >= 0)) )
+					{
+						print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=paid">'.$langs->trans('ClassifyPaid').'</a></div>';
+					}
 
-						// Classify 'closed not completely paid' (possible si validee et pas encore classee payee)
-						if ($object->statut == 1 && $object->paye == 0 && $resteapayer > 0
-							&& $user->rights->facture->paiement)
+					// Classify 'closed not completely paid' (possible si validee et pas encore classee payee)
+					if ($object->statut == 1 && $object->paye == 0 && $resteapayer > 0
+						&& $user->rights->facture->paiement)
+					{
+						if ($totalpaye > 0 || $totalcreditnotes > 0)
+						{
+							// If one payment or one credit note was linked to this invoice
+							print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=paid">'.$langs->trans('ClassifyPaidPartially').'</a></div>';
+						}
+						else
 						{
-							if ($totalpaye > 0 || $totalcreditnotes > 0)
+							if ($objectidnext)
 							{
-								// If one payment or one credit note was linked to this invoice
-								print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=paid">'.$langs->trans('ClassifyPaidPartially').'</a></div>';
+								print '<div class="inline-block divButAction"><span class="butActionRefused" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('ClassifyCanceled').'</span></div>';
 							}
 							else
 							{
-								if ($objectidnext)
-								{
-									print '<div class="inline-block divButAction"><span class="butActionRefused" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('ClassifyCanceled').'</span></div>';
-								}
-								else
-								{
-									print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=canceled">'.$langs->trans('ClassifyCanceled').'</a></div>';
-								}
+								print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=canceled">'.$langs->trans('ClassifyCanceled').'</a></div>';
 							}
 						}
+					}
+
+					// Clone
+					if (($object->type == 0 || $object->type == 3 || $object->type == 4) && $user->rights->facture->creer)
+					{
+						print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=clone&amp;object=invoice">'.$langs->trans("ToClone").'</a></div>';
+					}
 
-						// Clone
-						if (($object->type == 0 || $object->type == 3 || $object->type == 4) && $user->rights->facture->creer)
+					// Clone as predefined
+					if (($object->type == 0 || $object->type == 3 || $object->type == 4) && $object->statut == 0 && $user->rights->facture->creer)
+					{
+						if (! $objectidnext)
 						{
-							print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=clone&amp;object=invoice">'.$langs->trans("ToClone").'</a></div>';
+							print '<div class="inline-block divButAction"><a class="butAction" href="facture/fiche-rec.php?facid='.$object->id.'&amp;action=create">'.$langs->trans("ChangeIntoRepeatableInvoice").'</a></div>';
 						}
+					}
 
-						// Clone as predefined
-						if (($object->type == 0 || $object->type == 3 || $object->type == 4) && $object->statut == 0 && $user->rights->facture->creer)
+					// Delete
+					if ($user->rights->facture->supprimer)
+					{
+						if (! $object->is_erasable())
 						{
-							if (! $objectidnext)
-							{
-								print '<div class="inline-block divButAction"><a class="butAction" href="facture/fiche-rec.php?facid='.$object->id.'&amp;action=create">'.$langs->trans("ChangeIntoRepeatableInvoice").'</a></div>';
-							}
+							print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="'.$langs->trans("DisabledBecauseNotErasable").'">'.$langs->trans('Delete').'</a></div>';
 						}
-
-						// Delete
-						if ($user->rights->facture->supprimer)
+						else if ($objectidnext)
 						{
-							if (! $object->is_erasable())
-							{
-								print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="'.$langs->trans("DisabledBecauseNotErasable").'">'.$langs->trans('Delete').'</a></div>';
-							}
-							else if ($objectidnext)
-							{
-								print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('Delete').'</a></div>';
-							}
-							elseif ($object->getSommePaiement())
-							{
-								print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="'.$langs->trans("DisabledBecausePayments").'">'.$langs->trans('Delete').'</a></div>';
-							}
-							else
-							{
-								print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=delete">'.$langs->trans('Delete').'</a></div>';
-							}
+							print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('Delete').'</a></div>';
+						}
+						elseif ($object->getSommePaiement())
+						{
+							print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="'.$langs->trans("DisabledBecausePayments").'">'.$langs->trans('Delete').'</a></div>';
 						}
 						else
 						{
-							print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="'.$langs->trans("NotAllowed").'">'.$langs->trans('Delete').'</a></div>';
+							print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=delete">'.$langs->trans('Delete').'</a></div>';
 						}
-
-						print '</div>';
 					}
-				}
-				print '<br>';
-
-				if ($action != 'prerelance' && $action != 'presend')
-				{
-					print '<div class="fichecenter"><div class="fichehalfleft">';
-					//print '<table width="100%"><tr><td width="50%" valign="top">';
-					//print '<a name="builddoc"></a>'; // ancre
-
-					/*
-					 * Documents generes
-					*/
-					$filename=dol_sanitizeFileName($object->ref);
-					$filedir=$conf->facture->dir_output . '/' . dol_sanitizeFileName($object->ref);
-					$urlsource=$_SERVER['PHP_SELF'].'?facid='.$object->id;
-					$genallowed=$user->rights->facture->creer;
-					$delallowed=$user->rights->facture->supprimer;
-
-					print $formfile->showdocuments('facture',$filename,$filedir,$urlsource,$genallowed,$delallowed,$object->modelpdf,1,0,0,28,0,'','','',$soc->default_lang);
-					$somethingshown=$formfile->numoffiles;
-
-					/*
-					 * Linked object block
-					*/
-					$somethingshown=$object->showLinkedObjectBlock();
-
-					// Link for paypal payment
-					if (! empty($conf->paypal->enabled) && $object->statut != 0)
+					else
 					{
-						include_once DOL_DOCUMENT_ROOT.'/paypal/lib/paypal.lib.php';
-						print showPaypalPaymentUrl('invoice',$object->ref);
+						print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="'.$langs->trans("NotAllowed").'">'.$langs->trans('Delete').'</a></div>';
 					}
 
-					print '</div><div class="fichehalfright"><div class="ficheaddleft">';
-					//print '</td><td valign="top" width="50%">';
+					print '</div>';
+				}
+			}
+			print '<br>';
+
+			if ($action != 'prerelance' && $action != 'presend')
+			{
+				print '<div class="fichecenter"><div class="fichehalfleft">';
+				//print '<table width="100%"><tr><td width="50%" valign="top">';
+				//print '<a name="builddoc"></a>'; // ancre
+
+				/*
+				 * Documents generes
+				*/
+				$filename=dol_sanitizeFileName($object->ref);
+				$filedir=$conf->facture->dir_output . '/' . dol_sanitizeFileName($object->ref);
+				$urlsource=$_SERVER['PHP_SELF'].'?facid='.$object->id;
+				$genallowed=$user->rights->facture->creer;
+				$delallowed=$user->rights->facture->supprimer;
 
-					// List of actions on element
-					include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
-					$formactions=new FormActions($db);
-					$somethingshown=$formactions->showactions($object,'invoice',$socid);
+				print $formfile->showdocuments('facture',$filename,$filedir,$urlsource,$genallowed,$delallowed,$object->modelpdf,1,0,0,28,0,'','','',$soc->default_lang);
+				$somethingshown=$formfile->numoffiles;
 
-					//print '</td></tr></table>';
-					print '</div></div></div>';
+				/*
+				 * Linked object block
+				*/
+				$somethingshown=$object->showLinkedObjectBlock();
+
+				// Link for paypal payment
+				if (! empty($conf->paypal->enabled) && $object->statut != 0)
+				{
+					include_once DOL_DOCUMENT_ROOT.'/paypal/lib/paypal.lib.php';
+					print showPaypalPaymentUrl('invoice',$object->ref);
 				}
-				else
+
+				print '</div><div class="fichehalfright"><div class="ficheaddleft">';
+				//print '</td><td valign="top" width="50%">';
+
+				// List of actions on element
+				include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
+				$formactions=new FormActions($db);
+				$somethingshown=$formactions->showactions($object,'invoice',$socid);
+
+				//print '</td></tr></table>';
+				print '</div></div></div>';
+			}
+			else
+			{
+				/*
+				 * Affiche formulaire mail
+				*/
+
+				// By default if $action=='presend'
+				$titreform='SendBillByMail';
+				$topicmail='SendBillRef';
+				$action='send';
+				$modelmail='facture_send';
+
+				if ($action == 'prerelance')	// For backward compatibility
 				{
-					/*
-					 * Affiche formulaire mail
-					*/
+					$titrefrom='SendReminderBillByMail';
+					$topicmail='SendReminderBillRef';
+					$action='relance';
+					$modelmail='facture_relance';
+				}
 
-					// By default if $action=='presend'
-					$titreform='SendBillByMail';
-					$topicmail='SendBillRef';
-					$action='send';
-					$modelmail='facture_send';
+				$ref = dol_sanitizeFileName($object->ref);
+				include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+				$fileparams = dol_most_recent_file($conf->facture->dir_output . '/' . $ref, preg_quote($ref,'/'));
+				$file=$fileparams['fullname'];
 
-					if ($action == 'prerelance')	// For backward compatibility
+				// Build document if it not exists
+				if (! $file || ! is_readable($file))
+				{
+					// Define output language
+					$outputlangs = $langs;
+					$newlang='';
+					if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) $newlang=$_REQUEST['lang_id'];
+					if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$object->client->default_lang;
+					if (! empty($newlang))
 					{
-						$titrefrom='SendReminderBillByMail';
-						$topicmail='SendReminderBillRef';
-						$action='relance';
-						$modelmail='facture_relance';
+						$outputlangs = new Translate("",$conf);
+						$outputlangs->setDefaultLang($newlang);
 					}
 
-					$ref = dol_sanitizeFileName($object->ref);
-					include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+					$result=facture_pdf_create($db, $object, GETPOST('model')?GETPOST('model'):$object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
+					if ($result <= 0)
+					{
+						dol_print_error($db,$result);
+						exit;
+					}
 					$fileparams = dol_most_recent_file($conf->facture->dir_output . '/' . $ref, preg_quote($ref,'/'));
 					$file=$fileparams['fullname'];
+				}
 
-					// Build document if it not exists
-					if (! $file || ! is_readable($file))
-					{
-						// Define output language
-						$outputlangs = $langs;
-						$newlang='';
-						if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) $newlang=$_REQUEST['lang_id'];
-						if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$object->client->default_lang;
-						if (! empty($newlang))
-						{
-							$outputlangs = new Translate("",$conf);
-							$outputlangs->setDefaultLang($newlang);
-						}
-
-						$result=facture_pdf_create($db, $object, GETPOST('model')?GETPOST('model'):$object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
-						if ($result <= 0)
-						{
-							dol_print_error($db,$result);
-							exit;
+				print '<br>';
+				print_titre($langs->trans($titreform));
+
+				// Cree l'objet formulaire mail
+				include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
+				$formmail = new FormMail($db);
+				$formmail->fromtype = 'user';
+				$formmail->fromid   = $user->id;
+				$formmail->fromname = $user->getFullName($langs);
+				$formmail->frommail = $user->email;
+				$formmail->withfrom=1;
+				$liste=array();
+				foreach ($object->thirdparty->thirdparty_and_contact_email_array(1) as $key=>$value)	$liste[$key]=$value;
+				$formmail->withto=GETPOST('sendto')?GETPOST('sendto'):$liste;
+				$formmail->withtocc=$liste;
+				$formmail->withtoccc=$conf->global->MAIN_EMAIL_USECCC;
+				$formmail->withtopic=$langs->transnoentities($topicmail,'__FACREF__');
+				$formmail->withfile=2;
+				$formmail->withbody=1;
+				$formmail->withdeliveryreceipt=1;
+				$formmail->withcancel=1;
+				// Tableau des substitutions
+				$formmail->substit['__FACREF__']=$object->ref;
+				$formmail->substit['__SIGNATURE__']=$user->signature;
+				$formmail->substit['__PERSONALIZED__']='';
+				$formmail->substit['__CONTACTCIVNAME__']='';
+
+				//Find the good contact adress
+				$custcontact='';
+				$contactarr=array();
+				$contactarr=$object->liste_contact(-1,'external');
+
+				if (is_array($contactarr) && count($contactarr)>0) {
+					foreach($contactarr as $contact) {
+						if ($contact['libelle']==$langs->trans('TypeContact_facture_external_BILLING')) {
+
+							require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
+
+							$contactstatic=new Contact($db);
+							$contactstatic->fetch($contact['id']);
+							$custcontact=$contactstatic->getFullName($langs,1);
 						}
-						$fileparams = dol_most_recent_file($conf->facture->dir_output . '/' . $ref, preg_quote($ref,'/'));
-						$file=$fileparams['fullname'];
 					}
 
-					print '<br>';
-					print_titre($langs->trans($titreform));
-
-					// Cree l'objet formulaire mail
-					include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
-					$formmail = new FormMail($db);
-					$formmail->fromtype = 'user';
-					$formmail->fromid   = $user->id;
-					$formmail->fromname = $user->getFullName($langs);
-					$formmail->frommail = $user->email;
-					$formmail->withfrom=1;
-					$liste=array();
-					foreach ($object->thirdparty->thirdparty_and_contact_email_array(1) as $key=>$value)	$liste[$key]=$value;
-					$formmail->withto=GETPOST('sendto')?GETPOST('sendto'):$liste;
-					$formmail->withtocc=$liste;
-					$formmail->withtoccc=$conf->global->MAIN_EMAIL_USECCC;
-					$formmail->withtopic=$langs->transnoentities($topicmail,'__FACREF__');
-					$formmail->withfile=2;
-					$formmail->withbody=1;
-					$formmail->withdeliveryreceipt=1;
-					$formmail->withcancel=1;
-					// Tableau des substitutions
-					$formmail->substit['__FACREF__']=$object->ref;
-					$formmail->substit['__SIGNATURE__']=$user->signature;
-					$formmail->substit['__PERSONALIZED__']='';
-					$formmail->substit['__CONTACTCIVNAME__']='';
-
-					//Find the good contact adress
-					$custcontact='';
-					$contactarr=array();
-					$contactarr=$object->liste_contact(-1,'external');
-
-					if (is_array($contactarr) && count($contactarr)>0) {
-						foreach($contactarr as $contact) {
-							if ($contact['libelle']==$langs->trans('TypeContact_facture_external_BILLING')) {
-
-								require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
-
-								$contactstatic=new Contact($db);
-								$contactstatic->fetch($contact['id']);
-								$custcontact=$contactstatic->getFullName($langs,1);
-							}
-						}
-
-						if (!empty($custcontact)) {
-							$formmail->substit['__CONTACTCIVNAME__']=$custcontact;
-						}
+					if (!empty($custcontact)) {
+						$formmail->substit['__CONTACTCIVNAME__']=$custcontact;
 					}
+				}
 
 
-					// Tableau des parametres complementaires du post
-					$formmail->param['action']=$action;
-					$formmail->param['models']=$modelmail;
-					$formmail->param['facid']=$object->id;
-					$formmail->param['returnurl']=$_SERVER["PHP_SELF"].'?id='.$object->id;
+				// Tableau des parametres complementaires du post
+				$formmail->param['action']=$action;
+				$formmail->param['models']=$modelmail;
+				$formmail->param['facid']=$object->id;
+				$formmail->param['returnurl']=$_SERVER["PHP_SELF"].'?id='.$object->id;
 
-					// Init list of files
-					if (GETPOST("mode")=='init')
-					{
-						$formmail->clear_attached_files();
-						$formmail->add_attached_files($file,basename($file),dol_mimetype($file));
-					}
+				// Init list of files
+				if (GETPOST("mode")=='init')
+				{
+					$formmail->clear_attached_files();
+					$formmail->add_attached_files($file,basename($file),dol_mimetype($file));
+				}
 
-					$formmail->show_form();
+				$formmail->show_form();
 
-					print '<br>';
-				}
-		}
-		else
-		{
-			dol_print_error($db,$object->error);
-		}
+				print '<br>';
+			}
 	}
+	else
+	{
+		dol_print_error($db,$object->error);
+	}
+}
 
-	dol_htmloutput_mesg('',$mesgs);
+dol_htmloutput_mesg('',$mesgs);
 
-	llxFooter();
-	$db->close();
-	?>
+llxFooter();
+$db->close();
+?>
diff --git a/htdocs/compta/journal/purchasesjournal.php b/htdocs/compta/journal/purchasesjournal.php
index a37d5c240dfddbb86727841db26885bbe340e17d..2269c0035b9e44278cd07c807c48ad769fbea705 100755
--- a/htdocs/compta/journal/purchasesjournal.php
+++ b/htdocs/compta/journal/purchasesjournal.php
@@ -3,7 +3,8 @@
  * Copyright (C) 2007-2010	Jean Heimburger		<jean@tiaris.info>
  * Copyright (C) 2011		Juanjo Menent		<jmenent@2byte.es>
  * Copyright (C) 2012		Regis Houssin		<regis.houssin@capnetworks.com>
- * Copyright (C) 2011-2012 Alexandre Spangaro	  <alexandre.spangaro@gmail.com>
+ * Copyright (C) 2011-2012	Alexandre spangaro	<alexandre.spangaro@gmail.com>
+ * Copyright (C) 2013		Marcos García		<marcosgdf@gmail.com>
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -99,12 +100,9 @@ $sql = "SELECT f.rowid, f.ref_supplier, f.type, f.datef, f.libelle,";
 $sql.= " fd.total_ttc, fd.tva_tx, fd.total_ht, fd.tva as total_tva, fd.product_type, fd.localtax1_tx, fd.localtax2_tx, fd.total_localtax1, fd.total_localtax2,";
 $sql.= " s.rowid as socid, s.nom as name, s.code_compta_fournisseur,";
 $sql.= " p.rowid as pid, p.ref as ref, p.accountancy_code_buy,";
-$sql.= " ct.accountancy_code_buy as account_tva, ct.recuperableonly,";
-$sql.= " ctl1.accountancy_code_buy as account_localtax1, ctl2.accountancy_code_buy as account_localtax2";
+$sql.= " ct.accountancy_code_buy as account_tva, ct.recuperableonly";
 $sql.= " FROM ".MAIN_DB_PREFIX."facture_fourn_det fd";
 $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_tva ct ON fd.tva_tx = ct.taux AND fd.info_bits = ct.recuperableonly AND ct.fk_pays = '".$idpays."'";
-$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_tva ctl1 ON fd.localtax1_tx = ctl1.localtax1 AND ctl1.fk_pays = '".$idpays."'";
-$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_tva ctl2 ON fd.localtax2_tx = ctl2.localtax2 AND ctl2.fk_pays = '".$idpays."'";
 $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product p ON p.rowid = fd.fk_product";
 $sql.= " JOIN ".MAIN_DB_PREFIX."facture_fourn f ON f.rowid = fd.fk_facture_fourn";
 $sql.= " JOIN ".MAIN_DB_PREFIX."societe s ON s.rowid = f.fk_soc" ;
@@ -145,6 +143,11 @@ if ($result)
 		$compta_localtax1 = (! empty($obj->account_localtax1)?$obj->account_localtax1:$langs->trans("CodeNotDef"));
 		$compta_localtax2 = (! empty($obj->account_localtax2)?$obj->account_localtax2:$langs->trans("CodeNotDef"));
 
+		$account_localtax1=getLocalTaxesFromRate($obj->tva_tx, 1, $mysoc);
+		$compta_localtax1= (! empty($account_localtax1[2])?$account_localtax1[2]:$langs->trans("CodeNotDef"));
+		$account_localtax2=getLocalTaxesFromRate($obj->tva_tx, 2, $mysoc);
+		$compta_localtax2= (! empty($account_localtax2[2])?$account_localtax2[2]:$langs->trans("CodeNotDef"));
+		
 		$tabfac[$obj->rowid]["date"] = $obj->datef;
 		$tabfac[$obj->rowid]["ref"] = $obj->ref_supplier;
 		$tabfac[$obj->rowid]["type"] = $obj->type;
@@ -166,7 +169,6 @@ else {
 /*
  * Show result array
  */
-$i = 0;
 print "<table class=\"noborder\" width=\"100%\">";
 print "<tr class=\"liste_titre\">";
 ///print "<td>".$langs->trans("JournalNum")."</td>";
@@ -177,96 +179,71 @@ print "<td>".$langs->trans("Type")."</td><td align='right'>".$langs->trans("Debi
 print "</tr>\n";
 
 $var=true;
-$r='';
 
 $invoicestatic=new FactureFournisseur($db);
 $companystatic=new Fournisseur($db);
 
 foreach ($tabfac as $key => $val)
 {
-	$invoicestatic->id=$key;
-	$invoicestatic->ref=$val["ref"];
-	$invoicestatic->type=$val["type"];
-
-	// product
-	foreach ($tabht[$key] as $k => $mt)
-	{
-		if ($mt)
-		{
-			print "<tr ".$bc[$var]." >";
-			//print "<td>".$conf->global->COMPTA_JOURNAL_BUY."</td>";
-			print "<td>".$val["date"]."</td>";
-			print "<td>".$invoicestatic->getNomUrl(1)."</td>";
-			print "<td>".$k."</td><td>".$langs->trans("Products")."</td>";
-			print '<td align="right">'.($mt>=0?price($mt):'')."</td>";
-			print '<td align="right">'.($mt<0?price(-$mt):'')."</td>";
-			print "</tr>";
-		}
-	}
-	// vat
-	foreach ($tabtva[$key] as $k => $mt)
+	$invoicestatic->id = $key;
+	$invoicestatic->ref = $val["ref"];
+	$invoicestatic->type = $val["type"];
+
+	$companystatic->id = $tabcompany[$key]['id'];
+	$companystatic->name = $tabcompany[$key]['name'];
+
+	$lines = array(
+		array(
+			'var' => $tabht[$key],
+			'label' => $langs->trans('Products'),
+		),
+		array(
+			'var' => $tabtva[$key],
+			'label' => $langs->trans('VAT')
+		),
+		array(
+			'var' => $tablocaltax1[$key],
+			'label' => $langs->transcountry('LT1', $mysoc->country_code)
+		),
+		array(
+			'var' => $tablocaltax2[$key],
+			'label' => $langs->transcountry('LT2', $mysoc->country_code)
+		),
+		array(
+			'var' => $tabttc[$key],
+			'label' => $langs->trans('ThirdParty').' ('.$companystatic->getNomUrl(0, 'supplier', 16).')',
+			'nomtcheck' => true,
+			'inv' => true
+		)
+	);
+
+	foreach ($lines as $line)
 	{
-		if ($mt)
+		foreach ($line['var'] as $k => $mt)
 		{
-			print "<tr ".$bc[$var]." >";
-			//print "<td>".$conf->global->COMPTA_JOURNAL_BUY."</td>";
-			print "<td>".$val["date"]."</td>";
-			print "<td>".$invoicestatic->getNomUrl(1)."</td>";
-			print "<td>".$k."</td><td>".$langs->trans("VAT")."</td>";
-			print '<td align="right">'.($mt>=0?price($mt):'')."</td>";
-			print '<td align="right">'.($mt<0?price(-$mt):'')."</td>";
-			print "</tr>";
+			if (isset($line['nomtcheck']) || $mt)
+			{
+				print "<tr ".$bc[$var]." >";
+				//print "<td>".$conf->global->COMPTA_JOURNAL_BUY."</td>";
+				print "<td>".$val["date"]."</td>";
+				print "<td>".$invoicestatic->getNomUrl(1)."</td>";
+				print "<td>".$k."</td><td>".$line['label']."</td>";
+
+				if (isset($line['inv']))
+				{
+					print '<td align="right">'.($mt<0?price(-$mt):'')."</td>";
+	    			print '<td align="right">'.($mt>=0?price($mt):'')."</td>";
+				}
+				else
+				{
+					print '<td align="right">'.($mt>=0?price($mt):'')."</td>";
+					print '<td align="right">'.($mt<0?price(-$mt):'')."</td>";
+				}
+				
+				print "</tr>";
+			}
 		}
 	}
-	// localtax1
-	foreach ($tablocaltax1[$key] as $k => $mt)
-	{
-	    if ($mt)
-	    {
-    		print "<tr ".$bc[$var].">";
-    		//print "<td>".$conf->global->COMPTA_JOURNAL_BUY."</td>";
-    		print "<td>".$val["date"]."</td>";
-    		print "<td>".$invoicestatic->getNomUrl(1)."</td>";
-    		print "<td>".$k."</td><td>".$langs->transcountrynoentities("LT1",$mysoc->country_code)."</td>";
-    		print "<td align='right'>".($mt>=0?price($mt):'')."</td>";
-    		print "<td align='right'>".($mt<0?price(-$mt):'')."</td>";
-    		print "</tr>";
-	    }
-	}
-	// localtax2
-	foreach ($tablocaltax2[$key] as $k => $mt)
-	{
-	    if ($mt)
-	    {
-    		print "<tr ".$bc[$var].">";
-    		//print "<td>".$conf->global->COMPTA_JOURNAL_BUY."</td>";
-    		print "<td>".$val["date"]."</td>";
-    		print "<td>".$invoicestatic->getNomUrl(1)."</td>";
-    		print "<td>".$k."</td><td>".$langs->transcountrynoentities("LT2",$mysoc->country_code)."</td>";
-    		print "<td align='right'>".($mt>=0?price($mt):'')."</td>";
-    		print "<td align='right'>".($mt<0?price(-$mt):'')."</td>";
-    		print "</tr>";
-	    }
-	}
-	print "<tr ".$bc[$var].">";
-	// third party
-	//print "<td>".$conf->global->COMPTA_JOURNAL_BUY."</td>";
-	print "<td>".$val["date"]."</td>";
-	print "<td>".$invoicestatic->getNomUrl(1)."</td>";
-
-	foreach ($tabttc[$key] as $k => $mt)
-	{
-    	$companystatic->id=$tabcompany[$key]['id'];
-    	$companystatic->name=$tabcompany[$key]['name'];
-
-    	print "<td>".$k;
-	    print "</td><td>".$langs->trans("ThirdParty");
-		print ' ('.$companystatic->getNomUrl(0,'supplier',16).')';
-	    print "</td>";
-	    print '<td align="right">'.($mt<0?price(-$mt):'')."</td>";
-	    print '<td align="right">'.($mt>=0?price($mt):'')."</td>";
-	}
-	print "</tr>";
 
 	$var = !$var;
 }
diff --git a/htdocs/compta/journal/sellsjournal.php b/htdocs/compta/journal/sellsjournal.php
index ddb12839bf4dd409b110abc1c10e6fec5ba006aa..859c1ff2ea51a16bf5772508deee8d8439651640 100755
--- a/htdocs/compta/journal/sellsjournal.php
+++ b/htdocs/compta/journal/sellsjournal.php
@@ -3,8 +3,8 @@
  * Copyright (C) 2007-2010	Jean Heimburger		<jean@tiaris.info>
  * Copyright (C) 2011		Juanjo Menent		<jmenent@2byte.es>
  * Copyright (C) 2012		Regis Houssin		<regis.houssin@capnetworks.com>
- * Copyright (C) 2011-2012 Alexandre Spangaro	  <alexandre.spangaro@gmail.com>
- * Copyright (C) 2013       Marcos García <marcosgdf@gmail.com>
+ * Copyright (C) 2011-2012  Alexandre Spangaro	<alexandre.spangaro@gmail.com>
+ * Copyright (C) 2013		Marcos García		<marcosgdf@gmail.com>
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -102,15 +102,12 @@ $sql = "SELECT f.rowid, f.facnumber, f.type, f.datef, f.ref_client,";
 $sql.= " fd.product_type, fd.total_ht, fd.total_tva, fd.tva_tx, fd.total_ttc, fd.localtax1_tx, fd.localtax2_tx, fd.total_localtax1, fd.total_localtax2,";
 $sql.= " s.rowid as socid, s.nom as name, s.code_compta, s.client,";
 $sql.= " p.rowid as pid, p.ref as pref, p.accountancy_code_sell,";
-$sql.= " ct.accountancy_code_sell as account_tva, ct.recuperableonly,";
-$sql.= " ctl1.accountancy_code_sell as account_localtax1, ctl2.accountancy_code_sell as account_localtax2";
+$sql.= " ct.accountancy_code_sell as account_tva, ct.recuperableonly";
 $sql.= " FROM ".MAIN_DB_PREFIX."facturedet fd";
 $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product p ON p.rowid = fd.fk_product";
 $sql.= " JOIN ".MAIN_DB_PREFIX."facture f ON f.rowid = fd.fk_facture";
 $sql.= " JOIN ".MAIN_DB_PREFIX."societe s ON s.rowid = f.fk_soc";
 $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_tva ct ON fd.tva_tx = ct.taux AND fd.info_bits = ct.recuperableonly AND ct.fk_pays = '".$idpays."'";
-$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_tva ctl1 ON fd.localtax1_tx = ctl1.localtax1 AND ctl1.fk_pays = '".$idpays."'";
-$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_tva ctl2 ON fd.localtax2_tx = ctl2.localtax2 AND ctl2.fk_pays = '".$idpays."'";
 $sql.= " WHERE f.entity = ".$conf->entity;
 $sql.= " AND f.fk_statut > 0";
 if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql.= " AND f.type IN (0,1,2)";
@@ -129,6 +126,8 @@ if ($result)
 	$tablocaltax2 = array();
 	$tabttc = array();
 	$tabcompany = array();
+	$account_localtax1=0;
+	$account_localtax2=0;
 
 	$num = $db->num_rows($result);
    	$i=0;
@@ -147,9 +146,12 @@ if ($result)
 		}
 		$cpttva = (! empty($conf->global->COMPTA_VAT_ACCOUNT)?$conf->global->COMPTA_VAT_ACCOUNT:$langs->trans("CodeNotDef"));
 		$compta_tva = (! empty($obj->account_tva)?$obj->account_tva:$cpttva);
-		$compta_localtax1 = (! empty($obj->account_localtax1)?$obj->account_localtax1:$langs->trans("CodeNotDef"));
-		$compta_localtax2 = (! empty($obj->account_localtax2)?$obj->account_localtax2:$langs->trans("CodeNotDef"));
 
+		$account_localtax1=getLocalTaxesFromRate($obj->tva_tx, 1, $mysoc);
+		$compta_localtax1= (! empty($account_localtax1[3])?$account_localtax1[3]:$langs->trans("CodeNotDef"));
+		$account_localtax2=getLocalTaxesFromRate($obj->tva_tx, 2, $mysoc);
+		$compta_localtax2= (! empty($account_localtax2[3])?$account_localtax2[3]:$langs->trans("CodeNotDef"));
+		
     	//la ligne facture
    		$tabfac[$obj->rowid]["date"] = $obj->datef;
    		$tabfac[$obj->rowid]["ref"] = $obj->facnumber;
@@ -178,17 +180,15 @@ else {
  */
 
 
-$i = 0;
-print "<table class=\"noborder\" width=\"100%\">";
-print "<tr class=\"liste_titre\">";
+print '<table class="noborder" width="100%">';
+print '<tr class="liste_titre">';
 //print "<td>".$langs->trans("JournalNum")."</td>";
-print "<td>".$langs->trans("Date")."</td><td>".$langs->trans("Piece").' ('.$langs->trans("InvoiceRef").")</td>";
-print "<td>".$langs->trans("Account")."</td>";
-print "<td>".$langs->trans("Type")."</td><td align='right'>".$langs->trans("Debit")."</td><td align='right'>".$langs->trans("Credit")."</td>";
+print '<td>'.$langs->trans('Date').'</td><td>'.$langs->trans('Piece').' ('.$langs->trans('InvoiceRef').')</td>';
+print '<td>'.$langs->trans('Account').'</td>';
+print '<td>'.$langs->trans('Type').'</td><td align="right">'.$langs->trans('Debit').'</td><td align="right">'.$langs->trans('Credit').'</td>';
 print "</tr>\n";
 
 $var=true;
-$r='';
 
 $invoicestatic=new Facture($db);
 $companystatic=new Client($db);
@@ -199,74 +199,62 @@ foreach ($tabfac as $key => $val)
 	$invoicestatic->ref=$val["ref"];
 	$invoicestatic->type=$val["type"];
 
-	print "<tr ".$bc[$var].">";
-	// third party
-	//print "<td>".$conf->global->COMPTA_JOURNAL_SELL."</td>";
-	print "<td>".$val["date"]."</td>";
-	print "<td>".$invoicestatic->getNomUrl(1)."</td>";
-	foreach ($tabttc[$key] as $k => $mt)
+	$companystatic->id=$tabcompany[$key]['id'];
+	$companystatic->name=$tabcompany[$key]['name'];
+	$companystatic->client=$tabcompany[$key]['client'];
+
+	$lines = array(
+		array(
+			'var' => $tabttc[$key],
+			'label' => $langs->trans('ThirdParty').' ('.$companystatic->getNomUrl(0, 'customer', 16).')',
+			'nomtcheck' => true,
+			'inv' => true
+		),
+		array(
+			'var' => $tabht[$key],
+			'label' => $langs->trans('Products'),
+		),
+		array(
+			'var' => $tabtva[$key],
+			'label' => $langs->trans('VAT')
+		),
+		array(
+			'var' => $tablocaltax1[$key],
+			'label' => $langs->transcountry('LT1', $mysoc->country_code)
+		),
+		array(
+			'var' => $tablocaltax2[$key],
+			'label' => $langs->transcountry('LT2', $mysoc->country_code)
+		)	
+	);
+
+	foreach ($lines as $line)
 	{
-    	$companystatic->id=$tabcompany[$key]['id'];
-    	$companystatic->name=$tabcompany[$key]['name'];
-    	$companystatic->client=$tabcompany[$key]['client'];
-    	print "<td>".$k;
-		print "</td><td>".$langs->trans("ThirdParty");
-		print ' ('.$companystatic->getNomUrl(0,'customer',16).')';
-		print "</td><td align='right'>".($mt>=0?price($mt):'')."</td><td align='right'>".($mt<0?price(-$mt):'')."</td>";
-	}
-	print "</tr>";
-	// product
-	foreach ($tabht[$key] as $k => $mt)
-	{
-		if ($mt)
+		foreach ($line['var'] as $k => $mt)
 		{
-			print "<tr ".$bc[$var].">";
-			//print "<td>".$conf->global->COMPTA_JOURNAL_SELL."</td>";
-			print "<td>".$val["date"]."</td>";
-			print "<td>".$invoicestatic->getNomUrl(1)."</td>";
-			print "<td>".$k;
-			print "</td><td>".$langs->trans("Products")."</td><td align='right'>".($mt<0?price(-$mt):'')."</td><td align='right'>".($mt>=0?price($mt):'')."</td></tr>";
+			if (isset($line['nomtcheck']) || $mt)
+			{
+				print "<tr ".$bc[$var]." >";
+				//print "<td>".$conf->global->COMPTA_JOURNAL_SELL."</td>";
+				print "<td>".$val["date"]."</td>";
+				print "<td>".$invoicestatic->getNomUrl(1)."</td>";
+				print "<td>".$k."</td><td>".$line['label']."</td>";
+
+				if (isset($line['inv']))
+				{
+					print '<td align="right">'.($mt>=0?price($mt):'')."</td>";
+					print '<td align="right">'.($mt<0?price(-$mt):'')."</td>";
+				}
+				else
+				{
+					print '<td align="right">'.($mt<0?price(-$mt):'')."</td>";
+	    			print '<td align="right">'.($mt>=0?price($mt):'')."</td>";
+				}
+
+				print "</tr>";
+			}
 		}
 	}
-	// vat
-	foreach ($tabtva[$key] as $k => $mt)
-	{
-	    if ($mt)
-	    {
-    		print "<tr ".$bc[$var].">";
-    		//print "<td>".$conf->global->COMPTA_JOURNAL_SELL."</td>";
-    		print "<td>".$val["date"]."</td>";
-    		print "<td>".$invoicestatic->getNomUrl(1)."</td>";
-    		print "<td>".$k;
-    		print "</td><td>".$langs->trans("VAT")."</td><td align='right'>".($mt<0?price(-$mt):'')."</td><td align='right'>".($mt>=0?price($mt):'')."</td></tr>";
-	    }
-	}
-	// localtax1
-	foreach ($tablocaltax1[$key] as $k => $mt)
-	{
-	    if ($mt)
-	    {
-    		print "<tr ".$bc[$var].">";
-    		//print "<td>".$conf->global->COMPTA_JOURNAL_SELL."</td>";
-    		print "<td>".$val["date"]."</td>";
-    		print "<td>".$invoicestatic->getNomUrl(1)."</td>";
-    		print "<td>".$k;
-    		print "</td><td>".$langs->transcountrynoentities("LT1",$mysoc->country_code)."</td><td align='right'>".($mt<0?price(-$mt):'')."</td><td align='right'>".($mt>=0?price($mt):'')."</td></tr>";
-	    }
-	}
-	// localtax2
-	foreach ($tablocaltax2[$key] as $k => $mt)
-	{
-	    if ($mt)
-	    {
-    		print "<tr ".$bc[$var].">";
-    		//print "<td>".$conf->global->COMPTA_JOURNAL_SELL."</td>";
-    		print "<td>".$val["date"]."</td>";
-    		print "<td>".$invoicestatic->getNomUrl(1)."</td>";
-    		print "<td>".$k;
-    		print "</td><td>".$langs->transcountrynoentities("LT2",$mysoc->country_code)."</td><td align='right'>".($mt<0?price(-$mt):'')."</td><td align='right'>".($mt>=0?price($mt):'')."</td></tr>";
-	    }
-	}
 
 	$var = !$var;
 }
diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php
index b1b26518e9546949731ef7e478420ed7f83c1c18..456834120375db1a086e7beda6907f64f85be017 100644
--- a/htdocs/core/lib/functions.lib.php
+++ b/htdocs/core/lib/functions.lib.php
@@ -2848,7 +2848,7 @@ function getLocalTaxesFromRate($vatrate, $local, $thirdparty)
 	dol_syslog("getLocalTaxesFromRate vatrate=".$vatrate." local=".$local." thirdparty id=".(is_object($thirdparty)?$thirdparty->id:''));
 
 	// Search local taxes
-	$sql  = "SELECT t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type";
+	$sql  = "SELECT t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type,t.accountancy_code_sell,t.accountancy_code_buy";
 	$sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_pays as p";
 	$sql .= " WHERE t.fk_pays = p.rowid AND p.code = '".$thirdparty->country_code."'";
 	$sql .= " AND t.taux = ".$vatrate." AND t.active = 1";
@@ -2857,9 +2857,9 @@ function getLocalTaxesFromRate($vatrate, $local, $thirdparty)
 	if ($resql)
 	{
 		$obj = $db->fetch_object($resql);
-		if ($local == 1) return array($obj->localtax1_type, $obj->localtax1);
-		elseif ($local == 2) return array($obj->localtax2_type, $obj->localtax2);
-		else return array($obj->localtax1_type, $obj->localtax1, $obj->localtax2_type, $obj->localtax2);
+		if ($local == 1) return array($obj->localtax1_type, $obj->localtax1,$obj->accountancy_code_sell,$obj->accountancy_code_buy);
+		elseif ($local == 2) return array($obj->localtax2_type, $obj->localtax2,$obj->accountancy_code_sell,$obj->accountancy_code_buy);
+		else return array($obj->localtax1_type, $obj->localtax1, $obj->localtax2_type, $obj->localtax2,$obj->accountancy_code_sell,$obj->accountancy_code_buy);
 	}
 
 	return 0;
diff --git a/htdocs/core/modules/commande/doc/doc_generic_order_odt.modules.php b/htdocs/core/modules/commande/doc/doc_generic_order_odt.modules.php
index 00658b7b9cb2d9d3f2866760c4917ea91065b082..3330f491e707eba441008f61e19e312027d326e3 100644
--- a/htdocs/core/modules/commande/doc/doc_generic_order_odt.modules.php
+++ b/htdocs/core/modules/commande/doc/doc_generic_order_odt.modules.php
@@ -519,8 +519,12 @@ class doc_generic_order_odt extends ModelePDFCommandes
 				$reshook=$hookmanager->executeHooks('beforeODTSave',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
 
 				// Write new file
-				//$result=$odfHandler->exportAsAttachedFile('toto');
-				$odfHandler->saveToDisk($file);
+				if (!empty($conf->global->MAIN_ODT_AS_PDF)) {
+					$odfHandler->exportAsAttachedPDF($file);
+				}
+				else {
+					$odfHandler->saveToDisk($file);
+				}	
 
 				if (! empty($conf->global->MAIN_UMASK))
 					@chmod($file, octdec($conf->global->MAIN_UMASK));
diff --git a/htdocs/core/modules/expedition/methode_expedition.modules.php b/htdocs/core/modules/expedition/methode_expedition.modules.php
deleted file mode 100644
index 3ea7ba97ce9935fa2be06f97a6a40dd6d57a8959..0000000000000000000000000000000000000000
--- a/htdocs/core/modules/expedition/methode_expedition.modules.php
+++ /dev/null
@@ -1,68 +0,0 @@
-<?php
-/* Copyright (C) 2003 Rodolphe Quiedeville <rodolphe@quiedeville.org>
- * Copyright (C) 2007 Laurent Destailleur  <eldy@users.sourceforge.net>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * or see http://www.gnu.org/
- */
-
-/**
- *	\file       htdocs/core/modules/expedition/methode_expedition.modules.php
- *	\ingroup    expedition
- *	\brief      Fichier contenant la classe mere de generation de bon de livraison en PDF
- *				et la classe mere de numerotation des bons de livraisons
- */
-require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php';
-
-
-/**
- *	Parent class for shipping method classes
- */
-class ModeleShippingMethod
-{
-    /**
-     * Constructo
-     *
-     * @param	DoliDB		$db		Database handler
-     */
-	function __construct($db)
-	{
-		$this->db = $db;
-		$this->name = "NOT DEFINED";
-		$this->description = "ERROR IN MODULE DESCRIPTION";
-	}
-
-
-	/**
-	 *  Return list of active generation modules
-	 *
-     *  @param	DoliDB	$db     			Database handler
-     *  @param  string	$maxfilenamelength  Max length of value to show
-     *  @return	array						List of templates
-	 */
-	static function liste_modeles($db,$maxfilenamelength=0)
-	{
-		global $conf;
-
-		$type='???';
-		$liste=array();
-
-		include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
-		$liste=getListOfModels($db,$type,$maxfilenamelength);
-
-		return $liste;
-	}
-}
-
-?>
diff --git a/htdocs/core/modules/expedition/methode_expedition_colsui.modules.php b/htdocs/core/modules/expedition/methode_expedition_colsui.modules.php
deleted file mode 100644
index fca7ffc38ff09615863b009895b2a4df89f1efff..0000000000000000000000000000000000000000
--- a/htdocs/core/modules/expedition/methode_expedition_colsui.modules.php
+++ /dev/null
@@ -1,56 +0,0 @@
-<?php
-/* Copyright (C) 2008 Rodolphe Quiedeville <rodolphe@quiedeville.org>
- * Copyright (C) 2008 Bearstech - http://bearstech.com/
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-
-/**
- *	\file       htdocs/core/modules/expedition/methode_expedition_colsui.modules.php
- *	\ingroup    expedition
- */
-include_once 'methode_expedition.modules.php';
-
-/**
- * Class to manage shipment Colsui
- */
-class methode_expedition_colsui extends ModeleShippingMethod
-{
-    /**
-     * Constructor
-     *
-     * @param	DoliDB		$db		Database handler
-     */
-	function __construct($db=0)
-	{
-		$this->db = $db;
-		$this->id = 3; // Do not change this value
-		$this->code = "COLSUI";  // Do not change this value
-		$this->name = "Colissimo Suivi";
-		$this->description = "Colissimo Suivi";
-	}
-
-	/**
-	 * Return URL of provider
-	 *
-	 * @param	string	$tracking_number	Tracking number
-	 * @return	string						URL for tracking
-	 */
-	function provider_url_status($tracking_number)
-	{
-		return sprintf("http://www.coliposte.net/particulier/suivi_particulier.jsp?colispart=%s",$tracking_number);
-	}
-}
-
-?>
diff --git a/htdocs/core/modules/expedition/methode_expedition_enl.modules.php b/htdocs/core/modules/expedition/methode_expedition_enl.modules.php
deleted file mode 100644
index 17e5cf35be9516104f7deca5a48500a1b2e8f0d7..0000000000000000000000000000000000000000
--- a/htdocs/core/modules/expedition/methode_expedition_enl.modules.php
+++ /dev/null
@@ -1,57 +0,0 @@
-<?php
-/* Copyright (C) 2003-2008 Rodolphe Quiedeville <rodolphe@quiedeville.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-
-/**
- *	\file       htdocs/core/modules/expedition/methode_expedition_enl.modules.php
- *	\ingroup    expedition
- */
-include_once 'methode_expedition.modules.php';
-
-
-/**
- * Class to manage shipment Enl
- */
-class methode_expedition_enl extends ModeleShippingMethod
-{
-    /**
-     * Constructor
-     *
-     * @param	DoliDB		$db		Database handler
-     */
-	function __construct($db=0)
-	{
-		global $langs;
-		$this->db = $db;
-		$this->id = 1; // Do not change this value
-		$this->name = "Enlevement";
-		$this->code = "ENL";
-		$this->description = $langs->trans("Enlevement");
-	}
-
-	/**
-	 * Return URL of provider
-	 *
-	 * @param	string	$tracking_number	Tracking number
-	 * @return	string						URL for tracking
-	 */
-	function provider_url_status($tracking_number)
-	{
-		return '';
-	}
-}
-
-?>
diff --git a/htdocs/core/modules/expedition/methode_expedition_lettremax.modules.php b/htdocs/core/modules/expedition/methode_expedition_lettremax.modules.php
deleted file mode 100644
index c8150af9497b796e53d6fe3db53c93b01554b5a2..0000000000000000000000000000000000000000
--- a/htdocs/core/modules/expedition/methode_expedition_lettremax.modules.php
+++ /dev/null
@@ -1,57 +0,0 @@
-<?php
-/* Copyright (C) 2011 Regis Houssin  <regis.houssin@capnetworks.com>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-
-/**
- *	\file       htdocs/core/modules/expedition/methode_expedition_lettremax.modules.php
- *	\ingroup    expedition
- */
-
-include_once 'methode_expedition.modules.php';
-
-
-/**
- * Class to manage shipment lettremax
- */
-class methode_expedition_lettremax extends ModeleShippingMethod
-{
-    /**
-     * Constructor
-     *
-     * @param	DoliDB		$db		Database handler
-     */
-	function __construct($db=0)
-	{
-		$this->db = $db;
-		$this->id = 4; // Do not change this value
-		$this->code = "LETTREMAX";  // Do not change this value
-		$this->name = "Lettre max";
-		$this->description = "Courrier suivi et lettre max";
-	}
-
-	/**
-	 * Return URL of provider
-	 *
-	 * @param	string	$tracking_number	Tracking number
-	 * @return	string						URL for tracking
-	 */
-	function provider_url_status($tracking_number)
-	{
-		return sprintf("http://www.csuivi.courrier.laposte.fr/default.asp?EZ_ACTION=rechercheRapide&numObjet=%s",$tracking_number);
-	}
-}
-
-?>
diff --git a/htdocs/core/modules/expedition/methode_expedition_trans.modules.php b/htdocs/core/modules/expedition/methode_expedition_trans.modules.php
deleted file mode 100644
index d974b7c161a1d7a0857f50e51a0a37c8e413cbb5..0000000000000000000000000000000000000000
--- a/htdocs/core/modules/expedition/methode_expedition_trans.modules.php
+++ /dev/null
@@ -1,59 +0,0 @@
-<?php
-/* Copyright (C) 2003-2008 Rodolphe Quiedeville <rodolphe@quiedeville.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-
-/**
- *	\file       htdocs/core/modules/expedition/methode_expedition_trans.modules.php
- *	\ingroup    expedition
- */
-include_once 'methode_expedition.modules.php';
-
-
-/**
- * Class to manage shipment Trans
- */
-class methode_expedition_trans extends ModeleShippingMethod
-{
-
-    /**
-     * Constructor
-     *
-     * @param	DoliDB		$db		Database handler
-     */
-	function __construct($db=0)
-	{
-		global $langs;
-
-		$this->db = $db;
-		$this->id = 2; // Ne pas changer cette valeur
-		$this->code = "TRANS";
-		$this->name = "Transporteur";
-		$this->description = $langs->trans("GenericTransport");
-	}
-
-	/**
-	 * Return URL of provider
-	 *
-	 * @param	string	$tracking_number	Tracking number
-	 * @return	string						URL for tracking
-	 */
-	function provider_url_status($tracking_number)
-	{
-		return '';
-	}
-}
-
-?>
diff --git a/htdocs/core/modules/facture/doc/doc_generic_invoice_odt.modules.php b/htdocs/core/modules/facture/doc/doc_generic_invoice_odt.modules.php
index 512bf98be8b4bbd4b006e665e9b8c2e3a1d1bdc4..8aa417c83c022b679d54af1ae0f7d169ba98d411 100644
--- a/htdocs/core/modules/facture/doc/doc_generic_invoice_odt.modules.php
+++ b/htdocs/core/modules/facture/doc/doc_generic_invoice_odt.modules.php
@@ -497,8 +497,12 @@ class doc_generic_invoice_odt extends ModelePDFFactures
 				$reshook=$hookmanager->executeHooks('beforeODTSave',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
 
 				// Write new file
-				//$result=$odfHandler->exportAsAttachedFile('toto');
-				$odfHandler->saveToDisk($file);
+				if (!empty($conf->global->MAIN_ODT_AS_PDF)) {
+					$odfHandler->exportAsAttachedPDF($file);
+				}
+				else {
+					$odfHandler->saveToDisk($file);
+				}	
 
 				if (! empty($conf->global->MAIN_UMASK))
 					@chmod($file, octdec($conf->global->MAIN_UMASK));
diff --git a/htdocs/core/modules/project/pdf/doc_generic_project_odt.modules.php b/htdocs/core/modules/project/pdf/doc_generic_project_odt.modules.php
index 1fbd02bbe6fa24f37e5ee57da50150846f6c220c..4c81babaa551cf0faaed57d29a82c470e5f38f39 100644
--- a/htdocs/core/modules/project/pdf/doc_generic_project_odt.modules.php
+++ b/htdocs/core/modules/project/pdf/doc_generic_project_odt.modules.php
@@ -650,7 +650,7 @@ class doc_generic_project_odt extends ModelePDFProjects
 
 						//Time ressources
 						$sql = "SELECT t.rowid, t.task_date, t.task_duration, t.fk_user, t.note";
-						$sql.= ", u.name, u.firstname";
+						$sql.= ", u.lastname, u.firstname";
 						$sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time as t";
 						$sql .= " , ".MAIN_DB_PREFIX."user as u";
 						$sql .= " WHERE t.fk_task =".$task->id;
@@ -973,8 +973,12 @@ class doc_generic_project_odt extends ModelePDFProjects
 
 
 				// Write new file
-				$odfHandler->saveToDisk($file);	
-				//$odfHandler->exportAsAttachedPDF($file);
+				if (!empty($conf->global->MAIN_ODT_AS_PDF)) {
+					$odfHandler->exportAsAttachedPDF($file);
+				}
+				else {
+					$odfHandler->saveToDisk($file);
+				}	
 
 				if (! empty($conf->global->MAIN_UMASK))
 					@chmod($file, octdec($conf->global->MAIN_UMASK));
diff --git a/htdocs/core/modules/propale/doc/doc_generic_proposal_odt.modules.php b/htdocs/core/modules/propale/doc/doc_generic_proposal_odt.modules.php
index 26d67f09a321f1b338c4ab7fc0f5cebe7e28b44e..d4e485562a4d139991fa8b57a1932696104a1cdf 100644
--- a/htdocs/core/modules/propale/doc/doc_generic_proposal_odt.modules.php
+++ b/htdocs/core/modules/propale/doc/doc_generic_proposal_odt.modules.php
@@ -482,8 +482,12 @@ class doc_generic_proposal_odt extends ModelePDFPropales
 				$reshook=$hookmanager->executeHooks('beforeODTSave',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
 
 				// Write new file
-				//$result=$odfHandler->exportAsAttachedFile('toto');
-				$odfHandler->saveToDisk($file);
+				if (!empty($conf->global->MAIN_ODT_AS_PDF)) {
+					$odfHandler->exportAsAttachedPDF($file);
+				}
+				else {
+					$odfHandler->saveToDisk($file);
+				}	
 
 				if (! empty($conf->global->MAIN_UMASK))
 					@chmod($file, octdec($conf->global->MAIN_UMASK));
diff --git a/htdocs/core/modules/societe/doc/doc_generic_odt.modules.php b/htdocs/core/modules/societe/doc/doc_generic_odt.modules.php
index acf14c67139f31161b92d2d5b644fd6bf1f76179..ca93ab1880ed5d8a5a959863efb00d3751104907 100644
--- a/htdocs/core/modules/societe/doc/doc_generic_odt.modules.php
+++ b/htdocs/core/modules/societe/doc/doc_generic_odt.modules.php
@@ -313,8 +313,12 @@ class doc_generic_odt extends ModeleThirdPartyDoc
 				$reshook=$hookmanager->executeHooks('beforeODTSave',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
 
 				// Write new file
-				//$result=$odfHandler->exportAsAttachedFile('toto');
-				$odfHandler->saveToDisk($file);
+				if (!empty($conf->global->MAIN_ODT_AS_PDF)) {
+					$odfHandler->exportAsAttachedPDF($file);
+				}
+				else {
+					$odfHandler->saveToDisk($file);
+				}	
 
 				if (! empty($conf->global->MAIN_UMASK))
 				@chmod($file, octdec($conf->global->MAIN_UMASK));
diff --git a/htdocs/expedition/class/expedition.class.php b/htdocs/expedition/class/expedition.class.php
index f3db4dafc8b191e9b11cf3301fc962701e43226c..95b18e1d814b7573f6f23bf123ccb24ba2373fe5 100644
--- a/htdocs/expedition/class/expedition.class.php
+++ b/htdocs/expedition/class/expedition.class.php
@@ -1199,7 +1199,7 @@ class Expedition extends CommonObject
     {
         global $langs;
 
-        $listmeths = array();
+        $this->listmeths = array();
         $i=0;
 
         $sql = "SELECT em.rowid, em.code, em.libelle, em.description, em.tracking, em.active";
@@ -1216,29 +1216,11 @@ class Expedition extends CommonObject
                 $label=$langs->trans('SendingMethod'.$obj->code);
                 $this->listmeths[$i]['libelle'] = ($label != 'SendingMethod'.$obj->code?$label:$obj->libelle);
                 $this->listmeths[$i]['description'] = $obj->description;
-                if ($obj->tracking)
-                {
-                    $this->listmeths[$i]['tracking'] = $obj->tracking;
-                }
-                else
-                {
-                    if ($obj->code)
-                    {
-                        $classname = "methode_expedition_".strtolower($obj->code);
-
-                        if (file_exists(DOL_DOCUMENT_ROOT."/core/modules/expedition/methode_expedition_".strtolower($obj->code).".modules.php") )
-                        {
-                            require_once DOL_DOCUMENT_ROOT."/core/modules/expedition/methode_expedition_".strtolower($obj->code).'.modules.php';
-                            $shipmethod = new $classname();
-                            $this->listmeths[$i]['tracking'] = $shipmethod->provider_url_status('{TRACKID}');
-                        }
-                    }
-                }
+                $this->listmeths[$i]['tracking'] = $obj->tracking;
                 $this->listmeths[$i]['active'] = $obj->active;
                 $i++;
             }
         }
-        else dol_print_error($this->db,'');
     }
 
     /**
@@ -1309,8 +1291,6 @@ class Expedition extends CommonObject
 	 */
 	function GetUrlTrackingStatus($value='')
 	{
-		$code='';
-
 		if (! empty($this->shipping_method_id))
 		{
 			$sql = "SELECT em.code, em.tracking";
@@ -1322,46 +1302,21 @@ class Expedition extends CommonObject
 			{
 				if ($obj = $this->db->fetch_object($resql))
 				{
-					$code = $obj->code;
-                    $tracking = $obj->tracking;
+					$tracking = $obj->tracking;
 				}
 			}
 		}
 
-        if ($tracking)
-        {
-                $url = str_replace('{TRACKID}', $value, $tracking);
-                $this->tracking_url = sprintf('<a target="_blank" href="%s">'.($value?$value:'url').'</a>',$url,$url);
-        }
-        else
-        {
-            if ($code)
-            {
-                $classname = "methode_expedition_".strtolower($code);
-
-                $url='';
-                if (file_exists(DOL_DOCUMENT_ROOT."/core/modules/expedition/methode_expedition_".strtolower($code).".modules.php") && ! empty($this->tracking_number))
-                {
-                    require_once DOL_DOCUMENT_ROOT."/core/modules/expedition/methode_expedition_".strtolower($code).'.modules.php';
-                    $shipmethod = new $classname();
-                    $url = $shipmethod->provider_url_status($this->tracking_number);
-                }
-
-                if ($url)
-                {
-                    $this->tracking_url = sprintf('<a target="_blank" href="%s">'.($value?$value:'url').'</a>',$url,$url);
-                }
-                else
-                {
-                    $this->tracking_url = $value;
-                }
-            }
-            else
-            {
-                $this->tracking_url = $value;
-            }
-        }
-    }
+		if (!empty($tracking) && !empty($value))
+		{
+			$url = str_replace('{TRACKID}', $value, $tracking);
+			$this->tracking_url = sprintf('<a target="_blank" href="%s">'.($value?$value:'url').'</a>',$url,$url);
+		}
+		else
+		{
+			$this->tracking_url = $value;
+		}
+	}
 
 	/**
 	 *	Classify the shipping as invoiced
diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php
index 759258888cff86917309a5d4283ff3990679d572..ac138636b08f8ba06ce6265425d65b9575e9f5fc 100644
--- a/htdocs/fourn/class/fournisseur.facture.class.php
+++ b/htdocs/fourn/class/fournisseur.facture.class.php
@@ -141,6 +141,7 @@ class FactureFournisseur extends CommonInvoice
         $sql.= ", fk_soc";
         $sql.= ", datec";
         $sql.= ", datef";
+		$sql.= ", fk_projet";
         $sql.= ", note_private";
         $sql.= ", note_public";
         $sql.= ", fk_user_author";
@@ -154,6 +155,7 @@ class FactureFournisseur extends CommonInvoice
         $sql.= ", ".$this->socid;
         $sql.= ", '".$this->db->idate($now)."'";
         $sql.= ", '".$this->db->idate($this->date)."'";
+		$sql.= ", ".$this->fk_project;
         $sql.= ", '".$this->db->escape($this->note_private)."'";
         $sql.= ", '".$this->db->escape($this->note_public)."'";
         $sql.= ", ".$user->id.",";
diff --git a/htdocs/fourn/facture/fiche.php b/htdocs/fourn/facture/fiche.php
index 6ed624b82fa9ec86f7dd5173cc81e8b67cc98f04..23ed291c6816b18e51b2c310bef30ea4fc362d0a 100644
--- a/htdocs/fourn/facture/fiche.php
+++ b/htdocs/fourn/facture/fiche.php
@@ -41,6 +41,8 @@ if (!empty($conf->produit->enabled))
 	require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
 if (!empty($conf->projet->enabled))
 	require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
+if (! empty($conf->projet->enabled))
+	require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
 
 
 $langs->load('bills');
@@ -271,6 +273,7 @@ elseif ($action == 'add' && $user->rights->fournisseur->facture->creer)
         // Creation facture
         $object->ref           = $_POST['ref'];
 		$object->ref_supplier  = $_POST['ref_supplier'];
+		$object->fk_project    = GETPOST('projectid');
         $object->socid         = $_POST['socid'];
         $object->libelle       = $_POST['libelle'];
         $object->date          = $datefacture;
@@ -1153,6 +1156,15 @@ if ($action == 'create')
     print '<tr><td>'.$langs->trans('DateMaxPayment').'</td><td>';
     $form->select_date($datedue,'ech','','','',"add",1,1);
     print '</td></tr>';
+	
+	// Project
+	if (! empty($conf->projet->enabled))
+	{
+		$langs->load('projects');
+		print '<tr><td>'.$langs->trans('Project').'</td><td colspan="2">';
+		select_projects(-1, $projectid, 'projectid');
+		print '</td></tr>';
+	}
 
     print '<tr><td>'.$langs->trans('NotePublic').'</td>';
     print '<td>';
diff --git a/htdocs/holiday/admin/holiday.php b/htdocs/holiday/admin/holiday.php
index 583ab228c9a442650d0279a07006e07dad9cb935..6e7216332ead822510475b14bde9ec1722745a95 100644
--- a/htdocs/holiday/admin/holiday.php
+++ b/htdocs/holiday/admin/holiday.php
@@ -278,7 +278,7 @@ $var=true;
 
 /*$var=!$var;
 print '<tr '.$bc[$var].'>'."\n";
-print '<td style="padding:5px; width: 40%;">'.$langs->trans('GroupToValidateCP').'</td>'."\n";
+print '<td style="padding:5px;">'.$langs->trans('GroupToValidateCP').'</td>'."\n";
 print '<td style="padding:5px;">'.$cp->selectUserGroup('userGroup').'</td>'."\n";
 print '</tr>'."\n";
 */
diff --git a/htdocs/includes/odtphp/odf.php b/htdocs/includes/odtphp/odf.php
index 7e72eb6f7e24e6107a0ef285e874f38bcb58b7b7..4f91157438b9aec4baa15a20142364a4ec3d1381 100644
--- a/htdocs/includes/odtphp/odf.php
+++ b/htdocs/includes/odtphp/odf.php
@@ -18,152 +18,152 @@ class OdfException extends Exception
 class Odf
 {
 	protected $config = array(
-    	'ZIP_PROXY' => 'PclZipProxy',	// PclZipProxy, PhpZipProxy
-    	'DELIMITER_LEFT' => '{',
-    	'DELIMITER_RIGHT' => '}',
-		'PATH_TO_TMP' => '/tmp'
-		);
-		protected $file;
-		protected $contentXml;			// To store content of content.xml file
-		protected $stylesXml;			// To store content of styles.xml file
-		protected $manifestXml;			// To store content of META-INF/manifest.xml file
-		protected $tmpfile;
-		protected $tmpdir='';
-		protected $images = array();
-		protected $vars = array();
-		protected $segments = array();
-		const PIXEL_TO_CM = 0.026458333;
-		/**
-		 * Class constructor
-		 *
-		 * @param string $filename the name of the odt file
-		 * @throws OdfException
-		 */
-		public function __construct($filename, $config = array())
-		{
-			clearstatcache();
-
-			if (! is_array($config)) {
-				throw new OdfException('Configuration data must be provided as array');
-			}
-			foreach ($config as $configKey => $configValue) {
-				if (array_key_exists($configKey, $this->config)) {
-					$this->config[$configKey] = $configValue;
-				}
-			}
-
-			$md5uniqid = md5(uniqid());
-			if ($this->config['PATH_TO_TMP']) $this->tmpdir = preg_replace('|[\/]$|','',$this->config['PATH_TO_TMP']);	// Remove last \ or /
-			$this->tmpdir .= ($this->tmpdir?'/':'').$md5uniqid;
-			$this->tmpfile = $this->tmpdir.'/'.$md5uniqid.'.odt';	// We keep .odt extension to allow OpenOffice usage during debug.
-
-			// A working directory is required for some zip proxy like PclZipProxy
-			if (in_array($this->config['ZIP_PROXY'],array('PclZipProxy')) && ! is_dir($this->config['PATH_TO_TMP'])) {
-				throw new OdfException('Temporary directory '.$this->config['PATH_TO_TMP'].' must exists');
-			}
-
-			// Create tmp direcoty (will be deleted in destructor)
-			if (!file_exists($this->tmpdir)) {
-				$result=mkdir($this->tmpdir);
-			}
-
-			// Load zip proxy
-			$zipHandler = $this->config['ZIP_PROXY'];
-			if (!defined('PCLZIP_TEMPORARY_DIR')) define('PCLZIP_TEMPORARY_DIR',$this->tmpdir);
-			include_once('zip/'.$zipHandler.'.php');
-			if (! class_exists($this->config['ZIP_PROXY'])) {
-				throw new OdfException($this->config['ZIP_PROXY'] . ' class not found - check your php settings');
+	'ZIP_PROXY' => 'PclZipProxy',	// PclZipProxy, PhpZipProxy
+	'DELIMITER_LEFT' => '{',
+	'DELIMITER_RIGHT' => '}',
+	'PATH_TO_TMP' => '/tmp'
+	);
+	protected $file;
+	protected $contentXml;			// To store content of content.xml file
+	protected $stylesXml;			// To store content of styles.xml file
+	protected $manifestXml;			// To store content of META-INF/manifest.xml file
+	protected $tmpfile;
+	protected $tmpdir='';
+	protected $images = array();
+	protected $vars = array();
+	protected $segments = array();
+	const PIXEL_TO_CM = 0.026458333;
+	/**
+	 * Class constructor
+	 *
+	 * @param string $filename the name of the odt file
+	 * @throws OdfException
+	 */
+	public function __construct($filename, $config = array())
+	{
+		clearstatcache();
+
+		if (! is_array($config)) {
+			throw new OdfException('Configuration data must be provided as array');
+		}
+		foreach ($config as $configKey => $configValue) {
+			if (array_key_exists($configKey, $this->config)) {
+				$this->config[$configKey] = $configValue;
 			}
-			$this->file = new $zipHandler($this->tmpdir);
+		}
 
+		$md5uniqid = md5(uniqid());
+		if ($this->config['PATH_TO_TMP']) $this->tmpdir = preg_replace('|[\/]$|','',$this->config['PATH_TO_TMP']);	// Remove last \ or /
+		$this->tmpdir .= ($this->tmpdir?'/':'').$md5uniqid;
+		$this->tmpfile = $this->tmpdir.'/'.$md5uniqid.'.odt';	// We keep .odt extension to allow OpenOffice usage during debug.
 
-			if ($this->file->open($filename) !== true) {	// This also create the tmpdir directory
-				throw new OdfException("Error while Opening the file '$filename' - Check your odt filename");
-			}
-			if (($this->contentXml = $this->file->getFromName('content.xml')) === false) {
-				throw new OdfException("Nothing to parse - Check that the content.xml file is correctly formed in source file '$filename'");
-			}
-			if (($this->manifestXml = $this->file->getFromName('META-INF/manifest.xml')) === false) {
- 				throw new OdfException("Something is wrong with META-INF/manifest.xml in source file '$filename'");
-			}
-			if (($this->stylesXml = $this->file->getFromName('styles.xml')) === false) {
-				throw new OdfException("Nothing to parse - Check that the styles.xml file is correctly formed in source file '$filename'");
-			}
-			$this->file->close();
+		// A working directory is required for some zip proxy like PclZipProxy
+		if (in_array($this->config['ZIP_PROXY'],array('PclZipProxy')) && ! is_dir($this->config['PATH_TO_TMP'])) {
+			throw new OdfException('Temporary directory '.$this->config['PATH_TO_TMP'].' must exists');
+		}
 
+		// Create tmp direcoty (will be deleted in destructor)
+		if (!file_exists($this->tmpdir)) {
+			$result=mkdir($this->tmpdir);
+		}
 
-			//print "tmpdir=".$tmpdir;
-			//print "filename=".$filename;
-			//print "tmpfile=".$tmpfile;
+		// Load zip proxy
+		$zipHandler = $this->config['ZIP_PROXY'];
+		if (!defined('PCLZIP_TEMPORARY_DIR')) define('PCLZIP_TEMPORARY_DIR',$this->tmpdir);
+		include_once('zip/'.$zipHandler.'.php');
+		if (! class_exists($this->config['ZIP_PROXY'])) {
+			throw new OdfException($this->config['ZIP_PROXY'] . ' class not found - check your php settings');
+		}
+		$this->file = new $zipHandler($this->tmpdir);
 
-			copy($filename, $this->tmpfile);
 
-			$this->_moveRowSegments();
+		if ($this->file->open($filename) !== true) {	// This also create the tmpdir directory
+			throw new OdfException("Error while Opening the file '$filename' - Check your odt filename");
 		}
-
-		/**
-		 * Assing a template variable
-		 *
-		 * @param string $key name of the variable within the template
-		 * @param string $value replacement value
-		 * @param bool $encode if true, special XML characters are encoded
-		 * @throws OdfException
-		 * @return odf
-		 */
-		public function setVars($key, $value, $encode = true, $charset = 'ISO-8859')
-		{
-                    $tag = $this->config['DELIMITER_LEFT'] . $key . $this->config['DELIMITER_RIGHT'];
-		    // TODO Warning string may be:
-		    // <text:span text:style-name="T13">{</text:span><text:span text:style-name="T12">aaa</text:span><text:span text:style-name="T13">}</text:span>
-		    // instead of {aaa} so we should enhance this function.
-            //print $key.'-'.$value.'-'.strpos($this->contentXml, $this->config['DELIMITER_LEFT'] . $key . $this->config['DELIMITER_RIGHT']).'<br>';
-		    if (strpos($this->contentXml, $tag) === false && strpos($this->stylesXml , $tag) === false) {
-                //if (strpos($this->contentXml, '">'. $key . '</text;span>') === false) {
-		        throw new OdfException("var $key not found in the document");
-                //}
-		    }
-			$value = $encode ? htmlspecialchars($value) : $value;
-			$value = ($charset == 'ISO-8859') ? utf8_encode($value) : $value;
-			$this->vars[$tag] = str_replace("\n", "<text:line-break/>", $value);
-			return $this;
-		}
-		
-		/**
-		 * Assing a template variable
-		 *
-		 * @param string $key name of the variable within the template
-		 * @param string $value replacement value
-		 * @param bool $encode if true, special XML characters are encoded
-		 * @throws OdfException
-		 * @return odf
-		 */
-		public function setVarsHeadFooter($key, $value, $encode = true, $charset = 'ISO-8859')
-		{
-			$tag = $this->config['DELIMITER_LEFT'] . $key . $this->config['DELIMITER_RIGHT'];
-			// TODO Warning string may be:
-			// <text:span text:style-name="T13">{</text:span><text:span text:style-name="T12">aaa</text:span><text:span text:style-name="T13">}</text:span>
-			// instead of {aaa} so we should enhance this function.
-			//print $key.'-'.$value.'-'.strpos($this->contentXml, $this->config['DELIMITER_LEFT'] . $key . $this->config['DELIMITER_RIGHT']).'<br>';
-			if (strpos($this->stylesXml, $tag) === false && strpos($this->stylesXml , $tag) === false) {
+		if (($this->contentXml = $this->file->getFromName('content.xml')) === false) {
+			throw new OdfException("Nothing to parse - Check that the content.xml file is correctly formed in source file '$filename'");
+		}
+		if (($this->manifestXml = $this->file->getFromName('META-INF/manifest.xml')) === false) {
+			throw new OdfException("Something is wrong with META-INF/manifest.xml in source file '$filename'");
+		}
+		if (($this->stylesXml = $this->file->getFromName('styles.xml')) === false) {
+			throw new OdfException("Nothing to parse - Check that the styles.xml file is correctly formed in source file '$filename'");
+		}
+		$this->file->close();
+
+
+		//print "tmpdir=".$tmpdir;
+		//print "filename=".$filename;
+		//print "tmpfile=".$tmpfile;
+
+		copy($filename, $this->tmpfile);
+
+		$this->_moveRowSegments();
+	}
+
+	/**
+	 * Assing a template variable
+	 *
+	 * @param string $key name of the variable within the template
+	 * @param string $value replacement value
+	 * @param bool $encode if true, special XML characters are encoded
+	 * @throws OdfException
+	 * @return odf
+	 */
+	public function setVars($key, $value, $encode = true, $charset = 'ISO-8859')
+	{
+		$tag = $this->config['DELIMITER_LEFT'] . $key . $this->config['DELIMITER_RIGHT'];
+		// TODO Warning string may be:
+		// <text:span text:style-name="T13">{</text:span><text:span text:style-name="T12">aaa</text:span><text:span text:style-name="T13">}</text:span>
+		// instead of {aaa} so we should enhance this function.
+		//print $key.'-'.$value.'-'.strpos($this->contentXml, $this->config['DELIMITER_LEFT'] . $key . $this->config['DELIMITER_RIGHT']).'<br>';
+		if (strpos($this->contentXml, $tag) === false && strpos($this->stylesXml , $tag) === false) {
 			//if (strpos($this->contentXml, '">'. $key . '</text;span>') === false) {
-				throw new OdfException("var $key not found in the document");
-				//}
-			}
-			$value = $encode ? htmlspecialchars($value) : $value;
-				$value = ($charset == 'ISO-8859') ? utf8_encode($value) : $value;
-				$this->vars[$tag] = str_replace("\n", "<text:line-break/>", $value);
-				return $this;
+			throw new OdfException("var $key not found in the document");
+			//}
 		}
-
-		/**
-		 * Evaluating php codes inside the ODT and output the buffer (print, echo) inplace of the code
-		 *
-		 */
-		public function phpEval()
-		{
-			preg_match_all('/[\{\<]\?(php)?\s+(?P<content>.+)\?[\}\>]/iU',$this->contentXml, $matches); // detecting all {?php code ?} or <?php code ? >
-			for ($i=0;$i < count($matches['content']);$i++) {
-				try {
+		$value = $encode ? htmlspecialchars($value) : $value;
+		$value = ($charset == 'ISO-8859') ? utf8_encode($value) : $value;
+		$this->vars[$tag] = str_replace("\n", "<text:line-break/>", $value);
+		return $this;
+	}
+
+	/**
+	 * Assing a template variable
+	 *
+	 * @param string $key name of the variable within the template
+	 * @param string $value replacement value
+	 * @param bool $encode if true, special XML characters are encoded
+	 * @throws OdfException
+	 * @return odf
+	 */
+	public function setVarsHeadFooter($key, $value, $encode = true, $charset = 'ISO-8859')
+	{
+		$tag = $this->config['DELIMITER_LEFT'] . $key . $this->config['DELIMITER_RIGHT'];
+		// TODO Warning string may be:
+		// <text:span text:style-name="T13">{</text:span><text:span text:style-name="T12">aaa</text:span><text:span text:style-name="T13">}</text:span>
+		// instead of {aaa} so we should enhance this function.
+		//print $key.'-'.$value.'-'.strpos($this->contentXml, $this->config['DELIMITER_LEFT'] . $key . $this->config['DELIMITER_RIGHT']).'<br>';
+		if (strpos($this->stylesXml, $tag) === false && strpos($this->stylesXml , $tag) === false) {
+			//if (strpos($this->contentXml, '">'. $key . '</text;span>') === false) {
+			throw new OdfException("var $key not found in the document");
+			//}
+		}
+		$value = $encode ? htmlspecialchars($value) : $value;
+		$value = ($charset == 'ISO-8859') ? utf8_encode($value) : $value;
+		$this->vars[$tag] = str_replace("\n", "<text:line-break/>", $value);
+		return $this;
+	}
+
+	/**
+	 * Evaluating php codes inside the ODT and output the buffer (print, echo) inplace of the code
+	 *
+	 */
+	public function phpEval()
+	{
+		preg_match_all('/[\{\<]\?(php)?\s+(?P<content>.+)\?[\}\>]/iU',$this->contentXml, $matches); // detecting all {?php code ?} or <?php code ? >
+		for ($i=0;$i < count($matches['content']);$i++) {
+			try {
 				$ob_output = ''; // flush the output for each code. This var will be filled in by the eval($code) and output buffering : any print or echo or output will be redirected into this variable
 				$code = $matches['content'][$i];
 				ob_start();
@@ -171,363 +171,400 @@ class Odf
 				$ob_output = ob_get_contents(); // send the content of the buffer into $ob_output
 				$this->contentXml = str_replace($matches[0][$i], $ob_output, $this->contentXml);
 				ob_end_clean();
-				} catch (Exception $e) {
-					ob_end_clean();
-					$this->contentXml = str_replace($matches[0][$i], 'ERROR: there was a problem while evaluating this portion of code, please fix it: '.$e, $this->contentXml);
-				}
-			}
-			return 0;
-		}
-
-		/**
-		 * Assign a template variable as a picture
-		 *
-		 * @param string $key name of the variable within the template
-		 * @param string $value path to the picture
-		 * @throws OdfException
-		 * @return odf
-		 */
-		public function setImage($key, $value)
-		{
-			$filename = strtok(strrchr($value, '/'), '/.');
-			$file = substr(strrchr($value, '/'), 1);
-			$size = @getimagesize($value);
-			if ($size === false) {
-				throw new OdfException("Invalid image");
+			} catch (Exception $e) {
+				ob_end_clean();
+				$this->contentXml = str_replace($matches[0][$i], 'ERROR: there was a problem while evaluating this portion of code, please fix it: '.$e, $this->contentXml);
 			}
-			list ($width, $height) = $size;
-			$width *= self::PIXEL_TO_CM;
-			$height *= self::PIXEL_TO_CM;
-			$xml = <<<IMG
+		}
+		return 0;
+	}
+
+	/**
+	 * Assign a template variable as a picture
+	 *
+	 * @param string $key name of the variable within the template
+	 * @param string $value path to the picture
+	 * @throws OdfException
+	 * @return odf
+	 */
+	public function setImage($key, $value)
+	{
+		$filename = strtok(strrchr($value, '/'), '/.');
+		$file = substr(strrchr($value, '/'), 1);
+		$size = @getimagesize($value);
+		if ($size === false) {
+			throw new OdfException("Invalid image");
+		}
+		list ($width, $height) = $size;
+		$width *= self::PIXEL_TO_CM;
+		$height *= self::PIXEL_TO_CM;
+		$xml = <<<IMG
 			<draw:frame draw:style-name="fr1" draw:name="$filename" text:anchor-type="aschar" svg:width="{$width}cm" svg:height="{$height}cm" draw:z-index="3"><draw:image xlink:href="Pictures/$file" xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad"/></draw:frame>
 IMG;
-			$this->images[$value] = $file;
-			$this->setVars($key, $xml, false);
-			return $this;
-		}
-
-		/**
-		 * Move segment tags for lines of tables
-		 * Called automatically within the constructor
-		 *
-		 * @return void
-		 */
-		private function _moveRowSegments()
+		$this->images[$value] = $file;
+		$this->setVars($key, $xml, false);
+		return $this;
+	}
+
+	/**
+	 * Move segment tags for lines of tables
+	 * Called automatically within the constructor
+	 *
+	 * @return void
+	 */
+	private function _moveRowSegments()
+	{
+		// Search all possible rows in the document
+		$reg1 = "#<table:table-row[^>]*>(.*)</table:table-row>#smU";
+		preg_match_all($reg1, $this->contentXml, $matches);
+		for ($i = 0, $size = count($matches[0]); $i < $size; $i++) {
+			// Check if the current row contains a segment row.*
+			$reg2 = '#\[!--\sBEGIN\s(row.[\S]*)\s--\](.*)\[!--\sEND\s\\1\s--\]#sm';
+			if (preg_match($reg2, $matches[0][$i], $matches2)) {
+				$balise = str_replace('row.', '', $matches2[1]);
+				// Move segment tags around the row
+				$replace = array(
+				'[!-- BEGIN ' . $matches2[1] . ' --]'	=> '',
+				'[!-- END ' . $matches2[1] . ' --]'		=> '',
+				'<table:table-row'							=> '[!-- BEGIN ' . $balise . ' --]<table:table-row',
+				'</table:table-row>'						=> '</table:table-row>[!-- END ' . $balise . ' --]'
+				);
+				$replacedXML = str_replace(array_keys($replace), array_values($replace), $matches[0][$i]);
+				$this->contentXml = str_replace($matches[0][$i], $replacedXML, $this->contentXml);
+			}
+		}
+	}
+
+	/**
+	 * Merge template variables
+	 * Called automatically for a save
+	 *
+	 * @param  string	$type		'content' or 'styles'
+	 * @return void
+	 */
+	private function _parse($type='content')
+	{
+		// Conditionals substitution
+		// Note: must be done before content substitution, else the variable will be replaced by its value and the conditional won't work anymore
+		foreach($this->vars as $key => $value)
 		{
-			// Search all possible rows in the document
-			$reg1 = "#<table:table-row[^>]*>(.*)</table:table-row>#smU";
-			preg_match_all($reg1, $this->contentXml, $matches);
-			for ($i = 0, $size = count($matches[0]); $i < $size; $i++) {
-				// Check if the current row contains a segment row.*
-				$reg2 = '#\[!--\sBEGIN\s(row.[\S]*)\s--\](.*)\[!--\sEND\s\\1\s--\]#sm';
-				if (preg_match($reg2, $matches[0][$i], $matches2)) {
-					$balise = str_replace('row.', '', $matches2[1]);
-					// Move segment tags around the row
-					$replace = array(
-					'[!-- BEGIN ' . $matches2[1] . ' --]'	=> '',
-					'[!-- END ' . $matches2[1] . ' --]'		=> '',
-					'<table:table-row'							=> '[!-- BEGIN ' . $balise . ' --]<table:table-row',
-					'</table:table-row>'						=> '</table:table-row>[!-- END ' . $balise . ' --]'
-					);
-					$replacedXML = str_replace(array_keys($replace), array_values($replace), $matches[0][$i]);
-					$this->contentXml = str_replace($matches[0][$i], $replacedXML, $this->contentXml);
+			// If value is true (not 0 nor false nor null nor empty string)
+			if($value)
+			{
+				// Remove the IF tag
+				$this->contentXml = str_replace('[!-- IF '.$key.' --]', '', $this->contentXml);
+				// Remove everything between the ELSE tag (if it exists) and the ENDIF tag
+				$reg = '@(\[!--\sELSE\s' . $key . '\s--\](.*))?\[!--\sENDIF\s' . $key . '\s--\]@smU'; // U modifier = all quantifiers are non-greedy
+				$this->contentXml = preg_replace($reg, '', $this->contentXml);
+			}
+			// Else the value is false, then two cases: no ELSE and we're done, or there is at least one place where there is an ELSE clause, then we replace it
+			else
+			{
+				// Find all conditional blocks for this variable: from IF to ELSE and to ENDIF
+				$reg = '@\[!--\sIF\s' . $key . '\s--\](.*)(\[!--\sELSE\s' . $key . '\s--\](.*))?\[!--\sENDIF\s' . $key . '\s--\]@smU'; // U modifier = all quantifiers are non-greedy
+				preg_match_all($reg, $this->contentXml, $matches, PREG_SET_ORDER);
+				foreach($matches as $match) { // For each match, if there is an ELSE clause, we replace the whole block by the value in the ELSE clause
+					if (!empty($match[3])) $this->contentXml = str_replace($match[0], $match[3], $this->contentXml);
 				}
+				// Cleanup the other conditional blocks (all the others where there were no ELSE clause, we can just remove them altogether)
+				$this->contentXml = preg_replace($reg, '', $this->contentXml);
 			}
 		}
 
-		/**
-		 * Merge template variables
-		 * Called automatically for a save
-		 *
-                 * @param  string	$type		'content' or 'styles'
-		 * @return void
-		 */
-		private function _parse($type='content')
-		{
-                    // Conditionals substitution
-                    // Note: must be done before content substitution, else the variable will be replaced by its value and the conditional won't work anymore
-                    foreach($this->vars as $key => $value)
-                    {
-                        // If value is true (not 0 nor false nor null nor empty string)
-                        if($value)
-                        {
-                            // Remove the IF tag
-                            $this->contentXml = str_replace('[!-- IF '.$key.' --]', '', $this->contentXml);
-                            // Remove everything between the ELSE tag (if it exists) and the ENDIF tag
-                            $reg = '@(\[!--\sELSE\s' . $key . '\s--\](.*))?\[!--\sENDIF\s' . $key . '\s--\]@smU'; // U modifier = all quantifiers are non-greedy
-                            $this->contentXml = preg_replace($reg, '', $this->contentXml);
-                        }
-                        // Else the value is false, then two cases: no ELSE and we're done, or there is at least one place where there is an ELSE clause, then we replace it
-                        else
-                        {
-                            // Find all conditional blocks for this variable: from IF to ELSE and to ENDIF
-                            $reg = '@\[!--\sIF\s' . $key . '\s--\](.*)(\[!--\sELSE\s' . $key . '\s--\](.*))?\[!--\sENDIF\s' . $key . '\s--\]@smU'; // U modifier = all quantifiers are non-greedy
-                            preg_match_all($reg, $this->contentXml, $matches, PREG_SET_ORDER);
-                            foreach($matches as $match) { // For each match, if there is an ELSE clause, we replace the whole block by the value in the ELSE clause
-                                if (!empty($match[3])) $this->contentXml = str_replace($match[0], $match[3], $this->contentXml);
-                            }
-                            // Cleanup the other conditional blocks (all the others where there were no ELSE clause, we can just remove them altogether)
-                            $this->contentXml = preg_replace($reg, '', $this->contentXml);
-                        }
-                    }
-
-                    // Content (variable) substitution
-                    if ($type == 'content')	$this->contentXml = str_replace(array_keys($this->vars), array_values($this->vars), $this->contentXml);
-                    // Styles substitution
-                    if ($type == 'styles')	$this->stylesXml = str_replace(array_keys($this->vars), array_values($this->vars), $this->stylesXml);
-
-		}
-
-		/**
-		 * Add the merged segment to the document
-		 *
-		 * @param Segment $segment
-		 * @throws OdfException
-		 * @return odf
-		 */
-		public function mergeSegment(Segment $segment)
-		{
-			if (! array_key_exists($segment->getName(), $this->segments)) {
-				throw new OdfException($segment->getName() . 'cannot be parsed, has it been set yet ?');
+		// Content (variable) substitution
+		if ($type == 'content')	$this->contentXml = str_replace(array_keys($this->vars), array_values($this->vars), $this->contentXml);
+		// Styles substitution
+		if ($type == 'styles')	$this->stylesXml = str_replace(array_keys($this->vars), array_values($this->vars), $this->stylesXml);
+
+	}
+
+	/**
+	 * Add the merged segment to the document
+	 *
+	 * @param Segment $segment
+	 * @throws OdfException
+	 * @return odf
+	 */
+	public function mergeSegment(Segment $segment)
+	{
+		if (! array_key_exists($segment->getName(), $this->segments)) {
+			throw new OdfException($segment->getName() . 'cannot be parsed, has it been set yet ?');
+		}
+		$string = $segment->getName();
+		// $reg = '@<text:p[^>]*>\[!--\sBEGIN\s' . $string . '\s--\](.*)\[!--.+END\s' . $string . '\s--\]<\/text:p>@smU';
+		$reg = '@\[!--\sBEGIN\s' . $string . '\s--\](.*)\[!--.+END\s' . $string . '\s--\]@smU';
+		$this->contentXml = preg_replace($reg, $segment->getXmlParsed(), $this->contentXml);
+		return $this;
+	}
+
+	/**
+	 * Display all the current template variables
+	 *
+	 * @return string
+	 */
+	public function printVars()
+	{
+		return print_r('<pre>' . print_r($this->vars, true) . '</pre>', true);
+	}
+
+	/**
+	 * Display the XML content of the file from odt document
+	 * as it is at the moment
+	 *
+	 * @return string
+	 */
+	public function __toString()
+	{
+		return $this->contentXml;
+	}
+
+	/**
+	 * Display loop segments declared with setSegment()
+	 *
+	 * @return string
+	 */
+	public function printDeclaredSegments()
+	{
+		return '<pre>' . print_r(implode(' ', array_keys($this->segments)), true) . '</pre>';
+	}
+
+	/**
+	 * Declare a segment in order to use it in a loop
+	 *
+	 * @param string $segment
+	 * @throws OdfException
+	 * @return Segment
+	 */
+	public function setSegment($segment)
+	{
+		if (array_key_exists($segment, $this->segments)) {
+			return $this->segments[$segment];
+		}
+		// $reg = "#\[!--\sBEGIN\s$segment\s--\]<\/text:p>(.*)<text:p\s.*>\[!--\sEND\s$segment\s--\]#sm";
+		$reg = "#\[!--\sBEGIN\s$segment\s--\](.*)\[!--\sEND\s$segment\s--\]#sm";
+		if (preg_match($reg, html_entity_decode($this->contentXml), $m) == 0) {
+			throw new OdfException("'$segment' segment not found in the document");
+		}
+		$this->segments[$segment] = new Segment($segment, $m[1], $this);
+		return $this->segments[$segment];
+	}
+	/**
+	 * Save the odt file on the disk
+	 *
+	 * @param string $file name of the desired file
+	 * @throws OdfException
+	 * @return void
+	 */
+	public function saveToDisk($file = null)
+	{
+		if ($file !== null && is_string($file)) {
+			if (file_exists($file) && !(is_file($file) && is_writable($file))) {
+				throw new OdfException('Permission denied : can\'t create ' . $file);
 			}
-			$string = $segment->getName();
-			// $reg = '@<text:p[^>]*>\[!--\sBEGIN\s' . $string . '\s--\](.*)\[!--.+END\s' . $string . '\s--\]<\/text:p>@smU';
-			$reg = '@\[!--\sBEGIN\s' . $string . '\s--\](.*)\[!--.+END\s' . $string . '\s--\]@smU';
-			$this->contentXml = preg_replace($reg, $segment->getXmlParsed(), $this->contentXml);
-			return $this;
-		}
-
-		/**
-		 * Display all the current template variables
-		 *
-		 * @return string
-		 */
-		public function printVars()
-		{
-			return print_r('<pre>' . print_r($this->vars, true) . '</pre>', true);
+			$this->_save();
+			copy($this->tmpfile, $file);
+		} else {
+			$this->_save();
 		}
-
-		/**
-		 * Display the XML content of the file from odt document
-		 * as it is at the moment
-		 *
-		 * @return string
-		 */
-		public function __toString()
-		{
-			return $this->contentXml;
+	}
+
+	/**
+	 * Write output file onto disk
+	 *
+	 * @throws OdfException
+	 * @return void
+	 */
+	private function _save()
+	{
+		$res=$this->file->open($this->tmpfile);    // tmpfile is odt template
+		$this->_parse('content');
+		$this->_parse('styles');
+
+		if (! $this->file->addFromString('content.xml', $this->contentXml)) {
+			throw new OdfException('Error during file export addFromString');
+		}
+		if (! $this->file->addFromString('styles.xml', $this->stylesXml)) {
+			throw new OdfException('Error during file export addFromString');
+		}
+		foreach ($this->images as $imageKey => $imageValue) {
+			// Add the image inside the ODT document
+			$this->file->addFile($imageKey, 'Pictures/' . $imageValue);
+			// Add the image to the Manifest (which maintains a list of images, necessary to avoid "Corrupt ODT file. Repair?" when opening the file with LibreOffice)
+			$this->addImageToManifest($imageValue);
+		}
+		if (! $this->file->addFromString('./META-INF/manifest.xml', $this->manifestXml)) {
+			throw new OdfException('Error during file export: manifest.xml');
+		}
+		$this->file->close();
+	}
+
+	/**
+	 * Update Manifest file according to added image files
+	 *
+	 * @param string	$file		Image file to add into manifest content
+	 */
+	public function addImageToManifest($file)
+	{
+		// Get the file extension
+		$ext = substr(strrchr($val, '.'), 1);
+		// Create the correct image XML entry to add to the manifest (this is necessary because ODT format requires that we keep a list of the images in the manifest.xml)
+		$add = ' <manifest:file-entry manifest:media-type="image/'.$ext.'" manifest:full-path="Pictures/'.$file.'"/>'."\n";
+		// Append the image to the manifest
+		$this->manifestXml = str_replace('</manifest:manifest>', $add.'</manifest:manifest>', $this->manifestXml); // we replace the manifest closing tag by the image XML entry + manifest closing tag (this results in appending the data, we do not overwrite anything)
+	}
+
+	/**
+	 * Export the file as attached file by HTTP
+	 *
+	 * @param string $name (optional)
+	 * @throws OdfException
+	 * @return void
+	 */
+	public function exportAsAttachedFile($name="")
+	{
+		$this->_save();
+		if (headers_sent($filename, $linenum)) {
+			throw new OdfException("headers already sent ($filename at $linenum)");
 		}
 
-		/**
-		 * Display loop segments declared with setSegment()
-		 *
-		 * @return string
-		 */
-		public function printDeclaredSegments()
+		if( $name == "" )
 		{
-			return '<pre>' . print_r(implode(' ', array_keys($this->segments)), true) . '</pre>';
+			$name = md5(uniqid()) . ".odt";
 		}
 
-		/**
-		 * Declare a segment in order to use it in a loop
-		 *
-		 * @param string $segment
-		 * @throws OdfException
-		 * @return Segment
-		 */
-		public function setSegment($segment)
+		header('Content-type: application/vnd.oasis.opendocument.text');
+		header('Content-Disposition: attachment; filename="'.$name.'"');
+		header('Content-Length: '.filesize($this->tmpfile));
+		readfile($this->tmpfile);
+	}
+
+	/**
+	 * Convert the ODT file to PDF and export the file as attached file by HTTP
+	 * Note: you need to have JODConverter and OpenOffice or LibreOffice installed and executable on the same system as where this php script will be executed. You also need to chmod +x odt2pdf.sh
+	 *
+	 * @param string $name (optional)
+	 * @throws OdfException
+	 * @return void
+	 */
+	public function exportAsAttachedPDF($name="")
+	{
+		global $conf;
+		 
+		if( $name == "" ) $name = md5(uniqid());
+
+		//dol_syslog(get_class($this).'::exportAsAttachedPDF $name='.$name, LOG_DEBUG);
+		$this->saveToDisk($name);
+
+		$execmethod=(empty($conf->global->MAIN_EXEC_USE_POPEN)?1:2);	// 1 or 2
+		 
+		$name=str_replace('.odt', '', $name);
+		$command = DOL_DOCUMENT_ROOT.'/includes/odtphp/odt2pdf.sh '.$name;
+		//dol_syslog('$execmethod='.$execmethod.' Run command='.$command);
+		if ($execmethod == 1)
 		{
-			if (array_key_exists($segment, $this->segments)) {
-				return $this->segments[$segment];
-			}
-			// $reg = "#\[!--\sBEGIN\s$segment\s--\]<\/text:p>(.*)<text:p\s.*>\[!--\sEND\s$segment\s--\]#sm";
-			$reg = "#\[!--\sBEGIN\s$segment\s--\](.*)\[!--\sEND\s$segment\s--\]#sm";
-			if (preg_match($reg, html_entity_decode($this->contentXml), $m) == 0) {
-				throw new OdfException("'$segment' segment not found in the document");
-			}
-			$this->segments[$segment] = new Segment($segment, $m[1], $this);
-			return $this->segments[$segment];
+			exec($command, $output_arr, $retval);
 		}
-		/**
-		 * Save the odt file on the disk
-		 *
-		 * @param string $file name of the desired file
-		 * @throws OdfException
-		 * @return void
-		 */
-		public function saveToDisk($file = null)
+		if ($execmethod == 2)
 		{
-			if ($file !== null && is_string($file)) {
-				if (file_exists($file) && !(is_file($file) && is_writable($file))) {
-					throw new OdfException('Permission denied : can\'t create ' . $file);
+			$ok=0;
+			$handle = fopen($outputfile, 'w');
+			if ($handle)
+			{
+				dol_syslog("Run command ".$command);
+				$handlein = popen($command, 'r');
+				while (!feof($handlein))
+				{
+					$read = fgets($handlein);
+					fwrite($handle,$read);
+					$output_arr[]=$read;
 				}
-				$this->_save();
-				copy($this->tmpfile, $file);
-			} else {
-				$this->_save();
+				pclose($handlein);
+				fclose($handle);
 			}
+			if (! empty($conf->global->MAIN_UMASK)) @chmod($outputfile, octdec($conf->global->MAIN_UMASK));
 		}
 
-		/**
-		 * Write output file onto disk
-		 *
-		 * @throws OdfException
-		 * @return void
-		 */
-		private function _save()
+		if($retval == 0)
 		{
-			$res=$this->file->open($this->tmpfile);    // tmpfile is odt template
-			$this->_parse('content');
-			$this->_parse('styles');
-
-			if (! $this->file->addFromString('content.xml', $this->contentXml)) {
-				throw new OdfException('Error during file export addFromString');
-			}
-			if (! $this->file->addFromString('styles.xml', $this->stylesXml)) {
-				throw new OdfException('Error during file export addFromString');
-			}
-			foreach ($this->images as $imageKey => $imageValue) {
-				// Add the image inside the ODT document
-				$this->file->addFile($imageKey, 'Pictures/' . $imageValue);
-                                // Add the image to the Manifest (which maintains a list of images, necessary to avoid "Corrupt ODT file. Repair?" when opening the file with LibreOffice)
-				$this->addImageToManifest($imageValue);
-			}
-        	if (! $this->file->addFromString('./META-INF/manifest.xml', $this->manifestXml)) {
-            	throw new OdfException('Error during file export: manifest.xml');
-        	}
-			$this->file->close();
-		}
-
-		/**
-		 * Update Manifest file according to added image files
-		 *
-		 * @param string	$file		Image file to add into manifest content
-		 */
-		public function addImageToManifest($file)
-		{
-                        // Get the file extension
-		        $ext = substr(strrchr($val, '.'), 1);
-                        // Create the correct image XML entry to add to the manifest (this is necessary because ODT format requires that we keep a list of the images in the manifest.xml)
-		        $add = ' <manifest:file-entry manifest:media-type="image/'.$ext.'" manifest:full-path="Pictures/'.$file.'"/>'."\n";
-                        // Append the image to the manifest
-		        $this->manifestXml = str_replace('</manifest:manifest>', $add.'</manifest:manifest>', $this->manifestXml); // we replace the manifest closing tag by the image XML entry + manifest closing tag (this results in appending the data, we do not overwrite anything)
-		}
-
-		/**
-		 * Export the file as attached file by HTTP
-		 *
-		 * @param string $name (optional)
-		 * @throws OdfException
-		 * @return void
-		 */
-		public function exportAsAttachedFile($name="")
-		{
-			$this->_save();
+			//dol_syslog(get_class($this).'::exportAsAttachedPDF $ret_val='.$retval, LOG_DEBUG);
 			if (headers_sent($filename, $linenum)) {
 				throw new OdfException("headers already sent ($filename at $linenum)");
 			}
 
-			if( $name == "" )
-			{
-				$name = md5(uniqid()) . ".odt";
-			}
-
-			header('Content-type: application/vnd.oasis.opendocument.text');
-			header('Content-Disposition: attachment; filename="'.$name.'"');
-			header('Content-Length: '.filesize($this->tmpfile));
-			readfile($this->tmpfile);
-		}
-
-		/**
-		 * Convert the ODT file to PDF and export the file as attached file by HTTP
-		 * Note: you need to have JODConverter and OpenOffice or LibreOffice installed and executable on the same system as where this php script will be executed. You also need to chmod +x odt2pdf.sh
-		 *
-		 * @param string $name (optional)
-		 * @throws OdfException
-		 * @return void
-		 */
-		public function exportAsAttachedPDF($name="")
-                {
-                    if( $name == "" ) $name = md5(uniqid());
-
-                    $this->saveToDisk("$name.odt");
-                    exec("./odt2pdf.sh $name",$output,$ret_val);
-                    if($ret_val == 0)
-                    {
-                        if (headers_sent($filename, $linenum)) {
-                            throw new OdfException("headers already sent ($filename at $linenum)");
-                        }
-
-                        header('Content-type: application/pdf');
-                        header('Content-Disposition: attachment; filename="'.$name.'.pdf"');
-                        readfile("$name.pdf");
-                        unlink("$name.odt");
-                        unlink("$name.pdf");
-                    } else {
-                        echo "Error occured:<br>";
-                        foreach($output as $line)
-                            echo $line."<br>";
-                    }
-		}
-
-		/**
-		 * Returns a variable of configuration
-		 *
-		 * @return string The requested variable of configuration
-		 */
-		public function getConfig($configKey)
-		{
-			if (array_key_exists($configKey, $this->config)) {
-				return $this->config[$configKey];
+			if (!empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
+				header('Content-type: application/pdf');
+				header('Content-Disposition: attachment; filename="'.$name.'.pdf"');
+				readfile("$name.pdf");
 			}
-			return false;
-		}
-		/**
-		 * Returns the temporary working file
-		 *
-		 * @return string le chemin vers le fichier temporaire de travail
-		 */
-		public function getTmpfile()
-		{
-			return $this->tmpfile;
+			unlink("$name.odt");
+		} else {
+			//dol_syslog(get_class($this).'::exportAsAttachedPDF $ret_val='.$retval, LOG_DEBUG);
+			//dol_syslog(get_class($this).'::exportAsAttachedPDF $output_arr='.var_export($output_arr,true), LOG_DEBUG);
+			echo "Error occured:<br>";
+			foreach($output_arr as $line)
+				echo $line."<br>";
+			//dol_syslog(get_class($this).'::exportAsAttachedPDF ERROR $line='.$line, LOG_DEBUG);
 		}
-
-		/**
-		 * Delete the temporary file when the object is destroyed
-		 */
-		public function __destruct()
-		{
-			if (file_exists($this->tmpfile)) {
-				unlink($this->tmpfile);
-			}
-
-			if (file_exists($this->tmpdir)) {
-				$this->_rrmdir($this->tmpdir);
-				rmdir($this->tmpdir);
-			}
+	}
+
+	/**
+	 * Returns a variable of configuration
+	 *
+	 * @return string The requested variable of configuration
+	 */
+	public function getConfig($configKey)
+	{
+		if (array_key_exists($configKey, $this->config)) {
+			return $this->config[$configKey];
+		}
+		return false;
+	}
+	/**
+	 * Returns the temporary working file
+	 *
+	 * @return string le chemin vers le fichier temporaire de travail
+	 */
+	public function getTmpfile()
+	{
+		return $this->tmpfile;
+	}
+
+	/**
+	 * Delete the temporary file when the object is destroyed
+	 */
+	public function __destruct()
+	{
+		if (file_exists($this->tmpfile)) {
+			unlink($this->tmpfile);
 		}
 
-		/**
-		 * Empty the temporary working directory recursively
-		 * @param $dir the temporary working directory
-		 * @return void
-		 */
-		private function _rrmdir($dir)
-		{
-			if ($handle = opendir($dir)) {
-				while (false !== ($file = readdir($handle))) {
-					if ($file != '.' && $file != '..') {
-						if (is_dir($dir . '/' . $file)) {
-							$this->_rrmdir($dir . '/' . $file);
-							rmdir($dir . '/' . $file);
-						} else {
-							unlink($dir . '/' . $file);
-						}
+		if (file_exists($this->tmpdir)) {
+			$this->_rrmdir($this->tmpdir);
+			rmdir($this->tmpdir);
+		}
+	}
+
+	/**
+	 * Empty the temporary working directory recursively
+	 * @param $dir the temporary working directory
+	 * @return void
+	 */
+	private function _rrmdir($dir)
+	{
+		if ($handle = opendir($dir)) {
+			while (false !== ($file = readdir($handle))) {
+				if ($file != '.' && $file != '..') {
+					if (is_dir($dir . '/' . $file)) {
+						$this->_rrmdir($dir . '/' . $file);
+						rmdir($dir . '/' . $file);
+					} else {
+						unlink($dir . '/' . $file);
 					}
 				}
-				closedir($handle);
 			}
+			closedir($handle);
 		}
+	}
 }
 
 ?>
\ No newline at end of file
diff --git a/htdocs/includes/odtphp/odt2pdf.sh b/htdocs/includes/odtphp/odt2pdf.sh
old mode 100644
new mode 100755
diff --git a/htdocs/langs/en_US/bills.lang b/htdocs/langs/en_US/bills.lang
index 41b08dd399fa398b1fd4389aa2647cfbd444cdba..a76156142d6a94d0fd2969a085888d91430f2a84 100644
--- a/htdocs/langs/en_US/bills.lang
+++ b/htdocs/langs/en_US/bills.lang
@@ -311,6 +311,8 @@ PaymentConditionShortPT_ORDER=On order
 PaymentConditionPT_ORDER=On order
 PaymentConditionShortPT_5050=50-50
 PaymentConditionPT_5050=50%% in advance, 50%% on delivery
+FixAmount=Fix amount
+VarAmount=Variable amount (%% tot.)
 
 # PaymentType
 PaymentTypeVIR=Bank deposit
diff --git a/htdocs/langs/es_ES/admin.lang b/htdocs/langs/es_ES/admin.lang
index c42a026c87f88d15ff31c59bc0b18a48befbad42..ec45e7eb6a92a37fe6e93a0f46dcd07a85a42714 100644
--- a/htdocs/langs/es_ES/admin.lang
+++ b/htdocs/langs/es_ES/admin.lang
@@ -336,7 +336,7 @@ EnterRefToBuildUrl=Introduzca la referencia del objeto %s
 GetSecuredUrl=Obtener la URL calculada
 ButtonHideUnauthorized=Ocultar los botones de acciones no autorizadas en vez de mostrarlos atenuados
 TotalNumberOfActivatedModules=Número total de módulos activados: <b>%s</b>
-YouMustEnableOneModule=Debe activar al menos 1 módulo.
+YouMustEnableOneModule=Debe activar al menos un módulo.
 ProductVatMassChange=Modificar IVA en masa
 ProductVatMassChangeDesc=Esta página le permite cambiar el tipo de IVA definido en  los productos o servicios de un valor a otro. Tenga en cuenta que el cambio se lleva a cabo en masa sobre toda la base de datos.
 OldVATRates=Tasa de IVA antigua
diff --git a/htdocs/langs/es_ES/bills.lang b/htdocs/langs/es_ES/bills.lang
index ff1d75eb35893eee2b947115131ce38817104c4c..d4146ba2f4ed31e897ada42de7273d9a99e44f12 100644
--- a/htdocs/langs/es_ES/bills.lang
+++ b/htdocs/langs/es_ES/bills.lang
@@ -287,6 +287,8 @@ TotalOfTwoDiscountMustEqualsOriginal=La suma del importe de los 2 nuevos descuen
 ConfirmRemoveDiscount=¿Está seguro de querer eliminar este descuento?
 RelatedBill=Factura asociada
 RelatedBills=Facturas asociadas
+FixAmount=Importe fijo
+VarAmount=Importe variable (%% total)
 
 # PaymentConditions
 PaymentConditionShortRECEP=A la recepción
diff --git a/htdocs/langs/fr_FR/bills.lang b/htdocs/langs/fr_FR/bills.lang
index 0c87fb93f66e9ae99861feb9d682c241507b0b53..adfa9a34bdceb63be38e16102ecefae6cf278743 100644
--- a/htdocs/langs/fr_FR/bills.lang
+++ b/htdocs/langs/fr_FR/bills.lang
@@ -322,6 +322,8 @@ PaymentTypeVAD=Paiement en ligne
 PaymentTypeShortVAD=Paiement en ligne
 PaymentTypeTRA=Paiement par traite
 PaymentTypeShortTRA=Traite
+FixAmount=Montant Fixe
+VarAmount=Montant variable (%% tot.)
 
 BankDetails=Coordonnées bancaires
 BankCode=Code banque
diff --git a/htdocs/societe/consumption.php b/htdocs/societe/consumption.php
index 7c0a4c0332f251408d02d5e7d868867fc03e57d6..aff1fded6d3da1715e3a1679807733712715cb7a 100644
--- a/htdocs/societe/consumption.php
+++ b/htdocs/societe/consumption.php
@@ -295,14 +295,13 @@ if ($sql_select)
 			// Define output language
 			if (! empty($conf->global->MAIN_MULTILANGS) && ! empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE))
 			{
-				$this->fetch_thirdparty();
 				$prod = new Product($db);
 				$prod->fetch($objp->fk_product);
 
 				$outputlangs = $langs;
 				$newlang='';
 				if (empty($newlang) && GETPOST('lang_id')) $newlang=GETPOST('lang_id');
-				if (empty($newlang)) $newlang=$this->client->default_lang;
+				if (empty($newlang)) $newlang=$object->default_lang;
 				if (! empty($newlang))
 				{
 					$outputlangs = new Translate("",$conf);