diff --git a/ChangeLog b/ChangeLog
index 338a1406b8e2f0db46b8b40c05a0a132fd4625e4..0978f65863ba5bcbd139bc28cbb699f6ae3b07a5 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -41,6 +41,7 @@ Fix: [ bug #1240 ] traduction.
 Fix: [ bug #1238 ] When creating accompte with a %, free product are used for calculation.
 Fix: [ bug #1280 ] service with not end of date was tagged as expired.
 Fix: [ bug #1295 ] Error when creating an agenda extrafield with a number as reference
+Fix: [ bug #1306 ] Fatal error when adding an external calendar
 New: Added es_CL language
 
 ***** ChangeLog for 3.5 compared to 3.4.* *****
diff --git a/htdocs/admin/agenda_extsites.php b/htdocs/admin/agenda_extsites.php
index 4bb3cb8c4f3d230bc7f943c2b609ec00cd9e8e1c..b133485f8661ddfb9619b30c32ae398f5b40cbe8 100644
--- a/htdocs/admin/agenda_extsites.php
+++ b/htdocs/admin/agenda_extsites.php
@@ -1,6 +1,6 @@
 <?php
 /* Copyright (C) 2008-2011 Laurent Destailleur  <eldy@users.sourceforge.net>
- * Copyright (C) 2011-2013 Juanjo Menent        <jmenent@2byte.es>
+ * Copyright (C) 2011-2014 Juanjo Menent        <jmenent@2byte.es>
  *
  * 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
@@ -28,6 +28,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php';
 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/agenda.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
 
 if (!$user->admin)
     accessforbidden();
diff --git a/htdocs/compta/facture.php b/htdocs/compta/facture.php
index 4823bb636fcef7836a5b230bd5983152b0d5f896..63a1c14d2b15220cb71149867e2c9b91ef3eed20 100644
--- a/htdocs/compta/facture.php
+++ b/htdocs/compta/facture.php
@@ -579,14 +579,21 @@ else if ($action == 'confirm_canceled' && $confirm == 'yes')
 // Convertir en reduc
 else if ($action == 'confirm_converttoreduc' && $confirm == 'yes' && $user->rights->facture->creer)
 {
-	$db->begin();
-
 	$object->fetch($id);
 	$object->fetch_thirdparty();
 	$object->fetch_lines();
 
-	if (!empty($object->paye))	// protection against multiple submit
+	// Check if there is already a discount (protection to avoid duplicate creation when resubmit post)
+	$discountcheck=new DiscountAbsolute($db);
+	$result=$discountcheck->fetch(0,$object->id);
+
+	$canconvert=0;
+	if ($object->type == 3 && $object->paye == 1 && empty($discountcheck->id)) $canconvert=1;	// we can convert deposit into discount if deposit is payed completely and not already converted (see real condition into condition used to show button converttoreduc)
+	if ($object->type == 2 && $object->paye == 0 && empty($discountcheck->id)) $canconvert=1;	// we can convert credit note into discount if credit note is not payed back and amount of payment is 0 (see real condition into condition used to show button converttoreduc)
+	if ($canconvert)
 	{
+		$db->begin();
+
 		// Boucle sur chaque taux de tva
 		$i=0;
 		foreach($object->lines as $line)
@@ -1981,9 +1988,10 @@ if ($action == 'update_extras')
 }
 
 
+
 /*
  * View
-*/
+ */
 
 $form = new Form($db);
 $formother=new FormOther($db);
@@ -2186,6 +2194,7 @@ if ($action == 'create')
 		$options.='</option>';
 	}
 
+	// Show link for credit note
 	$facids=$facturestatic->list_qualified_avoir_invoices($soc->id);
 	if ($facids < 0)
 	{
@@ -3593,7 +3602,10 @@ else if ($id > 0 || ! empty($ref))
 			}
 
 			// 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 ((($object->type == 0 || $object->type == 1)
+				|| ($object->type == 2 && empty($discount->id))
+				|| ($object->type == 3 && empty($discount->id)))
+				 && ($object->statut == 2 || $object->statut == 3))				// A paid invoice (partially or completely)
 			{
 				if (! $objectidnext && $object->close_code != 'replaced')	// Not replaced by another invoice
 				{
@@ -3680,23 +3692,32 @@ else if ($id > 0 || ! empty($ref))
 				// 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>';
+					if ($resteapayer == 0)
+					{
+						print '<div class="inline-block divButAction"><span class="butActionRefused" title="'.$langs->trans("DisabledBecauseRemainderToPayIsZero").'">'.$langs->trans('DoPaymentBack').'</span></div>';
+					}
+					else
+					{
+						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 == 2 && $resteapayer == 0 && $user->rights->facture->creer && empty($discount->id))
+				if ($object->type == 3 && $object->paye == 1 && $resteapayer == 0 && $user->rights->facture->creer && empty($discount->id))
 				{
 					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)) )
+			// Classify paid
+			if ($object->statut == 1 && $object->paye == 0 && $user->rights->facture->paiement && (($object->type != 2 && $object->type != 3 && $resteapayer <= 0) || ($object->type == 2 && $resteapayer >= 0))
+				|| ($object->type == 3 && $object->paye == 0 && $resteapayer == 0 && $user->rights->facture->paiement && empty($discount->id))
+			)
 			{
 				print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=paid">'.$langs->trans('ClassifyPaid').'</a></div>';
 			}
diff --git a/htdocs/core/class/conf.class.php b/htdocs/core/class/conf.class.php
index 903694128f9e4c4beb74e176c633efa45a0fd1cb..957bec4708891004768c005c8e1f31bdbde6a7f8 100644
--- a/htdocs/core/class/conf.class.php
+++ b/htdocs/core/class/conf.class.php
@@ -201,6 +201,11 @@ class Conf
 		//var_dump($this->modules);
 		//var_dump($this->modules_parts['theme']);
 
+		// If you can't set timezone of your PHP, set this constant. Better is to set it to UTC.
+		// In future, this constant will be forced to 'UTC' so PHP server timezone will not have effect anymore.
+		//$this->global->MAIN_SERVER_TZ='Europe/Paris';
+		if (! empty($this->global->MAIN_SERVER_TZ) && $this->global->MAIN_SERVER_TZ != 'auto') date_default_timezone_set($this->global->MAIN_SERVER_TZ);
+
 		// Object $mc
 		if (! defined('NOREQUIREMC') && ! empty($this->multicompany->enabled))
 		{
diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php
index b6df6ff335c7e5d4acd23f0ac7ffcdfe8d5938fb..bf398c389c020b405c33d5778ac10f7617d5e569 100644
--- a/htdocs/core/lib/functions.lib.php
+++ b/htdocs/core/lib/functions.lib.php
@@ -987,9 +987,9 @@ function dol_getdate($timestamp,$fast=false)
  *	@param	int			$month			Month (1 to 12)
  *	@param	int			$day			Day (1 to 31)
  *	@param	int			$year			Year
- *	@param	int			$gm				1=Input informations are GMT values, otherwise local to server TZ
+ *	@param	int			$gm				true or 1=Input informations are GMT values, false or 0 or 'server' = local to server TZ, 'user' = local to user TZ
  *	@param	int			$check			0=No check on parameters (Can use day 32, etc...)
- *	@return	int					Date as a timestamp, '' if error
+ *	@return	int							Date as a timestamp, '' if error
  * 	@see 								dol_print_date, dol_stringtotime, dol_getdate
  */
 function dol_mktime($hour,$minute,$second,$month,$day,$year,$gm=false,$check=1)
@@ -1015,7 +1015,23 @@ function dol_mktime($hour,$minute,$second,$month,$day,$year,$gm=false,$check=1)
 
 	if (method_exists('DateTime','getTimestamp') && empty($conf->global->MAIN_OLD_DATE))
 	{
-		if (empty($gm)) $localtz = new DateTimeZone(date_default_timezone_get());
+		if (empty($gm) || $gm === 'server')
+		{
+			// If you can't set timezone of your PHP, set this constant. Better is to set it to UTC.
+			// In future, this constant will be forced to 'UTC' so PHP server timezone will not have effect anymore.
+			if (! empty($conf->global->MAIN_SERVER_TZ))
+			{
+				if ($conf->global->MAIN_SERVER_TZ != 'auto') $default_timezone=$conf->global->MAIN_SERVER_TZ;
+				else $default_timezone=@date_default_timezone_get();
+			}
+			else $default_timezone=@date_default_timezone_get();
+			$localtz = new DateTimeZone($default_timezone);
+		}
+		else if ($gm === 'user')
+		{
+			$default_timezone=(empty($_SESSION["dol_tz_string"])?'UTC':$_SESSION["dol_tz_string"]);
+			$localtz = new DateTimeZone($default_timezone);
+		}
 		else $localtz = new DateTimeZone('UTC');
 		$dt = new DateTime(null,$localtz);
 		$dt->setDate($year,$month,$day);
diff --git a/htdocs/core/modules/commande/doc/pdf_einstein.modules.php b/htdocs/core/modules/commande/doc/pdf_einstein.modules.php
index 0126edd78d43dc356f6facf5b227d41a29762793..953212748f89c99346897d9f2f215392383ac957 100644
--- a/htdocs/core/modules/commande/doc/pdf_einstein.modules.php
+++ b/htdocs/core/modules/commande/doc/pdf_einstein.modules.php
@@ -1,5 +1,5 @@
 <?php
-/* Copyright (C) 2004-2013	Laurent Destailleur	<eldy@users.sourceforge.net>
+/* Copyright (C) 2004-2014	Laurent Destailleur	<eldy@users.sourceforge.net>
  * Copyright (C) 2005-2012	Regis Houssin		<regis.houssin@capnetworks.com>
  * Copyright (C) 2008		Raphael Bertrand	<raphael.bertrand@resultic.fr>
  * Copyright (C) 2010-2013	Juanjo Menent		<jmenent@2byte.es>
@@ -109,7 +109,7 @@ class pdf_einstein extends ModelePDFCommandes
 		$this->posxdiscount=162;
 		$this->postotalht=174;
 		if (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT)) $this->posxtva=$this->posxup;
-		$this->posxpicture=$this->posxtva - 16;	// width of images
+		$this->posxpicture=$this->posxtva - (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH)?16:$conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH);	// width of images
 		if ($this->page_largeur < 210) // To work with US executive format
 		{
 			$this->posxpicture-=20;
@@ -153,7 +153,7 @@ class pdf_einstein extends ModelePDFCommandes
 		$outputlangs->load("products");
 		$outputlangs->load("orders");
 		$outputlangs->load("deliveries");
-		
+
 		if ($conf->commande->dir_output)
 		{
             $object->fetch_thirdparty();
@@ -228,6 +228,15 @@ class pdf_einstein extends ModelePDFCommandes
 						$this->atleastonediscount++;
 					}
 				}
+				if (empty($this->atleastonediscount))
+				{
+					$this->posxpicture+=($this->postotalht - $this->posxdiscount);
+					$this->posxtva+=($this->postotalht - $this->posxdiscount);
+					$this->posxup+=($this->postotalht - $this->posxdiscount);
+					$this->posxqty+=($this->postotalht - $this->posxdiscount);
+					$this->posxdiscount+=($this->postotalht - $this->posxdiscount);
+					//$this->postotalht;
+				}
 
 				// New page
 				$pdf->AddPage();
@@ -304,7 +313,7 @@ class pdf_einstein extends ModelePDFCommandes
 								$pdf->AddPage('','',true);
 								if (! empty($tplidx)) $pdf->useTemplate($tplidx);
 								if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
-								$pdf->setPage($pagenb+1);
+								$pdf->setPage($pageposafter+1);
 							}
 						}
 						else
@@ -400,6 +409,7 @@ class pdf_einstein extends ModelePDFCommandes
 					// Add line
 					if (! empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblignes - 1))
 					{
+						$pdf->setPage($pageposafter);
 						$pdf->SetLineStyle(array('dash'=>'1,1','color'=>array(210,210,210)));
 						//$pdf->SetDrawColor(190,190,200);
 						$pdf->line($this->marge_gauche, $nexY+1, $this->page_largeur - $this->marge_droite, $nexY+1);
@@ -583,20 +593,6 @@ class pdf_einstein extends ModelePDFCommandes
             $posy=$pdf->GetY()+1;
         }
 		*/
-		if (! empty($object->date_livraison))
-		{
-            $pdf->SetXY($this->marge_gauche, $posy);
-            $pdf->SetFont('','B', $default_font_size - 2);
-            $text=$outputlangs->transnoentities("DeliveryDate").':';
-            $pdf->MultiCell(80, 3, $text, 0, 'L', 0);
-            
-			$pdf->SetFont('','', $default_font_size - 2);
-			$pdf->SetXY($posxval, $posy);
-            $text=dol_print_date($object->date_livraison,'day','',$outputlangs);
-            $pdf->MultiCell(80, 3, $text, 0, 'L', 0);
-
-            $posy=$pdf->GetY()+1;
-		}
 		/* TODO
 		else if (! empty($object->availability_code))
 		{
@@ -609,7 +605,7 @@ class pdf_einstein extends ModelePDFCommandes
             $posy=$pdf->GetY()+1;
 		}*/
 
-	    // Show shipping date
+	    // Show planed date of delivery
         if ($object->date_livraison)
 		{
             $outputlangs->load("sendings");
diff --git a/htdocs/core/modules/commande/doc/pdf_proforma.modules.php b/htdocs/core/modules/commande/doc/pdf_proforma.modules.php
index 35d7dd3f9fca631763b6bec868a2532f034e801d..b6021d17c0d1922daa16cb372cdb36840bf3d71d 100644
--- a/htdocs/core/modules/commande/doc/pdf_proforma.modules.php
+++ b/htdocs/core/modules/commande/doc/pdf_proforma.modules.php
@@ -1,5 +1,5 @@
 <?php
-/* Copyright (C) 2004-2013	Laurent Destailleur	<eldy@users.sourceforge.net>
+/* Copyright (C) 2004-2014	Laurent Destailleur	<eldy@users.sourceforge.net>
  * Copyright (C) 2005-2012	Regis Houssin		<regis.houssin@capnetworks.com>
  * Copyright (C) 2008		Raphael Bertrand	<raphael.bertrand@resultic.fr>
  * Copyright (C) 2010-2013	Juanjo Menent		<jmenent@2byte.es>
@@ -109,7 +109,7 @@ class pdf_proforma extends ModelePDFCommandes
 		$this->posxdiscount=162;
 		$this->postotalht=174;
 		if (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT)) $this->posxtva=$this->posxup;
-		$this->posxpicture=$this->posxtva - 16;	// width of images
+		$this->posxpicture=$this->posxtva - (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH)?16:$conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH);	// width of images
 		if ($this->page_largeur < 210) // To work with US executive format
 		{
 			$this->posxpicture-=20;
@@ -227,6 +227,15 @@ class pdf_proforma extends ModelePDFCommandes
 						$this->atleastonediscount++;
 					}
 				}
+				if (empty($this->atleastonediscount))
+				{
+					$this->posxpicture+=($this->postotalht - $this->posxdiscount);
+					$this->posxtva+=($this->postotalht - $this->posxdiscount);
+					$this->posxup+=($this->postotalht - $this->posxdiscount);
+					$this->posxqty+=($this->postotalht - $this->posxdiscount);
+					$this->posxdiscount+=($this->postotalht - $this->posxdiscount);
+					//$this->postotalht;
+				}
 
 				// New page
 				$pdf->AddPage();
@@ -303,7 +312,7 @@ class pdf_proforma extends ModelePDFCommandes
 								$pdf->AddPage('','',true);
 								if (! empty($tplidx)) $pdf->useTemplate($tplidx);
 								if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
-								$pdf->setPage($pagenb+1);
+								$pdf->setPage($pageposafter+1);
 							}
 						}
 						else
@@ -399,6 +408,7 @@ class pdf_proforma extends ModelePDFCommandes
 					// Add line
 					if (! empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblignes - 1))
 					{
+						$pdf->setPage($pageposafter);
 						$pdf->SetLineStyle(array('dash'=>'1,1','color'=>array(210,210,210)));
 						//$pdf->SetDrawColor(190,190,200);
 						$pdf->line($this->marge_gauche, $nexY+1, $this->page_largeur - $this->marge_droite, $nexY+1);
diff --git a/htdocs/core/modules/expedition/doc/pdf_merou.modules.php b/htdocs/core/modules/expedition/doc/pdf_merou.modules.php
index fc3bd6281eb81cf7448623901878fa56f17b9974..dafff8b81ea0bc7f0ff52b465db7d9f08fef528b 100644
--- a/htdocs/core/modules/expedition/doc/pdf_merou.modules.php
+++ b/htdocs/core/modules/expedition/doc/pdf_merou.modules.php
@@ -267,6 +267,7 @@ class pdf_merou extends ModelePdfExpedition
 					// Add line
 					if (! empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblignes - 1))
 					{
+						$pdf->setPage($pageposafter);
 						$pdf->SetLineStyle(array('dash'=>'1,1','color'=>array(210,210,210)));
 						//$pdf->SetDrawColor(190,190,200);
 						$pdf->line($this->marge_gauche, $nexY+1, $this->page_largeur - $this->marge_droite, $nexY+1);
diff --git a/htdocs/core/modules/expedition/doc/pdf_rouget.modules.php b/htdocs/core/modules/expedition/doc/pdf_rouget.modules.php
index 66f36e1b84f7fa4d0fab9eaf0fef3ed79d3cbee4..d924da16785b70c523d5bf1cec6fae5ecc8c0e6d 100644
--- a/htdocs/core/modules/expedition/doc/pdf_rouget.modules.php
+++ b/htdocs/core/modules/expedition/doc/pdf_rouget.modules.php
@@ -264,6 +264,7 @@ class pdf_rouget extends ModelePdfExpedition
 					// Add line
 					if (! empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblignes - 1))
 					{
+						$pdf->setPage($pageposafter);
 						$pdf->SetLineStyle(array('dash'=>'1,1','color'=>array(210,210,210)));
 						//$pdf->SetDrawColor(190,190,200);
 						$pdf->line($this->marge_gauche, $nexY+1, $this->page_largeur - $this->marge_droite, $nexY+1);
diff --git a/htdocs/core/modules/facture/doc/pdf_crabe.modules.php b/htdocs/core/modules/facture/doc/pdf_crabe.modules.php
index 0f2ac346e695ec7b4c2342420c87118e25d6aecd..7d3c1f351543f6b7669b92870becfbdfb5348dd9 100644
--- a/htdocs/core/modules/facture/doc/pdf_crabe.modules.php
+++ b/htdocs/core/modules/facture/doc/pdf_crabe.modules.php
@@ -1,5 +1,5 @@
 <?php
-/* Copyright (C) 2004-2013	Laurent Destailleur	<eldy@users.sourceforge.net>
+/* Copyright (C) 2004-2014	Laurent Destailleur	<eldy@users.sourceforge.net>
  * Copyright (C) 2005-2012	Regis Houssin		<regis.houssin@capnetworks.com>
  * Copyright (C) 2008		Raphael Bertrand	<raphael.bertrand@resultic.fr>
  * Copyright (C) 2010-2013	Juanjo Menent		<jmenent@2byte.es>
@@ -109,7 +109,7 @@ class pdf_crabe extends ModelePDFFactures
 		$this->posxdiscount=162;
 		$this->postotalht=174;
 		if (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT)) $this->posxtva=$this->posxup;
-		$this->posxpicture=$this->posxtva - 16;	// width of images
+		$this->posxpicture=$this->posxtva - (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH)?16:$conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH);	// width of images
 		if ($this->page_largeur < 210) // To work with US executive format
 		{
 			$this->posxpicture-=20;
@@ -228,6 +228,15 @@ class pdf_crabe extends ModelePDFFactures
 						$this->atleastonediscount++;
 					}
 				}
+				if (empty($this->atleastonediscount))
+				{
+					$this->posxpicture+=($this->postotalht - $this->posxdiscount);
+					$this->posxtva+=($this->postotalht - $this->posxdiscount);
+					$this->posxup+=($this->postotalht - $this->posxdiscount);
+					$this->posxqty+=($this->postotalht - $this->posxdiscount);
+					$this->posxdiscount+=($this->postotalht - $this->posxdiscount);
+					//$this->postotalht;
+				}
 
 				// New page
 				$pdf->AddPage();
@@ -306,7 +315,7 @@ class pdf_crabe extends ModelePDFFactures
 								$pdf->AddPage('','',true);
 								if (! empty($tplidx)) $pdf->useTemplate($tplidx);
 								if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
-								$pdf->setPage($pagenb+1);
+								$pdf->setPage($pageposafter+1);
 							}
 						}
 						else
@@ -378,7 +387,7 @@ class pdf_crabe extends ModelePDFFactures
 					if ($object->remise_percent) $localtax2ligne-=($localtax2ligne*$object->remise_percent)/100;
 
 					$vatrate=(string) $object->lines[$i]->tva_tx;
-					
+
 					// Retrieve type from database for backward compatibility with old records
 					if ((! isset($localtax1_type) || $localtax1_type=='' || ! isset($localtax2_type) || $localtax2_type=='') // if tax type not defined
 					&& (! empty($localtax1_rate) || ! empty($localtax2_rate))) // and there is local tax
@@ -401,6 +410,7 @@ class pdf_crabe extends ModelePDFFactures
 					// Add line
 					if (! empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblignes - 1))
 					{
+						$pdf->setPage($pageposafter);
 						$pdf->SetLineStyle(array('dash'=>'1,1','color'=>array(210,210,210)));
 						//$pdf->SetDrawColor(190,190,200);
 						$pdf->line($this->marge_gauche, $nexY+1, $this->page_largeur - $this->marge_droite, $nexY+1);
diff --git a/htdocs/core/modules/import/import_csv.modules.php b/htdocs/core/modules/import/import_csv.modules.php
index f0766e271e5956a2ad33d3860ba1afade074aea6..667d13a0f883c9f6d4f22e6d8834d75b496ad454 100644
--- a/htdocs/core/modules/import/import_csv.modules.php
+++ b/htdocs/core/modules/import/import_csv.modules.php
@@ -250,7 +250,7 @@ class ImportCsv extends ModeleImports
 	/**
 	 * 	Return array of next record in input file.
 	 *
-	 * 	@return		Array		Array of field values. Data are UTF8 encoded. [fieldpos] => (['val']=>val, ['type']=>-1=null,0=blank,1=string)
+	 * 	@return		Array		Array of field values. Data are UTF8 encoded. [fieldpos] => (['val']=>val, ['type']=>-1=null,0=blank,1=not empty string)
 	 */
 	function import_read_record()
 	{
@@ -383,7 +383,7 @@ class ImportCsv extends ModeleImports
 					{
 						// Set $newval with value to insert and set $listvalues with sql request part for insert
 						$newval='';
-						if ($arrayrecord[($key-1)]['type'] > 0) $newval=$arrayrecord[($key-1)]['val'];    // If type of field is not null or '' but string
+						if ($arrayrecord[($key-1)]['type'] > 0) $newval=$arrayrecord[($key-1)]['val'];    // If type of field into input file is not empty string (so defined into input file), we get value
 
 						// Make some tests on $newval
 
@@ -441,41 +441,46 @@ class ImportCsv extends ModeleImports
                                 {
                                     if (empty($newval)) $newval='0';
                                 }
-                                elseif ($objimport->array_import_convertvalue[0][$val]['rule']=='getcustomercodeifnull')
+                                elseif ($objimport->array_import_convertvalue[0][$val]['rule']=='getcustomercodeifauto')
                                 {
-                                    if (empty($newval) || $newval=='auto')
+                                    if (strtolower($newval) == 'auto')
                                     {
                                         $this->thirpartyobject->get_codeclient(0,0);
                                         $newval=$this->thirpartyobject->code_client;
                                         //print 'code_client='.$newval;
                                     }
+                                    if (empty($newval)) $arrayrecord[($key-1)]['type']=-1;	// If we get empty value, we will use "null"
                                 }
-                                elseif ($objimport->array_import_convertvalue[0][$val]['rule']=='getsuppliercodeifnull')
+                                elseif ($objimport->array_import_convertvalue[0][$val]['rule']=='getsuppliercodeifauto')
                                 {
-                                    if (empty($newval) || $newval=='auto')
+                                    if (strtolower($newval) == 'auto')
                                     {
                                         $newval=$this->thirpartyobject->get_codefournisseur(0,1);
                                         $newval=$this->thirpartyobject->code_fournisseur;
                                         //print 'code_fournisseur='.$newval;
                                     }
+                                    if (empty($newval)) $arrayrecord[($key-1)]['type']=-1;	// If we get empty value, we will use "null"
                                 }
-                                elseif ($objimport->array_import_convertvalue[0][$val]['rule']=='getcustomeraccountancycodeifnull')
+                                elseif ($objimport->array_import_convertvalue[0][$val]['rule']=='getcustomeraccountancycodeifauto')
                                 {
-                                    if (empty($newval) || $newval=='auto')
+                                    if (strtolower($newval) == 'auto')
                                     {
                                         $this->thirpartyobject->get_codecompta('customer');
                                         $newval=$this->thirpartyobject->code_compta;
                                         //print 'code_compta='.$newval;
                                     }
+                                    if (empty($newval)) $arrayrecord[($key-1)]['type']=-1;	// If we get empty value, we will use "null"
                                 }
-                                elseif ($objimport->array_import_convertvalue[0][$val]['rule']=='getsupplieraccountancycodeifnull')
+                                elseif ($objimport->array_import_convertvalue[0][$val]['rule']=='getsupplieraccountancycodeifauto')
                                 {
-                                    if (empty($newval) || $newval=='auto')
+                                    if (strtolower($newval) == 'auto')
                                     {
                                         $this->thirpartyobject->get_codecompta('supplier');
                                         $newval=$this->thirpartyobject->code_compta_fournisseur;
+                                        if (empty($newval)) $arrayrecord[($key-1)]['type']=-1;	// If we get empty value, we will use "null"
                                         //print 'code_compta_fournisseur='.$newval;
                                     }
+                                    if (empty($newval)) $arrayrecord[($key-1)]['type']=-1;	// If we get empty value, we will use "null"
                                 }
 
                                 //print 'Val to use as insert is '.$newval.'<br>';
@@ -540,6 +545,7 @@ class ImportCsv extends ModeleImports
 						if ($listfields) { $listfields.=', '; $listvalues.=', '; }
 						$listfields.=$fieldname;
 
+						// Note: arrayrecord (and 'type') is filled with ->import_read_record called by import.php page before calling import_insert
 						if (empty($newval) && $arrayrecord[($key-1)]['type'] < 0)       $listvalues.=($newval=='0'?$newval:"null");
 						elseif (empty($newval) && $arrayrecord[($key-1)]['type'] == 0) $listvalues.="''";
 						else															 $listvalues.="'".$this->db->escape($newval)."'";
@@ -653,7 +659,7 @@ function cleansep($value)
 function tablewithentity($table)
 {
 	global $db;
-	
+
 	$resql=$db->DDLDescTable($table,'entity');
 	if ($resql)
 	{
@@ -662,7 +668,7 @@ function tablewithentity($table)
 		if ($obj) return 1;
 		else return 0;
 	}
-	else return -1; 
+	else return -1;
 }
 
 ?>
diff --git a/htdocs/core/modules/livraison/pdf/pdf_typhon.modules.php b/htdocs/core/modules/livraison/pdf/pdf_typhon.modules.php
index bdb35d67fbe7649a0d329972db4acad5dcfa1b90..b9d61ec10490a915c5be9414fb3368423a5e040b 100644
--- a/htdocs/core/modules/livraison/pdf/pdf_typhon.modules.php
+++ b/htdocs/core/modules/livraison/pdf/pdf_typhon.modules.php
@@ -1,5 +1,5 @@
 <?php
-/* Copyright (C) 2004-2008 Laurent Destailleur   <eldy@users.sourceforge.net>
+/* Copyright (C) 2004-2014 Laurent Destailleur   <eldy@users.sourceforge.net>
  * Copyright (C) 2005-2009 Regis Houssin         <regis.houssin@capnetworks.com>
  * Copyright (C) 2007      Franky Van Liedekerke <franky.van.liedekerke@telenet.be>
  * Copyright (C) 2008      Chiptronik
@@ -223,15 +223,24 @@ class pdf_typhon extends ModelePDFDeliveryOrder
 				$pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite);   // Left, Top, Right
 
 				/*
-				 // Positionne $this->atleastonediscount si on a au moins une remise
-				 for ($i = 0 ; $i < $nblines ; $i++)
-				 {
-				 if ($object->lines[$i]->remise_percent)
-				 {
-				 $this->atleastonediscount++;
-				 }
-				 }
-				 */
+				// Positionne $this->atleastonediscount si on a au moins une remise
+				for ($i = 0 ; $i < $nblines ; $i++)
+				{
+				 	if ($object->lines[$i]->remise_percent)
+				 	{
+				 		$this->atleastonediscount++;
+				 	}
+				}
+ 				if (empty($this->atleastonediscount))
+				{
+					$this->posxpicture+=($this->postotalht - $this->posxdiscount);
+					$this->posxtva+=($this->postotalht - $this->posxdiscount);
+					$this->posxup+=($this->postotalht - $this->posxdiscount);
+					$this->posxqty+=($this->postotalht - $this->posxdiscount);
+					$this->posxdiscount+=($this->postotalht - $this->posxdiscount);
+					//$this->postotalht;
+				}
+				*/
 
 				// New page
 				$pdf->AddPage();
@@ -307,7 +316,7 @@ class pdf_typhon extends ModelePDFDeliveryOrder
                     			$pdf->AddPage('','',true);
                     			if (! empty($tplidx)) $pdf->useTemplate($tplidx);
                     			if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
-                    			$pdf->setPage($pagenb+1);
+                    			$pdf->setPage($pageposafter+1);
                     		}
                     	}
                     	else
@@ -370,6 +379,7 @@ class pdf_typhon extends ModelePDFDeliveryOrder
 					// Add line
 					if (! empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblines - 1))
 					{
+						$pdf->setPage($pageposafter);
 						$pdf->SetLineStyle(array('dash'=>'1,1','color'=>array(210,210,210)));
 						//$pdf->SetDrawColor(190,190,200);
 						$pdf->line($this->marge_gauche, $nexY+1, $this->page_largeur - $this->marge_droite, $nexY+1);
diff --git a/htdocs/core/modules/modSociete.class.php b/htdocs/core/modules/modSociete.class.php
index ea3be87aaeed5ba34e93e1c19960808a5240b09a..96a3ee4d31bff9100154ef645c9fc3fb48d61481 100644
--- a/htdocs/core/modules/modSociete.class.php
+++ b/htdocs/core/modules/modSociete.class.php
@@ -401,14 +401,14 @@ class modSociete extends DolibarrModules
 			's.fk_typent'=>array('rule'=>'fetchidfromcodeid','classfile'=>'/core/class/ctypent.class.php','class'=>'Ctypent','method'=>'fetch','dict'=>'DictionnaryCompanyType'),
 			's.fk_pays'=>array('rule'=>'fetchidfromcodeid','classfile'=>'/core/class/cpays.class.php','class'=>'Cpays','method'=>'fetch','dict'=>'DictionnaryCountry'),
 			's.fk_stcomm'=>array('rule'=>'zeroifnull'),
-		    's.code_client'=>array('rule'=>'getcustomercodeifnull'),
-		    's.code_fournisseur'=>array('rule'=>'getsuppliercodeifnull'),
-		    's.code_compta'=>array('rule'=>'getcustomeraccountancycodeifnull'),
-		    's.code_compta_fournisseur'=>array('rule'=>'getsupplieraccountancycodeifnull')
+		    's.code_client'=>array('rule'=>'getcustomercodeifauto'),
+		    's.code_fournisseur'=>array('rule'=>'getsuppliercodeifauto'),
+		    's.code_compta'=>array('rule'=>'getcustomeraccountancycodeifauto'),
+		    's.code_compta_fournisseur'=>array('rule'=>'getsupplieraccountancycodeifauto')
 		);
 		//$this->import_convertvalue_array[$r]=array('s.fk_soc'=>array('rule'=>'lastrowid',table='t');
 		$this->import_regex_array[$r]=array('s.status'=>'^[0|1]','s.client'=>'^[0|1|2|3]','s.fournisseur'=>'^[0|1]','s.fk_typent'=>'id@'.MAIN_DB_PREFIX.'c_typent','s.datec'=>'^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]$');
-		$this->import_examplevalues_array[$r]=array('s.nom'=>"MyBigCompany",'s.status'=>"0 (closed) or 1 (active)",'s.client'=>'0 (no customer no prospect)/1 (customer)/2 (prospect)/3 (customer and prospect)','s.fournisseur'=>'0 or 1','s.datec'=>dol_print_date(dol_now(),'%Y-%m-%d'),'s.code_client'=>"CU01-0001 or auto",'s.code_fournisseur'=>"SU01-0001 or auto",'s.address'=>"61 jump street",'s.zip'=>"123456",'s.town'=>"Big town",'s.fk_pays'=>'US, FR, DE...','s.phone'=>"0101010101",'s.fax'=>"0101010102",'s.url'=>"http://mycompany.com",'s.email'=>"test@mycompany.com",'s.siret'=>"",'s.siren'=>"",'s.ape'=>"",'s.idprof4'=>"",'s.tva_intra'=>"FR0123456789",'s.capital'=>"10000",'s.note_private'=>"This is an example of private note for record",'s.note_public'=>"This is an example of public note for record",'s.fk_typent'=>"2",'s.fk_effectif'=>"3","s.fk_forme_juridique"=>"1",'s.fk_prospectlevel'=>'PL_MEDIUM','s.fk_stcomm'=>'0','s.default_lang'=>'en_US','s.barcode'=>'123456789');
+		$this->import_examplevalues_array[$r]=array('s.nom'=>"MyBigCompany",'s.status'=>"0 (closed) or 1 (active)",'s.client'=>'0 (no customer no prospect)/1 (customer)/2 (prospect)/3 (customer and prospect)','s.fournisseur'=>'0 or 1','s.datec'=>dol_print_date(dol_now(),'%Y-%m-%d'),'s.code_client'=>"CU01-0001 or empty or 'auto'",'s.code_fournisseur'=>"SU01-0001 or empty or 'auto'",'s.address'=>"61 jump street",'s.zip'=>"123456",'s.town'=>"Big town",'s.fk_pays'=>'US, FR, DE...','s.phone'=>"0101010101",'s.fax'=>"0101010102",'s.url'=>"http://mycompany.com",'s.email'=>"test@mycompany.com",'s.siret'=>"",'s.siren'=>"",'s.ape'=>"",'s.idprof4'=>"",'s.tva_intra'=>"FR0123456789",'s.capital'=>"10000",'s.note_private'=>"This is an example of private note for record",'s.note_public'=>"This is an example of public note for record",'s.fk_typent'=>"2",'s.fk_effectif'=>"3","s.fk_forme_juridique"=>"1",'s.fk_prospectlevel'=>'PL_MEDIUM','s.fk_stcomm'=>'0','s.default_lang'=>'en_US','s.barcode'=>'123456789');
 
 		// Import list of contact and attributes
 		$r++;
diff --git a/htdocs/core/modules/project/pdf/pdf_baleine.modules.php b/htdocs/core/modules/project/pdf/pdf_baleine.modules.php
index cca049cba920c0d88e9d6d9f8d2767eb36ec8088..881b112688ecb9e2ab3e403a5d779a6c1f2b2714 100644
--- a/htdocs/core/modules/project/pdf/pdf_baleine.modules.php
+++ b/htdocs/core/modules/project/pdf/pdf_baleine.modules.php
@@ -222,12 +222,15 @@ class pdf_baleine extends ModelePDFProjects
 					$pdf->MultiCell(20, 3, $dateend, 0, 'L');
 
 
+					$pageposafter=$pdf->getPage();
+
 					$pdf->SetFont('','', $default_font_size - 1);   // On repositionne la police par defaut
 					$nexY = $pdf->GetY();
 
 					// Add line
 					if (! empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblignes - 1))
 					{
+						$pdf->setPage($pageposafter);
 						$pdf->SetLineStyle(array('dash'=>'1,1','color'=>array(210,210,210)));
 						//$pdf->SetDrawColor(190,190,200);
 						$pdf->line($this->marge_gauche, $nexY+1, $this->page_largeur - $this->marge_droite, $nexY+1);
diff --git a/htdocs/core/modules/propale/doc/pdf_azur.modules.php b/htdocs/core/modules/propale/doc/pdf_azur.modules.php
index fbe3fb98bbfa8bada08f35a9ce90ca9467768fe4..4aea9af7085b847ac914dd15c2db8f77e2cc968a 100644
--- a/htdocs/core/modules/propale/doc/pdf_azur.modules.php
+++ b/htdocs/core/modules/propale/doc/pdf_azur.modules.php
@@ -1,5 +1,5 @@
 <?php
-/* Copyright (C) 2004-2013 Laurent Destailleur  <eldy@users.sourceforge.net>
+/* Copyright (C) 2004-2014 Laurent Destailleur  <eldy@users.sourceforge.net>
  * Copyright (C) 2005-2012 Regis Houssin        <regis.houssin@capnetworks.com>
  * Copyright (C) 2008      Raphael Bertrand     <raphael.bertrand@resultic.fr>
  * Copyright (C) 2010-2013 Juanjo Menent	    <jmenent@2byte.es>
@@ -153,7 +153,7 @@ class pdf_azur extends ModelePDFPropales
 		$outputlangs->load("products");
 
 		$nblignes = count($object->lines);
-		
+
 		// Loop on each lines to detect if there is at least one image to show
 		$realpatharray=array();
 		if (! empty($conf->global->MAIN_GENERATE_PROPOSALS_WITH_PICTURE))
@@ -161,7 +161,7 @@ class pdf_azur extends ModelePDFPropales
 			for ($i = 0 ; $i < $nblignes ; $i++)
 			{
 				if (empty($object->lines[$i]->fk_product)) continue;
-				
+
 				$objphoto = new Product($this->db);
 				$objphoto->fetch($object->lines[$i]->fk_product);
 
@@ -185,7 +185,7 @@ class pdf_azur extends ModelePDFPropales
 		if ($conf->propal->dir_output)
 		{
 			$object->fetch_thirdparty();
-			
+
 			// $deja_regle = 0;
 
 			// Definition of $dir and $file
@@ -254,6 +254,15 @@ class pdf_azur extends ModelePDFPropales
 						$this->atleastonediscount++;
 					}
 				}
+				if (empty($this->atleastonediscount))
+				{
+					$this->posxpicture+=($this->postotalht - $this->posxdiscount);
+					$this->posxtva+=($this->postotalht - $this->posxdiscount);
+					$this->posxup+=($this->postotalht - $this->posxdiscount);
+					$this->posxqty+=($this->postotalht - $this->posxdiscount);
+					$this->posxdiscount+=($this->postotalht - $this->posxdiscount);
+					//$this->postotalht;
+				}
 
 				// New page
 				$pdf->AddPage();
@@ -320,7 +329,7 @@ class pdf_azur extends ModelePDFPropales
 						$pdf->AddPage('','',true);
 						if (! empty($tplidx)) $pdf->useTemplate($tplidx);
 						if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
-						$pdf->setPage($pagenb+1);
+						$pdf->setPage($pageposbefore+1);
 
 						$curY = $tab_top_newpage;
 						$showpricebeforepagebreak=0;
@@ -358,7 +367,7 @@ class pdf_azur extends ModelePDFPropales
 								$pdf->AddPage('','',true);
 								if (! empty($tplidx)) $pdf->useTemplate($tplidx);
 								if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
-								$pdf->setPage($pagenb+1);
+								$pdf->setPage($pageposafter+1);
 							}
 						}
 						else
@@ -375,6 +384,7 @@ class pdf_azur extends ModelePDFPropales
 
 					$nexY = $pdf->GetY();
 					$pageposafter=$pdf->getPage();
+
 					$pdf->setPage($pageposbefore);
 					$pdf->setTopMargin($this->marge_haute);
 					$pdf->setPageOrientation('', 1, 0);	// The only function to edit the bottom margin of current page to set it.
@@ -456,6 +466,7 @@ class pdf_azur extends ModelePDFPropales
 					// Add line
 					if (! empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblignes - 1))
 					{
+						$pdf->setPage($pageposafter);
 						$pdf->SetLineStyle(array('dash'=>'1,1','color'=>array(210,210,210)));
 						//$pdf->SetDrawColor(190,190,200);
 						$pdf->line($this->marge_gauche, $nexY+1, $this->page_largeur - $this->marge_droite, $nexY+1);
diff --git a/htdocs/core/modules/supplier_invoice/pdf/pdf_canelle.modules.php b/htdocs/core/modules/supplier_invoice/pdf/pdf_canelle.modules.php
index ccc3ed8c17b745dce133c16999ae4296e37e43d8..4ecaa978123572807b54b1a74c7603bdf085b1c1 100644
--- a/htdocs/core/modules/supplier_invoice/pdf/pdf_canelle.modules.php
+++ b/htdocs/core/modules/supplier_invoice/pdf/pdf_canelle.modules.php
@@ -1,6 +1,6 @@
 <?php
 /* Copyright (C) 2010-2011      Juanjo Menent        <jmenent@2byte.es>
- * Copyright (C) 2010-2012 		Laurent Destailleur  <eldy@users.sourceforge.net>
+ * Copyright (C) 2010-2014 		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
@@ -58,7 +58,7 @@ class pdf_canelle extends ModelePDFSuppliersInvoices
 	 *	Constructor
 	 *
 	 *  @param	DoliDB		$db     	Database handler
-	 *  @param	Societe		$object		Supplier invoice
+	 *  @param	Object		$object		Supplier invoice
 	 */
 	function __construct($db,$object)
 	{
@@ -105,7 +105,7 @@ class pdf_canelle extends ModelePDFSuppliersInvoices
 		$this->posxdiscount=162;
 		$this->postotalht=174;
 		//if (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT)) $this->posxtva=$this->posxup;
-		$this->posxpicture=$this->posxtva - 16;	// width of images
+		$this->posxpicture=$this->posxtva - (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH)?16:$conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH);	// width of images
 		if ($this->page_largeur < 210) // To work with US executive format
 		{
 			$this->posxpicture-=20;
@@ -225,6 +225,15 @@ class pdf_canelle extends ModelePDFSuppliersInvoices
                         $this->atleastonediscount++;
                     }
                 }
+				if (empty($this->atleastonediscount))
+				{
+					$this->posxpicture+=($this->postotalht - $this->posxdiscount);
+					$this->posxtva+=($this->postotalht - $this->posxdiscount);
+					$this->posxup+=($this->postotalht - $this->posxdiscount);
+					$this->posxqty+=($this->postotalht - $this->posxdiscount);
+					$this->posxdiscount+=($this->postotalht - $this->posxdiscount);
+					//$this->postotalht;
+				}
 
                 // New page
 				$pdf->AddPage();
@@ -279,7 +288,39 @@ class pdf_canelle extends ModelePDFSuppliersInvoices
 
 					// Description of product line
 					$curX = $this->posxdesc-1;
-                    pdf_writelinedesc($pdf,$object,$i,$outputlangs,$this->posxtva-$curX,3,$curX,$curY,$hideref,$hidedesc,1);
+					$showpricebeforepagebreak=1;
+
+					$pdf->startTransaction();
+					pdf_writelinedesc($pdf,$object,$i,$outputlangs,$this->posxtva-$curX,3,$curX,$curY,$hideref,$hidedesc,1);
+					$pageposafter=$pdf->getPage();
+					if ($pageposafter > $pageposbefore)	// There is a pagebreak
+					{
+						$pdf->rollbackTransaction(true);
+						$pageposafter=$pageposbefore;
+						//print $pageposafter.'-'.$pageposbefore;exit;
+						$pdf->setPageOrientation('', 1, $heightforfooter);	// The only function to edit the bottom margin of current page to set it.
+						pdf_writelinedesc($pdf,$object,$i,$outputlangs,$this->posxtva-$curX,4,$curX,$curY,$hideref,$hidedesc);
+						$posyafter=$pdf->GetY();
+						if ($posyafter > ($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot)))	// There is no space left for total+free text
+						{
+							if ($i == ($nblignes-1))	// No more lines, and no space left to show total, so we create a new page
+							{
+								$pdf->AddPage('','',true);
+								if (! empty($tplidx)) $pdf->useTemplate($tplidx);
+								if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
+								$pdf->setPage($pageposafter+1);
+							}
+						}
+						else
+						{
+							// We found a page break
+							$showpricebeforepagebreak=0;
+						}
+					}
+					else	// No pagebreak
+					{
+						$pdf->commitTransaction();
+					}
 
 					$nexY = $pdf->GetY();
                     $pageposafter=$pdf->getPage();
@@ -288,7 +329,7 @@ class pdf_canelle extends ModelePDFSuppliersInvoices
 					$pdf->setPageOrientation('', 1, 0);	// The only function to edit the bottom margin of current page to set it.
 
 					// We suppose that a too long description is moved completely on next page
-					if ($pageposafter > $pageposbefore) {
+					if ($pageposafter > $pageposbefore && empty($showpricebeforepagebreak)) {
 						$pdf->setPage($pageposafter); $curY = $tab_top_newpage;
 					}
 
@@ -299,7 +340,7 @@ class pdf_canelle extends ModelePDFSuppliersInvoices
                     {
     					$vat_rate = pdf_getlinevatrate($object, $i, $outputlangs, $hidedetails);
                         $pdf->SetXY($this->posxtva, $curY);
-	       				$pdf->MultiCell($this->posxup-$this->posxtva-0.8, 3, $vat_rate, 0, 'R');
+	       				$pdf->MultiCell($this->posxup-$this->posxtva-1, 3, $vat_rate, 0, 'R');
                     }
 
 					// Unit price before discount
@@ -320,7 +361,7 @@ class pdf_canelle extends ModelePDFSuppliersInvoices
 					// Total HT line
                     $total_excl_tax = pdf_getlinetotalexcltax($object, $i, $outputlangs);
                     $pdf->SetXY($this->postotalht, $curY);
-                    $pdf->MultiCell(26, 3, $total_excl_tax, 0, 'R', 0);
+                    $pdf->MultiCell($this->page_largeur-$this->marge_droite-$this->postotalht, 3, $total_excl_tax, 0, 'R', 0);
 
 					// Collecte des totaux par valeur de tva dans $this->tva["taux"]=total_tva
 					$tvaligne=$object->lines[$i]->total_tva;
@@ -342,6 +383,7 @@ class pdf_canelle extends ModelePDFSuppliersInvoices
 					// Add line
 					if (! empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblignes - 1))
 					{
+						$pdf->setPage($pageposafter);
 						$pdf->SetLineStyle(array('dash'=>'1,1','color'=>array(210,210,210)));
 						//$pdf->SetDrawColor(190,190,200);
 						$pdf->line($this->marge_gauche, $nexY+1, $this->page_largeur - $this->marge_droite, $nexY+1);
@@ -366,6 +408,7 @@ class pdf_canelle extends ModelePDFSuppliersInvoices
 						$pagenb++;
 						$pdf->setPage($pagenb);
 						$pdf->setPageOrientation('', 1, 0);	// The only function to edit the bottom margin of current page to set it.
+						if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
 					}
 					if (isset($object->lines[$i+1]->pagebreak) && $object->lines[$i+1]->pagebreak)
 					{
@@ -382,6 +425,7 @@ class pdf_canelle extends ModelePDFSuppliersInvoices
 						$pdf->AddPage();
 						if (! empty($tplidx)) $pdf->useTemplate($tplidx);
 						$pagenb++;
+						if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
 					}
 				}
 
diff --git a/htdocs/core/modules/supplier_order/pdf/pdf_muscadet.modules.php b/htdocs/core/modules/supplier_order/pdf/pdf_muscadet.modules.php
index efa93e17aecda1e9af7f80f3214eb7a2fece2682..cf8af3e6e7c8cbb219533b17ce9d490ba2b42844 100644
--- a/htdocs/core/modules/supplier_order/pdf/pdf_muscadet.modules.php
+++ b/htdocs/core/modules/supplier_order/pdf/pdf_muscadet.modules.php
@@ -1,5 +1,5 @@
 <?php
-/* Copyright (C) 2004-2013 Laurent Destailleur   <eldy@users.sourceforge.net>
+/* Copyright (C) 2004-2014 Laurent Destailleur   <eldy@users.sourceforge.net>
  * Copyright (C) 2005-2011 Regis Houssin         <regis.houssin@capnetworks.com>
  * Copyright (C) 2007      Franky Van Liedekerke <franky.van.liedekerke@telenet.be>
  * Copyright (C) 2010-2013 Juanjo Menent         <jmenent@2byte.es>
@@ -110,7 +110,7 @@ class pdf_muscadet extends ModelePDFSuppliersOrders
 		$this->posxdiscount=162;
 		$this->postotalht=174;
 		//if (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT)) $this->posxtva=$this->posxup;
-		$this->posxpicture=$this->posxtva - 16;	// width of images
+		$this->posxpicture=$this->posxtva - (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH)?16:$conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH);	// width of images
 		if ($this->page_largeur < 210) // To work with US executive format
 		{
 			$this->posxpicture-=20;
@@ -233,6 +233,15 @@ class pdf_muscadet extends ModelePDFSuppliersOrders
 						$this->atleastonediscount++;
 					}
 				}
+				if (empty($this->atleastonediscount))
+				{
+					$this->posxpicture+=($this->postotalht - $this->posxdiscount);
+					$this->posxtva+=($this->postotalht - $this->posxdiscount);
+					$this->posxup+=($this->postotalht - $this->posxdiscount);
+					$this->posxqty+=($this->postotalht - $this->posxdiscount);
+					$this->posxdiscount+=($this->postotalht - $this->posxdiscount);
+					//$this->postotalht;
+				}
 
 				// New page
 				$pdf->AddPage();
@@ -307,7 +316,7 @@ class pdf_muscadet extends ModelePDFSuppliersOrders
 								$pdf->AddPage('','',true);
 								if (! empty($tplidx)) $pdf->useTemplate($tplidx);
 								if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
-								$pdf->setPage($pagenb+1);
+								$pdf->setPage($pageposafter+1);
 							}
 						}
 						else
@@ -401,6 +410,7 @@ class pdf_muscadet extends ModelePDFSuppliersOrders
 					// Add line
 					if (! empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblignes - 1))
 					{
+						$pdf->setPage($pageposafter);
 						$pdf->SetLineStyle(array('dash'=>'1,1','color'=>array(210,210,210)));
 						//$pdf->SetDrawColor(190,190,200);
 						$pdf->line($this->marge_gauche, $nexY+1, $this->page_largeur - $this->marge_droite, $nexY+1);
diff --git a/htdocs/install/mysql/migration/repair.sql b/htdocs/install/mysql/migration/repair.sql
index e656799eb1fd4b1862e319aa229f0f030597daf2..0495171a9d0ed5ed6471844fe91661af360eaa56 100644
--- a/htdocs/install/mysql/migration/repair.sql
+++ b/htdocs/install/mysql/migration/repair.sql
@@ -6,6 +6,11 @@
 
 -- Requests to clean corrupted database
 
+-- delete foreign key that should never exists
+ALTER TABLE llx_propal DROP FOREIGN KEY fk_propal_fk_currency;
+ALTER TABLE llx_commande DROP FOREIGN KEY fk_commande_fk_currency;
+ALTER TABLE llx_facture DROP FOREIGN KEY fk_facture_fk_currency;
+
 delete from llx_facturedet where fk_facture in (select rowid from llx_facture where facnumber in ('(PROV)','ErrorBadMask'));
 delete from llx_facture where facnumber in ('(PROV)','ErrorBadMask');
 delete from llx_commandedet where fk_commande in (select rowid from llx_commande where ref in ('(PROV)','ErrorBadMask'));
diff --git a/test/phpunit/Example_import_company_1.csv b/test/phpunit/Example_import_company_1.csv
index 34f99a6b728f80838e143a809d549b7f5e2c4f54..7ba7a797317825dd3f0fc47478f038a036a6ad56 100755
--- a/test/phpunit/Example_import_company_1.csv
+++ b/test/phpunit/Example_import_company_1.csv
@@ -1,2 +1,3 @@
 "Name* (s.nom)";"Status (s.status)";"Customer* (s.client)";"Supplier* (s.fournisseur)";"DateCreation (s.datec)";"CustomerCode (s.code_client)";"SupplierCode (s.code_fournisseur)";"Address (s.address)";"Zip (s.cp)";"Town (s.ville)";"Phone (s.tel)";"Fax (s.fax)";"Url (s.url)";"Email (s.email)";"IdProf1 (s.siret)";"IdProf2 (s.siren)";"IdProf3 (s.ape)";"IdProf4 (s.idprof4)";"VATIntraShort (s.tva_intra)";"Capital (s.capital)";"Note (s.note)";"ThirdPartyType (s.fk_typent)";"Effectif (s.fk_effectif)";"JuridicalStatus (s.fk_forme_juridique)";"ProspectLevel (s.fk_prospectlevel)";"ProspectStatus (s.fk_stcomm)";"DefaultLanguage (s.default_lang)";"BarCode (s.barcode)"
-"MyBigCompanyImport1";1;3;1;01/01/00;"CU01-0001";"SU01-0001";"61 jump street";123456;"Big town";101010101;101010102;"http://mycompany.com";"test@mycompany.com";;;;;"FR0123456789";10000;"This is an example of note for record";2;3;1;"PL_MEDIUM";1;"en_US";123456789
+"MyBigCompanyImport1";1;3;1;01/01/00;"CU01-0001";"SU01-0001";"61 jump street";123456;"Big town";101010101;101010111;"http://mycompany.com";"test@mycompany.com";;;;;"FR0123456781";10000;"This is an example of note for record 1";2;3;1;"PL_MEDIUM";1;"en_US";123456781
+"MyBigCompanyImport2";1;3;1;01/01/00;"auto";;"62 jump street";123456;"Big town";101010102;101010112;"http://mycompany2.com";"test@mycompany2.com";;;;;"FR0123456782";10000;"This is an example of note for record 2";2;3;1;"PL_MEDIUM";1;"en_US";auto
diff --git a/test/phpunit/FilesLibTest.php b/test/phpunit/FilesLibTest.php
index d38f73326b2b27e71f82f7bfe7405a96c68b1264..1e8d91ed08d13ad94c342511a4b1c062e1bb743c 100644
--- a/test/phpunit/FilesLibTest.php
+++ b/test/phpunit/FilesLibTest.php
@@ -162,7 +162,7 @@ class FilesLibTest extends PHPUnit_Framework_TestCase
 		$file=dirname(__FILE__).'/Example_import_company_1.csv';
 		$result=dol_count_nb_of_line($file);
     	print __METHOD__." result=".$result."\n";
-		$this->assertEquals(2,$result);
+		$this->assertEquals(3,$result);
 
 		return $result;
     }
diff --git a/test/phpunit/ImportTest.php b/test/phpunit/ImportTest.php
index 378031be257bb8f2d8c77049ab4c6f3f408b2e9d..86d23a850e176049a9ba0684b61a1ca682b75f3b 100755
--- a/test/phpunit/ImportTest.php
+++ b/test/phpunit/ImportTest.php
@@ -125,7 +125,10 @@ class ImportTest extends PHPUnit_Framework_TestCase
     {
         $file=dirname(__FILE__).'/Example_import_company_1.csv';
 
-        //if (! preg_match('/^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]$/i','2012-03-23')) print 'eeeeeeeeeeee';
+        // TODO
+        // Run import on file and check the record with field "auto" are filled
+        // according to option
+
 
 		return true;
     }