diff --git a/htdocs/adherents/card_subscriptions.php b/htdocs/adherents/card_subscriptions.php
index d1787ad7ae72b9f7afb838e208b9652417e05b4a..491cbcf8b79bcf6246c1c14fa231168302a0d55e 100644
--- a/htdocs/adherents/card_subscriptions.php
+++ b/htdocs/adherents/card_subscriptions.php
@@ -165,93 +165,93 @@ if ($user->rights->adherent->cotisation->creer && $_POST["action"] == 'cotisatio
 
     $langs->load("banks");
 
-	$result=$adh->fetch($rowid);
-	$result=$adht->fetch($adh->typeid);
-
-	// Subscription informations
-	$datecotisation=0;
-	$datesubend=0;
-	if ($_POST["reyear"] && $_POST["remonth"] && $_POST["reday"])
-	{
-		$datecotisation=dol_mktime(0, 0, 0, $_POST["remonth"], $_POST["reday"], $_POST["reyear"]);
-	}
-	if ($_POST["endyear"] && $_POST["endmonth"] && $_POST["endday"])
-	{
-		$datesubend=dol_mktime(0, 0, 0, $_POST["endmonth"], $_POST["endday"], $_POST["endyear"]);
-	}
-	$cotisation=$_POST["cotisation"];	// Amount of subscription
-	$label=$_POST["label"];
-
-	if (! $datecotisation)
-	{
-	    $error++;
-		$errmsg=$langs->trans("BadDateFormat");
-		$action='addsubscription';
-	}
-	if (! $datesubend)
-	{
-		$datesubend=dol_time_plus_duree(dol_time_plus_duree($datecotisation,$defaultdelay,$defaultdelayunit),-1,'d');
-	}
-
-	// Payment informations
-	$accountid=$_POST["accountid"];
-	$operation=$_POST["operation"];	// Payment mode
-	$num_chq=$_POST["num_chq"];
-	$emetteur_nom=$_POST["chqemetteur"];
-	$emetteur_banque=$_POST["chqbank"];
+    $result=$adh->fetch($rowid);
+    $result=$adht->fetch($adh->typeid);
+
+    // Subscription informations
+    $datecotisation=0;
+    $datesubend=0;
+    if ($_POST["reyear"] && $_POST["remonth"] && $_POST["reday"])
+    {
+        $datecotisation=dol_mktime(0, 0, 0, $_POST["remonth"], $_POST["reday"], $_POST["reyear"]);
+    }
+    if ($_POST["endyear"] && $_POST["endmonth"] && $_POST["endday"])
+    {
+        $datesubend=dol_mktime(0, 0, 0, $_POST["endmonth"], $_POST["endday"], $_POST["endyear"]);
+    }
+    $cotisation=$_POST["cotisation"];	// Amount of subscription
+    $label=$_POST["label"];
+
+    if (! $datecotisation)
+    {
+        $error++;
+        $errmsg=$langs->trans("BadDateFormat");
+        $action='addsubscription';
+    }
+    if (! $datesubend)
+    {
+        $datesubend=dol_time_plus_duree(dol_time_plus_duree($datecotisation,$defaultdelay,$defaultdelayunit),-1,'d');
+    }
+
+    // Payment informations
+    $accountid=$_POST["accountid"];
+    $operation=$_POST["operation"];	// Payment mode
+    $num_chq=$_POST["num_chq"];
+    $emetteur_nom=$_POST["chqemetteur"];
+    $emetteur_banque=$_POST["chqbank"];
     $option=$_POST["paymentsave"];
     if (empty($option)) $option='none';
 
-	// Check if a payment is mandatory or not
-	if (! $error && $adht->cotisation)	// Type adherent soumis a cotisation
-	{
-		if (! is_numeric($_POST["cotisation"]))
-		{
-			// If field is '' or not a numeric value
-			$errmsg=$langs->trans("ErrorFieldRequired",$langs->transnoentities("Amount"));
+    // Check if a payment is mandatory or not
+    if (! $error && $adht->cotisation)	// Type adherent soumis a cotisation
+    {
+        if (! is_numeric($_POST["cotisation"]))
+        {
+            // If field is '' or not a numeric value
+            $errmsg=$langs->trans("ErrorFieldRequired",$langs->transnoentities("Amount"));
             $error++;
-			$action='addsubscription';
-		}
-		else
-		{
-			if ($conf->banque->enabled && $_POST["paymentsave"] != 'none')
-			{
-			    if ($_POST["cotisation"])
-				{
-					if (! $_POST["label"])     $errmsg=$langs->trans("ErrorFieldRequired",$langs->transnoentities("Label"));
-					if (! $_POST["operation"]) $errmsg=$langs->trans("ErrorFieldRequired",$langs->transnoentities("PaymentMode"));
-					if (! $_POST["accountid"]) $errmsg=$langs->trans("ErrorFieldRequired",$langs->transnoentities("FinancialAccount"));
-				}
-				else
-				{
-					if ($_POST["accountid"])   $errmsg=$langs->trans("ErrorDoNotProvideAccountsIfNullAmount");
-				}
-				if ($errmsg) $action='addsubscription';
-			}
-		}
-	}
-
-	if (! $error && $action=='cotisation')
-	{
-		$db->begin();
-
-		$crowid=$adh->cotisation($datecotisation, $cotisation, $accountid, $operation, $label, $num_chq, $emetteur_nom, $emetteur_banque, $datesubend, $option);
-
-		if ($crowid <= 0)
-		{
-		    $error++;
-		    $errmsg=$adh->error;
-		}
-
-		if (! $error)
-		{
-		    if ($option == 'bankviainvoice' || $option == 'invoiceonly')
-		    {
+            $action='addsubscription';
+        }
+        else
+        {
+            if ($conf->banque->enabled && $_POST["paymentsave"] != 'none')
+            {
+                if ($_POST["cotisation"])
+                {
+                    if (! $_POST["label"])     $errmsg=$langs->trans("ErrorFieldRequired",$langs->transnoentities("Label"));
+                    if (! $_POST["operation"]) $errmsg=$langs->trans("ErrorFieldRequired",$langs->transnoentities("PaymentMode"));
+                    if (! $_POST["accountid"]) $errmsg=$langs->trans("ErrorFieldRequired",$langs->transnoentities("FinancialAccount"));
+                }
+                else
+                {
+                    if ($_POST["accountid"])   $errmsg=$langs->trans("ErrorDoNotProvideAccountsIfNullAmount");
+                }
+                if ($errmsg) $action='addsubscription';
+            }
+        }
+    }
+
+    if (! $error && $action=='cotisation')
+    {
+        $db->begin();
+
+        $crowid=$adh->cotisation($datecotisation, $cotisation, $accountid, $operation, $label, $num_chq, $emetteur_nom, $emetteur_banque, $datesubend, $option);
+
+        if ($crowid <= 0)
+        {
+            $error++;
+            $errmsg=$adh->error;
+        }
+
+        if (! $error)
+        {
+            if ($option == 'bankviainvoice' || $option == 'invoiceonly')
+            {
                 // If option choosed, we create invoice
                 require_once(DOL_DOCUMENT_ROOT."/compta/facture/class/facture.class.php");
                 require_once(DOL_DOCUMENT_ROOT."/compta/facture/class/paymentterm.class.php");
 
-    		    $invoice=new Facture($db);
+                $invoice=new Facture($db);
                 $customer=new Societe($db);
                 $result=$customer->fetch($adh->fk_soc);
                 if ($result <= 0)
@@ -265,13 +265,13 @@ if ($user->rights->adherent->cotisation->creer && $_POST["action"] == 'cotisatio
                 $invoice->cond_reglement_id=$customer->cond_reglement_id;
                 if (empty($invoice->cond_reglement_id))
                 {
-                	$paymenttermstatic=new PaymentTerm($db);
-                	$invoice->cond_reglement_id=$paymenttermstatic->getDefaultId();
-					if (empty($invoice->cond_reglement_id))
-					{
-						$error++;
-						$errmsg='ErrorNoPaymentTermRECEPFound';
-					}
+                    $paymenttermstatic=new PaymentTerm($db);
+                    $invoice->cond_reglement_id=$paymenttermstatic->getDefaultId();
+                    if (empty($invoice->cond_reglement_id))
+                    {
+                        $error++;
+                        $errmsg='ErrorNoPaymentTermRECEPFound';
+                    }
                 }
                 $invoice->socid=$adh->fk_soc;
                 $invoice->date=$datecotisation;
@@ -294,32 +294,60 @@ if ($user->rights->adherent->cotisation->creer && $_POST["action"] == 'cotisatio
                     $error++;
                 }
 
+                // Validate invoice
                 $result=$invoice->validate($user);
 
-                 if ($option == 'bankviainvoice')
-                 {
+                if ($option == 'bankviainvoice')
+                {
                     // Now we add payment
-                    // TODO
-
-
-                 }
-		    }
-		}
-
-		if (! $error)
-		{
-			$db->commit();
-		}
-		else
-		{
-			$db->rollback();
-			$errmsg=$adh->error;
-			$action = 'addsubscription';
-		}
-
-		// Send email
-		if (! $error)
-		{
+                    require_once(DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php');
+                    require_once(DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php');
+
+                    // Creation de la ligne paiement
+                    $amounts[$invoice->id] = price2num($cotisation);
+                    $paiement = new Paiement($db);
+                    $paiement->datepaye     = $datecotisation;
+                    $paiement->amounts      = $amounts;
+                    $paiement->paiementid   = $operation;
+                    $paiement->num_paiement = $num_chq;
+                    $paiement->note         = $label;
+
+                    if (! $error)
+                    {
+                        $paiement_id = $paiement->create($user);
+                        if (! $paiement_id > 0)
+                        {
+                            $errmsg=$paiement->error;
+                            $error++;
+                        }
+                    }
+
+                    if (! $error)
+                    {
+                        $result=$paiement->addLinkInvoiceBank($user,'(SubscriptionPayment)',$accountid,$emetteur_nom,$emetteur_banque);
+                        if (! $result > 0)
+                        {
+                            $errmsg=$paiement->error;
+                            $error++;
+                        }
+                    }
+                }
+            }
+        }
+
+        if (! $error)
+        {
+            $db->commit();
+        }
+        else
+        {
+            $db->rollback();
+            $action = 'addsubscription';
+        }
+
+        // Send email
+        if (! $error)
+        {
             // Send confirmation Email
             if ($adh->email && $_POST["sendmail"])
             {
@@ -335,8 +363,8 @@ if ($user->rights->adherent->cotisation->creer && $_POST["action"] == 'cotisatio
             $_POST["operation"]='';
             $_POST["label"]='';
             $_POST["num_chq"]='';
-		}
-	}
+        }
+    }
 }
 
 
@@ -464,10 +492,10 @@ if ($rowid)
     if ($_GET['action'] == 'editlogin')
     {
         /*$include=array();
-        if (empty($user->rights->user->user->creer))    // If can edit only itself user, we can link to itself only
-        {
-            $include=array($adh->user_id,$user->id);
-        }*/
+         if (empty($user->rights->user->user->creer))    // If can edit only itself user, we can link to itself only
+         {
+         $include=array($adh->user_id,$user->id);
+         }*/
         print $html->form_users($_SERVER['PHP_SELF'].'?rowid='.$adh->id,$adh->user_id,'userid','');
     }
     else
@@ -488,12 +516,12 @@ if ($rowid)
 
     if ($errmsg)
     {
-    	if (preg_match('/^Error/i',$errmsg))
-    	{
-    		$langs->load("errors");
-    		$errmsg=$langs->trans($errmsg);
-    	}
-    	print '<div class="error">'.$errmsg.'</div>'."\n";
+        if (preg_match('/^Error/i',$errmsg))
+        {
+            $langs->load("errors");
+            $errmsg=$langs->trans($errmsg);
+        }
+        print '<div class="error">'.$errmsg.'</div>'."\n";
     }
 
 
@@ -504,18 +532,18 @@ if ($rowid)
     // Lien nouvelle cotisation si non brouillon et non resilie
     if ($user->rights->adherent->cotisation->creer)
     {
-    	if ($action != 'addsubscription')
-    	{
+        if ($action != 'addsubscription')
+        {
             print '<div class="tabsAction">';
 
-    	    if ($adh->statut > 0) print "<a class=\"butAction\" href=\"card_subscriptions.php?rowid=$rowid&action=addsubscription\">".$langs->trans("AddSubscription")."</a>";
+            if ($adh->statut > 0) print "<a class=\"butAction\" href=\"card_subscriptions.php?rowid=$rowid&action=addsubscription\">".$langs->trans("AddSubscription")."</a>";
             else print '<a class="butActionRefused" href="#" title="'.dol_escape_htmltag($langs->trans("ValidateBefore")).'">'.$langs->trans("AddSubscription").'</a>';
 
             print "<br>\n";
 
             print '</div>';
             print '<br>';
-    	}
+        }
     }
 
 
@@ -539,60 +567,60 @@ if ($rowid)
         $result = $db->query($sql);
         if ($result)
         {
-        	$cotisationstatic=new Cotisation($db);
-        	$accountstatic=new Account($db);
-
-        	$num = $db->num_rows($result);
-        	$i = 0;
-
-        	print "<table class=\"noborder\" width=\"100%\">\n";
-
-        	print '<tr class="liste_titre">';
-        	print '<td>'.$langs->trans("Ref").'</td>';
-        	print '<td align="center">'.$langs->trans("DateSubscription").'</td>';
-        	print '<td align="center">'.$langs->trans("DateEnd").'</td>';
-        	print '<td align="right">'.$langs->trans("Amount").'</td>';
-        	if ($conf->banque->enabled)
-        	{
-        		print '<td align="right">'.$langs->trans("Account").'</td>';
-        	}
-        	print "</tr>\n";
-
-        	$var=True;
-        	while ($i < $num)
-        	{
-        		$objp = $db->fetch_object($result);
-        		$var=!$var;
-        		print "<tr $bc[$var]>";
-        		$cotisationstatic->ref=$objp->crowid;
-        		$cotisationstatic->id=$objp->crowid;
-        		print '<td>'.$cotisationstatic->getNomUrl(1).'</td>';
-        		print '<td align="center">'.dol_print_date($db->jdate($objp->dateadh),'day')."</td>\n";
-        		print '<td align="center">'.dol_print_date($db->jdate($objp->datef),'day')."</td>\n";
-        		print '<td align="right">'.price($objp->cotisation).'</td>';
-        		if ($conf->banque->enabled)
-        		{
-        			print '<td align="right">';
-        			if ($objp->bid)
-        			{
-        				$accountstatic->label=$objp->label;
-        				$accountstatic->id=$objp->baid;
-        				print $accountstatic->getNomUrl(1);
-        			}
-        			else
-        			{
-        				print '&nbsp;';
-        			}
-        			print '</td>';
-        		}
-        		print "</tr>";
-        		$i++;
-        	}
-        	print "</table>";
+            $cotisationstatic=new Cotisation($db);
+            $accountstatic=new Account($db);
+
+            $num = $db->num_rows($result);
+            $i = 0;
+
+            print "<table class=\"noborder\" width=\"100%\">\n";
+
+            print '<tr class="liste_titre">';
+            print '<td>'.$langs->trans("Ref").'</td>';
+            print '<td align="center">'.$langs->trans("DateSubscription").'</td>';
+            print '<td align="center">'.$langs->trans("DateEnd").'</td>';
+            print '<td align="right">'.$langs->trans("Amount").'</td>';
+            if ($conf->banque->enabled)
+            {
+                print '<td align="right">'.$langs->trans("Account").'</td>';
+            }
+            print "</tr>\n";
+
+            $var=True;
+            while ($i < $num)
+            {
+                $objp = $db->fetch_object($result);
+                $var=!$var;
+                print "<tr $bc[$var]>";
+                $cotisationstatic->ref=$objp->crowid;
+                $cotisationstatic->id=$objp->crowid;
+                print '<td>'.$cotisationstatic->getNomUrl(1).'</td>';
+                print '<td align="center">'.dol_print_date($db->jdate($objp->dateadh),'day')."</td>\n";
+                print '<td align="center">'.dol_print_date($db->jdate($objp->datef),'day')."</td>\n";
+                print '<td align="right">'.price($objp->cotisation).'</td>';
+                if ($conf->banque->enabled)
+                {
+                    print '<td align="right">';
+                    if ($objp->bid)
+                    {
+                        $accountstatic->label=$objp->label;
+                        $accountstatic->id=$objp->baid;
+                        print $accountstatic->getNomUrl(1);
+                    }
+                    else
+                    {
+                        print '&nbsp;';
+                    }
+                    print '</td>';
+                }
+                print "</tr>";
+                $i++;
+            }
+            print "</table>";
         }
         else
         {
-        	dol_print_error($db);
+            dol_print_error($db);
         }
     }
 
@@ -603,9 +631,9 @@ if ($rowid)
      */
     if ($action == 'addsubscription' && $user->rights->adherent->cotisation->creer)
     {
-    	print '<br>';
+        print '<br>';
 
-    	print_fiche_titre($langs->trans("NewCotisation"));
+        print_fiche_titre($langs->trans("NewCotisation"));
 
         $bankdirect=0;        // Option to write to bank is on by default
         $bankviainvoice=0;    // Option to write via invoice is on by default
@@ -615,10 +643,10 @@ if ($rowid)
         // TODO A virer
         //$bankviainvoice=0;
 
-    	print "\n\n<!-- Form add subscription -->\n";
+        print "\n\n<!-- Form add subscription -->\n";
 
-    	if ($conf->use_javascript_ajax)
-    	{
+        if ($conf->use_javascript_ajax)
+        {
             print "\n".'<script type="text/javascript" language="javascript">';
             print 'jQuery(document).ready(function () {
                         jQuery(".bankswitchclass").'.($bankdirect||$bankviainvoice?'show()':'hide()').';
@@ -635,66 +663,66 @@ if ($rowid)
                             jQuery(".bankswitchclass").show();
                         });
     	       });';
-        	print '</script>'."\n";
-    	}
-
-    	print '<form name="cotisation" method="post" action="'.$_SERVER["PHP_SELF"].'">';
-    	print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
-    	print '<input type="hidden" name="action" value="cotisation">';
-    	print '<input type="hidden" name="rowid" value="'.$rowid.'">';
-    	print "<table class=\"border\" width=\"100%\">\n";
-
-    	$today=mktime();
-    	$datefrom=0;
-    	$dateto=0;
-
-    	// Date start subscription
-    	print '<tr><td width="30%" class="fieldrequired">'.$langs->trans("DateSubscription").'</td><td>';
-    	if ($_POST["reday"])
-    	{
-    		$datefrom=dol_mktime(0,0,0,$_POST["remonth"],$_POST["reday"],$_POST["reyear"]);
-    	}
-    	if (! $datefrom)
-    	{
-    		if ($adh->datefin > 0)
-    		{
-    			$datefrom=dol_time_plus_duree($adh->datefin,1,'d');
-    		}
-    		else
-    		{
-    			$datefrom=mktime();
-    		}
-    	}
-    	$html->select_date($datefrom,'','','','',"cotisation");
-    	print "</td></tr>";
-
-    	// Date end subscription
-    	if ($_POST["endday"])
-    	{
-    		$dateto=dol_mktime(0,0,0,$_POST["endmonth"],$_POST["endday"],$_POST["endyear"]);
-    	}
-    	if (! $dateto)
-    	{
-    		//$dateto=dol_time_plus_duree(dol_time_plus_duree($datefrom,$defaultdelay,$defaultdelayunit),-1,'d');
-    		$dateto=-1;		// By default, no date is suggested
-    	}
-    	print '<tr><td>'.$langs->trans("DateEndSubscription").'</td><td>';
-    	$html->select_date($dateto,'end','','','',"cotisation");
-    	print "</td></tr>";
-
-    	if ($adht->cotisation)
-    	{
-    		// Amount
-    		print '<tr><td class="fieldrequired">'.$langs->trans("Amount").'</td><td><input type="text" name="cotisation" size="6" value="'.$_POST["cotisation"].'"> '.$langs->trans("Currency".$conf->monnaie).'</td></tr>';
-
-    		// Label
-    		print '<tr><td class="fieldrequired">'.$langs->trans("Label").'</td>';
-    		print '<td><input name="label" type="text" size="32" value="'.$langs->trans("Subscription").' ';
-    		print dol_print_date(($datefrom?$datefrom:time()),"%Y").'" ></td></tr>';
-
-    		// Bank account transaction
-    		if ($conf->banque->enabled || $conf->facture->enabled)
-    		{
+            print '</script>'."\n";
+        }
+
+        print '<form name="cotisation" method="post" action="'.$_SERVER["PHP_SELF"].'">';
+        print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
+        print '<input type="hidden" name="action" value="cotisation">';
+        print '<input type="hidden" name="rowid" value="'.$rowid.'">';
+        print "<table class=\"border\" width=\"100%\">\n";
+
+        $today=mktime();
+        $datefrom=0;
+        $dateto=0;
+
+        // Date start subscription
+        print '<tr><td width="30%" class="fieldrequired">'.$langs->trans("DateSubscription").'</td><td>';
+        if ($_POST["reday"])
+        {
+            $datefrom=dol_mktime(0,0,0,$_POST["remonth"],$_POST["reday"],$_POST["reyear"]);
+        }
+        if (! $datefrom)
+        {
+            if ($adh->datefin > 0)
+            {
+                $datefrom=dol_time_plus_duree($adh->datefin,1,'d');
+            }
+            else
+            {
+                $datefrom=mktime();
+            }
+        }
+        $html->select_date($datefrom,'','','','',"cotisation");
+        print "</td></tr>";
+
+        // Date end subscription
+        if ($_POST["endday"])
+        {
+            $dateto=dol_mktime(0,0,0,$_POST["endmonth"],$_POST["endday"],$_POST["endyear"]);
+        }
+        if (! $dateto)
+        {
+            //$dateto=dol_time_plus_duree(dol_time_plus_duree($datefrom,$defaultdelay,$defaultdelayunit),-1,'d');
+            $dateto=-1;		// By default, no date is suggested
+        }
+        print '<tr><td>'.$langs->trans("DateEndSubscription").'</td><td>';
+        $html->select_date($dateto,'end','','','',"cotisation");
+        print "</td></tr>";
+
+        if ($adht->cotisation)
+        {
+            // Amount
+            print '<tr><td class="fieldrequired">'.$langs->trans("Amount").'</td><td><input type="text" name="cotisation" size="6" value="'.$_POST["cotisation"].'"> '.$langs->trans("Currency".$conf->monnaie).'</td></tr>';
+
+            // Label
+            print '<tr><td class="fieldrequired">'.$langs->trans("Label").'</td>';
+            print '<td><input name="label" type="text" size="32" value="'.$langs->trans("Subscription").' ';
+            print dol_print_date(($datefrom?$datefrom:time()),"%Y").'" ></td></tr>';
+
+            // Bank account transaction
+            if ($conf->banque->enabled || $conf->facture->enabled)
+            {
                 $company=new Societe($db);
                 if ($adh->fk_soc)
                 {
@@ -734,43 +762,43 @@ if ($rowid)
                 }
                 print '</td></tr>';
 
-    			// Bank account
-    			print '<tr class="bankswitchclass"><td class="fieldrequired">'.$langs->trans("FinancialAccount").'</td><td>';
-    			$html->select_comptes($_POST["accountid"],'accountid',0,'',1);
-    			print "</td></tr>\n";
-
-    			// Payment mode
-    			print '<tr class="bankswitchclass"><td class="fieldrequired">'.$langs->trans("PaymentMode").'</td><td>';
-    			$html->select_types_paiements($_POST["operation"],'operation');
-    			print "</td></tr>\n";
-
-    			print '<tr class="bankswitchclass"><td>'.$langs->trans('Numero');
-    			print ' <em>('.$langs->trans("ChequeOrTransferNumber").')</em>';
-    			print '</td>';
-    			print '<td><input id="fieldnum_chq" name="num_chq" type="text" size="8" value="'.(empty($_POST['num_chq'])?'':$_POST['num_chq']).'"></td></tr>';
-
-    			print '<tr class="bankswitchclass"><td>'.$langs->trans('CheckTransmitter');
-    			print ' <em>('.$langs->trans("ChequeMaker").')</em>';
-    			print '</td>';
-    			print '<td><input id="fieldchqemetteur" name="chqemetteur" size="32" type="text" value="'.(empty($_POST['chqemetteur'])?$facture->client->nom:$_POST['chqemetteur']).'"></td></tr>';
-
-    			print '<tr class="bankswitchclass"><td>'.$langs->trans('Bank');
-    			print ' <em>('.$langs->trans("ChequeBank").')</em>';
-    			print '</td>';
-    			print '<td><input id="chqbank" name="chqbank" size="32" type="text" value="'.(empty($_POST['chqbank'])?'':$_POST['chqbank']).'"></td></tr>';
-    		}
-    	}
+                // Bank account
+                print '<tr class="bankswitchclass"><td class="fieldrequired">'.$langs->trans("FinancialAccount").'</td><td>';
+                $html->select_comptes($_POST["accountid"],'accountid',0,'',1);
+                print "</td></tr>\n";
+
+                // Payment mode
+                print '<tr class="bankswitchclass"><td class="fieldrequired">'.$langs->trans("PaymentMode").'</td><td>';
+                $html->select_types_paiements($_POST["operation"],'operation');
+                print "</td></tr>\n";
+
+                print '<tr class="bankswitchclass"><td>'.$langs->trans('Numero');
+                print ' <em>('.$langs->trans("ChequeOrTransferNumber").')</em>';
+                print '</td>';
+                print '<td><input id="fieldnum_chq" name="num_chq" type="text" size="8" value="'.(empty($_POST['num_chq'])?'':$_POST['num_chq']).'"></td></tr>';
+
+                print '<tr class="bankswitchclass"><td>'.$langs->trans('CheckTransmitter');
+                print ' <em>('.$langs->trans("ChequeMaker").')</em>';
+                print '</td>';
+                print '<td><input id="fieldchqemetteur" name="chqemetteur" size="32" type="text" value="'.(empty($_POST['chqemetteur'])?$facture->client->nom:$_POST['chqemetteur']).'"></td></tr>';
+
+                print '<tr class="bankswitchclass"><td>'.$langs->trans('Bank');
+                print ' <em>('.$langs->trans("ChequeBank").')</em>';
+                print '</td>';
+                print '<td><input id="chqbank" name="chqbank" size="32" type="text" value="'.(empty($_POST['chqbank'])?'':$_POST['chqbank']).'"></td></tr>';
+            }
+        }
 
         print '<tr><td colspan="2">&nbsp;</td>';
 
         print '<tr><td width="30%">'.$langs->trans("SendAcknowledgementByMail").'</td>';
-    	print '<td>';
-    	if (! $adh->email)
-    	{
-    		print $langs->trans("NoEMail");
-    	}
-    	else
-    	{
+        print '<td>';
+        if (! $adh->email)
+        {
+            print $langs->trans("NoEMail");
+        }
+        else
+        {
             $adht = new AdherentType($db);
             $adht->fetch($adh->typeid);
 
@@ -787,21 +815,21 @@ if ($rowid)
             $helpcontent.='<b>'.$langs->trans("Content").'</b>:<br>';
             $helpcontent.=dol_htmlentitiesbr($texttosend)."\n";
 
-    		print $html->textwithpicto($tmp,$helpcontent,1,'help');
-    	}
-    	print '</td></tr>';
+            print $html->textwithpicto($tmp,$helpcontent,1,'help');
+        }
+        print '</td></tr>';
         print '</table>';
         print '<br>';
 
-    	print '<center>';
-    	print '<input type="submit" class="button" name="add" value="'.$langs->trans("AddSubscription").'">';
-    	print ' &nbsp; &nbsp; ';
-    	print '<input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">';
-    	print '</center>';
+        print '<center>';
+        print '<input type="submit" class="button" name="add" value="'.$langs->trans("AddSubscription").'">';
+        print ' &nbsp; &nbsp; ';
+        print '<input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">';
+        print '</center>';
 
-    	print '</form>';
+        print '</form>';
 
-    	print "\n<!-- End form subscription -->\n\n";
+        print "\n<!-- End form subscription -->\n\n";
     }
 
     //print '</td></tr>';
diff --git a/htdocs/compta/bank/class/account.class.php b/htdocs/compta/bank/class/account.class.php
index 4b55c7db997c9ad928a335e911b9b989d0078837..744836cf88ac30f768e3d4696486f2100a781130 100644
--- a/htdocs/compta/bank/class/account.class.php
+++ b/htdocs/compta/bank/class/account.class.php
@@ -168,7 +168,7 @@ class Account extends CommonObject
 			while ($i < $num)
 			{
 				$obj = $this->db->fetch_object($result);
-				// Anciens liens (pour compatibilit�)
+				// Anciens liens (pour compatibilite)
 				$lines[$i][0] = $obj->url;
 				$lines[$i][1] = $obj->url_id;
 				$lines[$i][2] = $obj->label;
@@ -525,9 +525,9 @@ class Account extends CommonObject
 
 
 	/**
-	 *      \brief      Charge un compte en memoire depuis la base
-	 *      \param      id      Id du compte a recuperer
-	 *      \param      ref     Ref du compte a recuperer
+	 *      Load a bank account into memory from database
+	 *      @param      id      Id du compte a recuperer
+	 *      @param      ref     Ref du compte a recuperer
 	 */
 	function fetch($id,$ref='')
 	{
diff --git a/htdocs/compta/paiement.php b/htdocs/compta/paiement.php
index fae963909b27f0a1be9d0e8f30c3f1e844908c8c..e7404dcce9ac2bb9bdee1cded21aac1d485e2860 100644
--- a/htdocs/compta/paiement.php
+++ b/htdocs/compta/paiement.php
@@ -29,8 +29,8 @@
 
 require('../main.inc.php');
 require_once(DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php');
-include_once(DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php');
-include_once(DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php');
+require_once(DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php');
+require_once(DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php');
 
 $langs->load('companies');
 $langs->load('bills');
@@ -47,6 +47,14 @@ $amounts=array();
 $amountsresttopay=array();
 $addwarning=0;
 
+// Security check
+if ($user->societe_id > 0)
+{
+    $socid = $user->societe_id;
+}
+
+
+
 /*
  * Action add_paiement et confirm_paiement
  */
@@ -130,10 +138,9 @@ if ($_POST['action'] == 'add_paiement')
  */
 if ($_POST['action'] == 'confirm_paiement' && $_POST['confirm'] == 'yes')
 {
-	$datepaye = dol_mktime(12, 0 , 0,
-	$_POST['remonth'],
-	$_POST['reday'],
-	$_POST['reyear']);
+    $error=0;
+
+	$datepaye = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
 
 	if (! $error)
 	{
@@ -147,70 +154,27 @@ if ($_POST['action'] == 'confirm_paiement' && $_POST['confirm'] == 'yes')
 		$paiement->num_paiement = $_POST['num_paiement'];
 		$paiement->note         = $_POST['comment'];
 
-		$paiement_id = $paiement->create($user);
-
-		if ($paiement_id > 0)
+		if (! $error)
 		{
-			if ($conf->banque->enabled)
-			{
-				// Insert payment into llx_bank
-				$label = "(CustomerInvoicePayment)";
-				$acc = new Account($db, $_POST['accountid']);
-
-				$bank_line_id = $acc->addline($paiement->datepaye,
-				$paiement->paiementid,	// Payment mode id or code ("CHQ or VIR for example")
-				$label,
-				$totalpaiement,
-				$paiement->num_paiement,
-	      		'',
-				$user,
-				$_POST['chqemetteur'],
-				$_POST['chqbank']);
-
-				// Mise a jour fk_bank dans llx_paiement.
-				// On connait ainsi le paiement qui a genere l'ecriture bancaire
-				if ($bank_line_id > 0)
-				{
-					$result=$paiement->update_fk_bank($bank_line_id);
-					if ($result <= 0) dol_print_error($db);
-                    // Add link in bank_url between payment and bank transaction
-					$result=$acc->add_url_line($bank_line_id,
-                        $paiement_id,
-                        DOL_URL_ROOT.'/compta/paiement/fiche.php?id=',
-                                                     '(paiement)',
-                                                     'payment');
-                    if ($result <= 0) dol_print_error($db);
-					// Add link in bank_url between invoice and bank transaction (for each invoice concerned by payment)
-                    $linkaddedforthirdparty=array();
-                    foreach ($paiement->amounts as $key => $value)
-                    {
-						$fac = new Facture($db);
-						$fac->fetch($key);
-						$fac->fetch_thirdparty();
-						if (! in_array($fac->client->id,$linkaddedforthirdparty)) // Not yet done for this thirdparty
-						{
-							$result=$acc->add_url_line($bank_line_id,
-							$fac->client->id,
-							DOL_URL_ROOT.'/compta/fiche.php?socid=',
-							$fac->client->nom,
-			       			'company');
-                            if ($result <= 0) dol_print_error($db);
-							$linkaddedforthirdparty[$fac->client->id]=$fac->client->id;  // Mark as done for this thirdparty
-						}
-					}
-				}
-				else
-				{
-					$error++;
-				}
-			}
+    		$paiement_id = $paiement->create($user);
+    		if (! $paiement_id > 0)
+    		{
+    		    $errmsg=$paiement->error;
+    		    $error++;
+    		}
 		}
-		else
+
+		if (! $error)
 		{
-			$error++;
+		    $result=$paiement->addLinkInvoiceBank($user,'(CustomerInvoicePayment)',$_POST['accountid'],$_POST['chqemetteur'],$_POST['chqbank']);
+            if (! $result > 0)
+            {
+                $errmsg=$paiement->error;
+                $error++;
+            }
 		}
 
-		if ($error == 0)
+		if (! $error)
 		{
 			$db->commit();
 			$loc = DOL_URL_ROOT.'/compta/paiement/fiche.php?id='.$paiement_id;
@@ -224,13 +188,6 @@ if ($_POST['action'] == 'confirm_paiement' && $_POST['confirm'] == 'yes')
 	}
 }
 
-// Security check
-if ($user->societe_id > 0)
-{
-	$action = '';
-	$socid = $user->societe_id;
-}
-
 
 /*
  * View
diff --git a/htdocs/compta/paiement/class/paiement.class.php b/htdocs/compta/paiement/class/paiement.class.php
index 907bdd21fa5b43bcc3295984a51f3f2a907b5302..320174213d9f82169a340ef365b3745943a27b4f 100644
--- a/htdocs/compta/paiement/class/paiement.class.php
+++ b/htdocs/compta/paiement/class/paiement.class.php
@@ -116,9 +116,10 @@ class Paiement
 	}
 
 	/**
-	 *    \brief      Create payment in database
-	 *    \param      user        object user
-	 *    \return     int         id of created payment, < 0 if error
+	 *    Create payment of invoices into database.
+	 *    Use this->amounts to have list of invoices for the payment
+	 *    @param      user        object user
+	 *    @return     int         id of created payment, < 0 if error
 	 */
 	function create($user)
 	{
@@ -138,64 +139,69 @@ class Paiement
 		}
 		$this->total = price2num($this->total);
 
+		// Check parameters
+		if ($this->total == 0) return -1; // On accepte les montants negatifs pour les rejets de prelevement
+
 
 		$this->db->begin();
 
-		if ($this->total <> 0) // On accepte les montants negatifs pour les rejets de prelevement
+		$sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement (datec, datep, amount, fk_paiement, num_paiement, note, fk_user_creat)";
+		$sql.= " VALUES ('".$this->db->idate($now)."', '".$this->db->idate($this->datepaye)."', '".$this->total."', ".$this->paiementid.", '".$this->num_paiement."', '".addslashes($this->note)."', ".$user->id.")";
+
+		dol_syslog("Paiement::Create insert paiement sql=".$sql);
+		$resql = $this->db->query($sql);
+		if ($resql)
 		{
-			$sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement (datec, datep, amount, fk_paiement, num_paiement, note, fk_user_creat)";
-			$sql.= " VALUES ('".$this->db->idate($now)."', '".$this->db->idate($this->datepaye)."', '".$this->total."', ".$this->paiementid.", '".$this->num_paiement."', '".addslashes($this->note)."', ".$user->id.")";
+			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'paiement');
 
-			dol_syslog("Paiement::Create insert paiement sql=".$sql);
-			$resql = $this->db->query($sql);
-			if ($resql)
+			// Insere liens montants / factures
+			foreach ($this->amounts as $key => $amount)
 			{
-				$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'paiement');
-
-				// Insere liens montants / factures
-				foreach ($this->amounts as $key => $amount)
+				$facid = $key;
+				if (is_numeric($amount) && $amount <> 0)
 				{
-					$facid = $key;
-					if (is_numeric($amount) && $amount <> 0)
-					{
-						$amount = price2num($amount);
-						$sql = 'INSERT INTO '.MAIN_DB_PREFIX.'paiement_facture (fk_facture, fk_paiement, amount)';
-						$sql .= ' VALUES ('.$facid.', '. $this->id.', \''.$amount.'\')';
-
-						dol_syslog("Paiement::Create Amount line '.$key.' insert paiement_facture sql=".$sql);
-						$resql=$this->db->query($sql);
-						if (! $resql)
-						{
-							$this->error=$this->db->lasterror();
-							dol_syslog('Paiement::Create insert paiement_facture error='.$this->error, LOG_ERR);
-							$error++;
-						}
-					}
-					else
+					$amount = price2num($amount);
+					$sql = 'INSERT INTO '.MAIN_DB_PREFIX.'paiement_facture (fk_facture, fk_paiement, amount)';
+					$sql .= ' VALUES ('.$facid.', '. $this->id.', \''.$amount.'\')';
+
+					dol_syslog("Paiement::Create Amount line '.$key.' insert paiement_facture sql=".$sql);
+					$resql=$this->db->query($sql);
+					if (! $resql)
 					{
-						dol_syslog('Paiement::Create Amount line '.$key.' not a number. We discard it.');
+						$this->error=$this->db->lasterror();
+						dol_syslog('Paiement::Create insert paiement_facture error='.$this->error, LOG_ERR);
+						$error++;
 					}
 				}
-
-				if (! $error)
+				else
 				{
-					// Appel des triggers
-					include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php");
-					$interface=new Interfaces($this->db);
-					$result=$interface->run_triggers('PAYMENT_CUSTOMER_CREATE',$this,$user,$langs,$conf);
-					if ($result < 0) { $error++; $this->errors=$interface->errors; }
-					// Fin appel triggers
+					dol_syslog('Paiement::Create Amount line '.$key.' not a number. We discard it.');
 				}
 			}
-			else
+
+			if (! $error)
 			{
-				$this->error=$this->db->error();
-				dol_syslog('Paiement::Create insert paiement error='.$this->error, LOG_ERR);
-				$error++;
+				// Appel des triggers
+				include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php");
+				$interface=new Interfaces($this->db);
+				$result=$interface->run_triggers('PAYMENT_CUSTOMER_CREATE',$this,$user,$langs,$conf);
+				if ($result < 0) { $error++; $this->errors=$interface->errors; }
+				// Fin appel triggers
 			}
 		}
+		else
+		{
+			$this->error=$this->db->error();
+			dol_syslog('Paiement::Create insert paiement error='.$this->error, LOG_ERR);
+			$error++;
+		}
+
+        // If option to add link to bank account is on
+
 
-		if ($this->total <> 0 && ! $error) // On accepte les montants negatifs
+
+
+		if (! $error) // On accepte les montants negatifs
 		{
 			$this->db->commit();
 			return $this->id;
@@ -293,6 +299,99 @@ class Paiement
 		}
 	}
 
+
+    /**
+     *      A record into bank for payment with links between this bank record and invoices of payment.
+     *      All payment properties must have been set first like after a call to create().
+     *      @param      user                Object of user making payment
+     *      @param      label               Label to use in bank record
+     *      @param      accountid           Id of bank account to do link with
+     *      @param      emetteur_nom        Name of transmitter
+     *      @param      emetteur_banque     Name of bank
+     *      @return     int                 <0 if KO, >0 if OK
+     */
+    function addLinkInvoiceBank($user,$label,$accountid,$emetteur_nom,$emetteur_banque)
+    {
+        global $conf;
+
+        $error=0;
+
+        if ($conf->banque->enabled)
+        {
+            require_once(DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php');
+
+            $acc = new Account($this->db);
+            $acc->fetch($accountid);
+
+            // Insert payment into llx_bank
+            $bank_line_id = $acc->addline($this->datepaye,
+            $this->paiementid,  // Payment mode id or code ("CHQ or VIR for example")
+            $label,
+            $this->total,
+            $this->num_paiement,
+            '',
+            $user,
+            $emetteur_nom,
+            $emetteur_banque);
+
+            // Mise a jour fk_bank dans llx_paiement.
+            // On connait ainsi le paiement qui a genere l'ecriture bancaire
+            if ($bank_line_id > 0)
+            {
+                $result=$this->update_fk_bank($bank_line_id);
+                if ($result <= 0)
+                {
+                    $error++;
+                    dol_print_error($this->db);
+                }
+                // Add link 'payment' in bank_url between payment and bank transaction
+                $result=$acc->add_url_line($bank_line_id,
+                    $this->id,
+                    DOL_URL_ROOT.'/compta/paiement/fiche.php?id=',
+                                                 '(paiement)',
+                                                 'payment');
+                if ($result <= 0)
+                {
+                    $error++;
+                    dol_print_error($this->db);
+                }
+                // Add link 'company' in bank_url between invoice and bank transaction (for each invoice concerned by payment)
+                $linkaddedforthirdparty=array();
+                foreach ($this->amounts as $key => $value)
+                {
+                    $fac = new Facture($this->db);
+                    $fac->fetch($key);
+                    $fac->fetch_thirdparty();   // This should be always same third party but we loop in case of.
+                    if (! in_array($fac->client->id,$linkaddedforthirdparty)) // Not yet done for this thirdparty
+                    {
+                        $result=$acc->add_url_line($bank_line_id,
+                        $fac->client->id,
+                        DOL_URL_ROOT.'/compta/fiche.php?socid=',
+                        $fac->client->nom,
+                        'company');
+                        if ($result <= 0) dol_print_error($this->db);
+                        $linkaddedforthirdparty[$fac->client->id]=$fac->client->id;  // Mark as done for this thirdparty
+                    }
+                }
+            }
+            else
+            {
+                $this->error=$acc->error;
+                $error++;
+            }
+        }
+
+        if (! $error)
+        {
+            return 1;
+        }
+        else
+        {
+            return -1;
+        }
+    }
+
+
 	/**
 	 *      \brief      Mise a jour du lien entre le paiement et la ligne generee dans llx_bank
 	 *      \param      id_bank     Id compte bancaire
@@ -301,6 +400,8 @@ class Paiement
 	{
 		$sql = 'UPDATE llx_paiement set fk_bank = '.$id_bank;
 		$sql.= ' WHERE rowid = '.$this->id;
+
+		dol_syslog('Paiement::update_fk_bank sql='.$sql);
 		$result = $this->db->query($sql);
 		if ($result)
 		{
diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php
index b2bd791f29fecefdc6c096fc7453e543d392b2f8..11d4a1de853621f43dc419e0eae50dc524f6b149 100644
--- a/htdocs/core/class/commonobject.class.php
+++ b/htdocs/core/class/commonobject.class.php
@@ -542,7 +542,7 @@ class CommonObject
 		if (!$this->isnolinkedbythird && !$user->rights->societe->client->voir) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc";
 		$sql.= " WHERE te.".$fieldid." < '".addslashes($this->ref)."'";
 		if (!$this->isnolinkedbythird && !$user->rights->societe->client->voir) $sql.= " AND sc.fk_user = " .$user->id;
-		if (isset($filter)) $sql.=" AND ".$filter;
+		if (! empty($filter)) $sql.=" AND ".$filter;
 		if ($this->ismultientitymanaged == 2 || ($this->element != 'societe' && !$this->isnolinkedbythird && !$user->rights->societe->client->voir)) $sql.= ' AND te.fk_soc = s.rowid';			// If we need to link to societe to limit select to entity
 		if ($this->ismultientitymanaged == 1) $sql.= ' AND te.entity IN (0,'.$conf->entity.')';
 
diff --git a/htdocs/langs/en_US/members.lang b/htdocs/langs/en_US/members.lang
index 7dde868aeb9d7a8a70b8fcce658fbde8cef4d5c7..940a15467b93be4bbebdb7f93cf207087c16f81c 100644
--- a/htdocs/langs/en_US/members.lang
+++ b/htdocs/langs/en_US/members.lang
@@ -159,4 +159,4 @@ LinkToGeneratedPagesDesc=This screen allows you to generate PDF files with busin
 DocForAllMembersCards=Generate business cards for all members (Format for output actually setup : <b>%s</b>)
 DocForOneMemberCards=Generate business cards for a particular member (Format for output actually setup: <b>%s</b>)
 DocForLabels=Generate address sheets (Format for output actually setup: <b>%s</b>)
-
+SubscriptionPayment=Subscription payment
\ No newline at end of file
diff --git a/htdocs/langs/fr_FR/members.lang b/htdocs/langs/fr_FR/members.lang
index d362fcc6c5b79c527b8ed815583f7c3dd654f8bc..684453ec58b85425aaa034e5965cb952fce478a6 100644
--- a/htdocs/langs/fr_FR/members.lang
+++ b/htdocs/langs/fr_FR/members.lang
@@ -159,3 +159,4 @@ LinkToGeneratedPagesDesc=Cet écran vous permet de générer des planches de car
 DocForAllMembersCards=Génération de cartes pour tous les adhérents (Format de planche actuellement configuré: <b>%s</b>)
 DocForOneMemberCards=Génération de cartes pour un adhérent particulier (Format de planche actuellement configuré: <b>%s</b>)
 DocForLabels=Génération d'étiquette d'adresses (Format de planche actuellement configuré: <b>%s</b>)
+SubscriptionPayment=Paiement cotisation
\ No newline at end of file