diff --git a/modules/bibcirculation/lib/bibcirculation_cern_ldap.py b/modules/bibcirculation/lib/bibcirculation_cern_ldap.py
index aeb7bb63c..c8061640c 100644
--- a/modules/bibcirculation/lib/bibcirculation_cern_ldap.py
+++ b/modules/bibcirculation/lib/bibcirculation_cern_ldap.py
@@ -1,87 +1,87 @@
 ## This file is part of Invenio.
 ## Copyright (C) 2009, 2010, 2011 CERN.
 ##
 ## Invenio is free software; you can redistribute it and/or
 ## modify it under the terms of the GNU General Public License as
 ## published by the Free Software Foundation; either version 2 of the
 ## License, or (at your option) any later version.
 ##
 ## Invenio is distributed in the hope that it will be useful, but
 ## WITHOUT ANY WARRANTY; without even the implied warranty of
 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 ## General Public License for more details.
 ##
 ## You should have received a copy of the GNU General Public License
 ## along with Invenio; if not, write to the Free Software Foundation, Inc.,
 ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 
 """Invenio LDAP interface for BibCirculation at CERN. """
 
 from invenio.config import CFG_CERN_SITE
 try:
     import ldap
     #from invenio.external_authentication_cern_wrapper import _cern_nice_soap_auth
     CFG_BIBCIRCULATION_HAS_LDAP = CFG_CERN_SITE
 except (ImportError, IOError):
     CFG_BIBCIRCULATION_HAS_LDAP = False
 
 from thread import get_ident
-from base64 import decodestring
+# from base64 import decodestring
 
 # This is the old configuration
 # CFG_CERN_LDAP_URI  = "ldaps://ldap.cern.ch:636"
 # CFG_CERN_LDAP_BIND = "n=%s,ou=users,o=cern,c=ch"
 # CFG_CERN_LDAP_BASE = "O=CERN,C=CH"
 
 CFG_CERN_LDAP_URI  = "ldap://xldap.cern.ch:389"
 #CFG_CERN_LDAP_BASE = "ou=users,ou=organic units,dc=cern,dc=ch"
 
 CFG_CERN_LDAP_BASE = "dc=cern,dc=ch"
 
 # This one also works but the previous one is recommended
 # CFG_CERN_LDAP_URI  = "ldap://ldap.cern.ch"
 # CFG_CERN_LDAP_BIND = "cn=%s,ou=users,ou=organic units,dc=cern,dc=ch"
 # CFG_CERN_LDAP_BASE = "O=CERN,C=CH"
 
 _ldap_connection_pool = {}
 
 def _cern_ldap_login():
     #user, password = decodestring(_cern_nice_soap_auth).split(':', 1)
     connection = ldap.initialize(CFG_CERN_LDAP_URI)
     #connection.simple_bind(CFG_CERN_LDAP_BIND % user, password)
     return connection
 
 def get_user_info_from_ldap(nickname="", email="", ccid=""):
     """Query the CERN LDAP server for information about a user.
     Return a dictionary of information"""
 
     try:
         connection = _ldap_connection_pool[get_ident()]
     except KeyError:
         connection = _ldap_connection_pool[get_ident()] = _cern_ldap_login()
 
     if nickname:
         query = '(displayName=%s)' % nickname
     elif email:
         query = '(mail=%s)' % email
     elif ccid:
         query = '(employeeID=%s)' % ccid
     else:
         return {}
 
     try:
 
-        filter = "(& %s (| (employeetype=primary) (employeetype=external) ) )" % query
+        query_filter = "(& %s (| (employeetype=primary) (employeetype=external) ) )" % query
         result = connection.search_st(CFG_CERN_LDAP_BASE, ldap.SCOPE_SUBTREE,
-                                      filter, timeout=5)
+                                      query_filter, timeout=5)
         if result and nickname:
             return result[0][1]
         else:
             try:
                 return result[0][1]
             except IndexError:
                 return {}
     except:
         return 'busy'
 
     return {}
diff --git a/modules/bibcirculation/lib/bibcirculation_daemon.py b/modules/bibcirculation/lib/bibcirculation_daemon.py
index e5696ed06..b97ccae0e 100644
--- a/modules/bibcirculation/lib/bibcirculation_daemon.py
+++ b/modules/bibcirculation/lib/bibcirculation_daemon.py
@@ -1,247 +1,249 @@
 # -*- coding: utf-8 -*-
 ##
 ## This file is part of Invenio.
 ## Copyright (C) 2008, 2009, 2010, 2011 CERN.
 ##
 ## Invenio is free software; you can redistribute it and/or
 ## modify it under the terms of the GNU General Public License as
 ## published by the Free Software Foundation; either version 2 of the
 ## License, or (at your option) any later version.
 ##
 ## Invenio is distributed in the hope that it will be useful, but
 ## WITHOUT ANY WARRANTY; without even the implied warranty of
 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 ## General Public License for more details.
 ##
 ## You should have received a copy of the GNU General Public License
 ## along with Invenio; if not, write to the Free Software Foundation, Inc.,
 ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 
 """
 BibCirculation daemon.
 """
 
 __revision__ = "$Id$"
 
 import sys
 import datetime
 import time
 from invenio.dbquery import run_sql
 from invenio.bibtask import task_init, \
                             task_sleep_now_if_required, \
                             task_update_progress, \
                             task_set_option, \
                             task_get_option
 from invenio.mailutils import send_email
 import invenio.bibcirculation_dblayer as db
 from invenio.bibcirculation_config import CFG_BIBCIRCULATION_TEMPLATES, \
                                           CFG_BIBCIRCULATION_LOANS_EMAIL, \
                                           CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN,\
                                           CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED
 
 from invenio.bibcirculation_utils import generate_email_body, \
                                          book_title_from_MARC, \
                                          update_user_info_from_ldap
 
 def task_submit_elaborate_specific_parameter(key, value, opts, args):
     """ Given the string key, checks its meaning and returns True if
         has elaborated the key.
         Possible keys:
     """
     if key in ('-o', '--overdue-letters'):
         task_set_option('overdue-letters', True)
     elif key in ('-b', '--update-borrowers'):
         task_set_option('update_borrowers', True)
     else:
         return False
     return True
 
 def get_expired_loan():
     """
     @return all expired loans
     """
 
     res = run_sql("""select id_crcBORROWER, id, id_bibrec
                        from crcLOAN
                       where (status=%s and due_date<NOW())
                          or (status=%s)
                 """, (CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN,
                        CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED))
     return res
 
 def update_expired_loan(loan_id):
     """
     Update status, number of overdue letter and date of overdue letter
 
     @param loan_id: identify the loan. Primary key of crcLOAN.
     @type loan_id: int
     """
 
     run_sql("""update crcLOAN
                   set overdue_letter_number=overdue_letter_number+1,
                        status=%s,
                        overdue_letter_date=NOW()
                 where id=%s
                """, (CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED,
                      loan_id))
 
 def get_overdue_letters_info(loan_id):
     """
     Get the number of letters and the date of the last letter
     sent for a given loan_id.
 
     @param loan_id: identify the loan. Primary of crcLOAN.
     @type loan_id: int
 
     @return number_of_letters and date of the last letter
     """
 
     res = run_sql("""select overdue_letter_number,
                             DATE_FORMAT(overdue_letter_date,'%%Y-%%m-%%d')
                        from crcLOAN
                       where id=%s""",
                   (loan_id, ))
 
     return res[0]
 
 
 
 def send_overdue_letter(borrower_id, subject, content):
     """
     Send an overdue letter
 
     @param borrower_id: identify the borrower. Primary key of crcBORROWER.
     @type borrower_id: int
 
     @param subject: subject of the overdue letter
     @type subject: string
     """
 
     to_borrower = db.get_borrower_email(borrower_id)
 
     send_email(fromaddr=CFG_BIBCIRCULATION_LOANS_EMAIL,
                toaddr=to_borrower,
                subject=subject,
                content=content,
                header='',
                footer='',
                attempt_times=1,
                attempt_sleeptime=10
                )
     return 1
 
 def must_send_second_recall(date_letters):
     """
     @param date_letters: date of the last letter.
     @type date_letters: string
 
     @return boolean
     """
     today = datetime.date.today()
 
     time_tuple = time.strptime(date_letters, "%Y-%m-%d")
     #datetime.strptime(date_letters, "%Y-%m-%d") doesn't work (only on 2.5).
     tmp_date = datetime.datetime(*time_tuple[0:3]) + datetime.timedelta(weeks=1)
 
     if tmp_date.strftime("%Y-%m-%d") <= today.strftime("%Y-%m-%d"):
         return True
     else:
         return False
 
 def must_send_third_recall(date_letters):
     """
     @param date_letters: date of the last letter.
     @type date_letters: string
 
     @return boolean
     """
     today = datetime.date.today()
 
     time_tuple = time.strptime(date_letters, "%Y-%m-%d")
     #datetime.strptime(date_letters, "%Y-%m-%d") doesn't work (only on Python 2.5)
     tmp_date = datetime.datetime(*time_tuple[0:3]) + datetime.timedelta(days=3)
 
     if tmp_date.strftime("%Y-%m-%d") <= today.strftime("%Y-%m-%d"):
         return True
     else:
         return False
 
 def update_borrowers_information():
     list_of_borrowers = db.get_all_borrowers()
 
-    for (user_id, ccid) in list_of_borrowers:
+    for borrower in list_of_borrowers:
+        user_id = borrower[0]
         update_user_info_from_ldap(user_id)
 
 
 def task_run_core():
     """
     run daemon
     """
 
     if task_get_option("update-borrowers"):
         list_of_borrowers = db.get_all_borrowers()
 
         total_borrowers = len(list_of_borrowers)
         done  = 0
 
-        for (user_id, ccid) in list_of_borrowers:
+        for borrower in list_of_borrowers:
+            user_id = borrower[0]
             update_user_info_from_ldap(user_id)
             done+=1
             task_update_progress("Done %d out of %d." % (done, total_borrowers))
             task_sleep_now_if_required(can_stop_too=True)
 
     if task_get_option("overdue-letters"):
         expired_loans = db.get_all_expired_loans()
 
         total_expired_loans = len(expired_loans)
         done  = 0
 
         for (borrower_id, _bor_name, recid, _barcode, _loaned_on,
              _due_date, _number_of_renewals, number_of_letters,
              date_letters, _notes, loan_id) in expired_loans:
 
             number_of_letters=int(number_of_letters)
 
             content = ''
             if number_of_letters == 0:
                 content = generate_email_body(CFG_BIBCIRCULATION_TEMPLATES['RECALL1'], loan_id)
             elif number_of_letters == 1 and must_send_second_recall(date_letters):
                 content = generate_email_body(CFG_BIBCIRCULATION_TEMPLATES['RECALL2'], loan_id)
             elif number_of_letters == 2 and must_send_third_recall(date_letters):
                 content = generate_email_body(CFG_BIBCIRCULATION_TEMPLATES['RECALL3'], loan_id)
             elif number_of_letters >= 3 and must_send_third_recall(date_letters):
                 content = generate_email_body(CFG_BIBCIRCULATION_TEMPLATES['RECALL3'], loan_id)
 
             if content != '':
                 title = book_title_from_MARC(recid)
                 subject = "LOAN RECALL: " + title
 
                 update_expired_loan(loan_id)
                 send_overdue_letter(borrower_id, subject, content)
 
             done+=1
 
             task_update_progress("Done %d out of %d." % (done, total_expired_loans))
 
             task_sleep_now_if_required(can_stop_too=True)
             time.sleep(1)
 
     return 1
 
 def main():
     """
     main()
     """
     task_init(authorization_action='runbibcircd',
               authorization_msg="BibCirculation Task Submission",
               help_specific_usage="""-o,  --overdue-letters\tCheck overdue loans and send recall emails if necessary.\n-b,  --update-borrowers\tUpdate borrowers information from ldap.\n""",
               description="""Examples:
               %s -u admin
               """ % (sys.argv[0]),
               specific_params=("ob", ["overdue-letters", "update-borrowers"]),
                 task_submit_elaborate_specific_parameter_fnc=task_submit_elaborate_specific_parameter,
                 version=__revision__,
                 task_run_fnc = task_run_core)
 
 if __name__ == '__main__':
     main()
diff --git a/modules/bibcirculation/lib/bibcirculation_dblayer.py b/modules/bibcirculation/lib/bibcirculation_dblayer.py
index 48bbbfbe1..9b66418f8 100644
--- a/modules/bibcirculation/lib/bibcirculation_dblayer.py
+++ b/modules/bibcirculation/lib/bibcirculation_dblayer.py
@@ -1,3371 +1,3358 @@
 # -*- coding: utf-8 -*-
 ##
 ## This file is part of Invenio.
 ## Copyright (C) 2008, 2009, 2010, 2011 CERN.
 ##
 ## Invenio is free software; you can redistribute it and/or
 ## modify it under the terms of the GNU General Public License as
 ## published by the Free Software Foundation; either version 2 of the
 ## License, or (at your option) any later version.
 ##
 ## Invenio is distributed in the hope that it will be useful, but
 ## WITHOUT ANY WARRANTY; without even the implied warranty of
 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 ## General Public License for more details.
 ##
 ## You should have received a copy of the GNU General Public License
 ## along with Invenio; if not, write to the Free Software Foundation, Inc.,
 ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 
 """Every db-related function of module bibcirculation"""
 
 __revision__ = "$Id$"
 
 from invenio.dbquery import run_sql
 from invenio.bibcirculation_config import \
     CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN, \
     CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN, \
     CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED, \
     CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED, \
     CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING, \
     CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING, \
     CFG_BIBCIRCULATION_REQUEST_STATUS_DONE, \
     CFG_BIBCIRCULATION_REQUEST_STATUS_CANCELLED, \
     CFG_BIBCIRCULATION_ILL_STATUS_RETURNED, \
     CFG_BIBCIRCULATION_ILL_STATUS_RECEIVED, \
     CFG_BIBCIRCULATION_ILL_STATUS_CANCELLED, \
     CFG_BIBCIRCULATION_LIBRARY_TYPE_INTERNAL, \
     CFG_BIBCIRCULATION_LIBRARY_TYPE_EXTERNAL, \
     CFG_BIBCIRCULATION_LIBRARY_TYPE_MAIN, \
     CFG_BIBCIRCULATION_LIBRARY_TYPE_HIDDEN
 
 def verify_office_reference(uid):
     """
     Verify is there a reference for user's office
     @param uid: user ID
     """
 
     query = """SELECT office
                  FROM crcborrower
                 WHERE id=%(user_id)i
             """
 
     uid = int(uid)
 
     res = run_sql(query%uid)
 
     return res
 
 def get_holdings_information(recid, include_hidden_libraries=True):
     """
     Get information about holding, using recid.
 
     @param recid: identify the record. Primary key of bibrec.
     @type recid: int
 
     @return holdings information
     """
 
     if include_hidden_libraries:
         res = run_sql("""SELECT it.barcode,
                                 lib.name,
                                 it.collection,
                                 it.location,
                                 it.description,
                                 it.loan_period,
                                 it.status,
                                 DATE_FORMAT(ln.due_date, '%%Y-%%m-%%d')
                            FROM crcITEM it
                                 left join crcLOAN ln
                                 on it.barcode = ln.barcode and ln.status != %s
                                 left join crcLIBRARY lib
                                 on lib.id = it.id_crcLIBRARY
                           WHERE it.id_bibrec=%s
                     """, (CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED, recid))
 
     else:
         res = run_sql("""SELECT it.barcode,
                                 lib.name,
                                 it.collection,
                                 it.location,
                                 it.description,
                                 it.loan_period,
                                 it.status,
                                 DATE_FORMAT(ln.due_date, '%%Y-%%m-%%d')
                            FROM crcITEM it
                                 left join crcLOAN ln
                                 on it.barcode = ln.barcode and ln.status != %s
                                 left join crcLIBRARY lib
                                 on lib.id = it.id_crcLIBRARY
                           WHERE it.id_bibrec=%s
                             AND lib.type<>%s
                     """, (CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED, recid,
                           CFG_BIBCIRCULATION_LIBRARY_TYPE_HIDDEN))
 
     return res
 
 
 def get_holdings_details(recid):
     """
     Get details about holdings (loan period, location and library).
 
     @param recid: identify the record. Primary key of bibrec.
     @type recid: int
 
     @return list with loan period, location and library.
     """
 
     res = run_sql(""" SELECT it.loan_period, lib.name, it.location
                         FROM crcITEM it, crcLIBRARY lib
                        WHERE id_bibrec=%s limit 1""",
                   (recid, ))
 
     return res
 
 def get_due_date_loan(recid):
     """
     Get the due date of a loan.
 
     @param recid: identify the record. Primary key of bibrec.
     @type recid: int
 
     @return due date
     """
 
     res = run_sql("""SELECT DATE_FORMAT(max(due_date),'%%Y-%%m-%%d')
                      FROM crcLOAN
                      WHERE id_bibrec=%s and status != %s
                   """, (recid, CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED))
 
     if res:
         return res[0][0]
     else:
         return None
 
 
 def get_holdings_info_no_requests(recid):
     """
     @param recid: identify the record. Primary key bibrec.
     @type recid: int
     """
 
     res = run_sql(""" SELECT it.loan_period, lib.name
                       FROM crcITEM it, crcLIBRARY lib
                       WHERE it.id_crcLIBRARY=lib.id and it.id_bibrec=%s
                       """, (recid, ))
 
     return res
 
 def get_request_recid(request_id):
     """
     Get recid of a given request_id
 
     @param request_id: identify the (hold) request. Primary key of crcLOANREQUEST.
     @type request_id: int
 
     @return recid
     """
     res = run_sql(""" SELECT id_bibrec
                       FROM crcLOANREQUEST
                       WHERE id=%s
                   """, (request_id, ))
 
     if res:
         return res[0][0]
     else:
         return None
 
 def get_request_borrower_id(request_id):
     """
     Get borrower_id of a given request_id
 
     @param request_id: identify the (hold) request. Primary key of crcLOANREQUEST.
     @type request_id: int
 
     @return borrower_id
     """
 
     res = run_sql(""" SELECT id_crcBORROWER
                       FROM crcLOANREQUEST
                       WHERE id=%s
                   """, (request_id, ))
 
     if res:
         return res[0][0]
     else:
         return None
 
 
 def get_request_barcode(request_id):
     """
     Get the barcode associate to a request_id.
 
     @param request_id: identify the (hold) request. Primary key of crcLOANREQUEST.
     @type request_id: int
 
     @return barcode
     """
     res = run_sql(""" SELECT barcode
                       FROM crcLOANREQUEST
                       WHERE id=%s
                   """, (request_id, ))
 
     if res:
         return res[0][0]
     else:
         return None
 
 def get_id_bibrec(barcode):
     """
     Get the id bibrec (or recid).
 
     @param barcode: identify the item. Primary key of crcITEM.
     @type barcode: string
 
     @return recid or None
     """
 
     res = run_sql("""SELECT id_bibrec
                      FROM crcITEM
                      WHERE barcode=%s
                   """, (barcode, ))
 
     if res:
         return res[0][0]
     else:
         return None
 
 def update_item_status(status, barcode):
     """
     Update the status of an item (using the barcode).
 
     @param status: status of the item.
     @type status: string
 
     @param barcode: identify the item. Primary key of crcITEM.
     @type barcode: string
 
     @return
     """
     if status == CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN:
         return int(run_sql("""UPDATE  crcITEM
                                  SET  status=%s,
                                       number_of_requests = number_of_requests + 1
                                WHERE  barcode=%s""", (status, barcode)))
     else:
         return int(run_sql("""UPDATE  crcITEM
                                  SET  status=%s
                                WHERE  barcode=%s""", (status, barcode)))
 
 
 def new_hold_request(borrower_id, recid, barcode, date_from, date_to, status):
     """
     Create a new hold request.
 
     @param borrower_id: identify the borrower. Primary key of crcBORROWER.
     @type borrower_id: int
 
     @param recid: identify the record. Primary key of bibrec.
     @type recid: int
 
     @param barcode: identify the item. Primary key of crcITEM.
     @type barcode: string
 
     @param date_from: begining of the period of interest.
     @type date_from: string
 
     @param date_to: end of the period of interest.
     @type date_to: string
 
     @param status: hold request status.
     @type status: string
 
     @return
     """
     res = run_sql("""INSERT INTO crcLOANREQUEST(id_crcBORROWER,
                                                 id_bibrec,
                                                 barcode,
                                                 period_of_interest_from,
                                                 period_of_interest_to,
                                                 status,
                                                 request_date)
                         VALUES (%s, %s, %s, %s, %s, %s, NOW())
                     """, (borrower_id, recid, barcode, date_from,
                           date_to, status))
 
     return res
 
 #def get_barcode(recid):
 #    """
 #    Get all the barcodes(copies) of a record(item).
 #
 #    @param recid: identify the record. Primary key of bibrec.
 #    @type recid: int
 #
 #    @return list with barcode(s).
 #    """
 #
 #    res = run_sql("""SELECT barcode
 #                     FROM crcITEM
 #                     WHERE id_bibrec=%s
 #                  """, (recid, ))
 #
 #    if res:
 #        return res[0][0]
 #    else:
 #        return None
 
 def get_due_date(barcode):
     """
     Get the due date of a given barcode.
 
     @param barcode: identify the item. Primary key of crcITEM.
     @type barcode: string
 
     @return due_date
     """
 
     res = run_sql("""SELECT period_of_interest_to
                      FROM crcLOANREQUEST
                      WHERE barcode=%s
                   """, (barcode, ))
 
     if res:
         return res[0][0]
     else:
         return None
 
 def get_requests(recid, status):
     """
     Get the number of requests of a record.
 
     @param recid: identify the record. Primary key of bibrec.
     @type recid: int
 
     @param status: identify the status.
     @type status: string
 
     @return number of request (int)
     """
     res = run_sql("""SELECT id,
                              DATE_FORMAT(period_of_interest_from,'%%Y-%%m-%%d'),
                              DATE_FORMAT(period_of_interest_to,'%%Y-%%m-%%d'),
                              DATE_FORMAT(request_date,'%%Y-%%m-%%d')
                         FROM crcLOANREQUEST
                        WHERE id_bibrec=%s
                          AND status=%s
                          AND period_of_interest_from <= NOW()
                          AND period_of_interest_to >= NOW()
                     ORDER BY request_date
                    """, (recid, status))
 
     return res
 
 def get_number_requests2(barcode, request_id):
     """
     @param barcode: identify the item. Primary key of crcITEM.
     @type barcode: string
 
     @param request_id: identify the (hold) request. Primary key of crcLOANREQUEST.
     @type request_id: int
     """
 
     res = run_sql("""SELECT id_bibrec
                       FROM crcLOANREQUEST
                       WHERE id < %s and barcode=%s and status != %s
                    """, (request_id, barcode,
                          CFG_BIBCIRCULATION_REQUEST_STATUS_DONE))
 
     return res
 
 
 def loan_return_confirm(borrower_id, recid):
     """
     @param borrower_id: identify the borrower. Primary key of crcBORROWER.
     @type borrower_id: int
 
     @param recid: identify the record. Primary key of bibrec.
     @type recid: int
     """
     res = run_sql("""SELECT bor.name, it.id_bibrec
                        FROM crcBORROWER bor, crcITEM it
                       WHERE bor.id=%s and it.id_bibrec=%s
                      """, (borrower_id, recid))
 
     return res
 
 def get_borrower_id(barcode):
     """
     Get the borrower id who is associate to a loan.
 
     @param barcode: identify the item. Primary key of crcITEM.
     @type barcode: string
 
     @return borrower_id or None
     """
     res = run_sql(""" SELECT id_crcBORROWER
                         FROM crcLOAN
                        WHERE barcode=%s and
                              (status=%s or status=%s)""",
                   (barcode, CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN,
                    CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED))
     try:
         return res[0][0]
     except IndexError:
         return None
 
 def get_borrower_email(borrower_id):
     """
     Get the email of a borrower.
 
     @param borrower_id: identify the borrower. Primary key of crcBORROWER.
     @type borrower_id: int
 
     @return borrower's email (string).
     """
     res = run_sql("""SELECT email
                        FROM crcBORROWER
                       WHERE id=%s""", (borrower_id, ))
 
     if res:
         return res[0][0]
     else:
         return None
 
 def get_next_waiting_loan_request(recid):
     """
     Get the next waiting (loan) request for a given recid.
 
     @param recid: identify the record. Primary key of bibrec.
     @type recid: int
 
     @return list with request_id, borrower_name, recid, status,
             period_of_interest (FROM and to) and request_date.
     """
     res = run_sql("""SELECT lr.id,
                             bor.name,
                             lr.id_bibrec,
                             lr.status,
                             DATE_FORMAT(lr.period_of_interest_from,'%%Y-%%m-%%d'),
                             DATE_FORMAT(lr.period_of_interest_to,'%%Y-%%m-%%d'),
                             lr.request_date
                        FROM crcLOANREQUEST lr,
                             crcBORROWER bor
                       WHERE lr.id_crcBORROWER=bor.id
                         AND (lr.status=%s OR lr.status=%s)
                         AND lr.id_bibrec=%s
                    ORDER BY lr.request_date""",
                   (CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING,
                    CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING,
                    recid))
 
     return res
 
 def return_loan(barcode):
     """
     Update loan information when copy is returned.
 
     @param returned_on: return date.
     @type returned_on: string
 
     @param status: new loan status.
     @type status: string
 
     @param barcode: identify the item. Primary key of crcITEM.
     @type barcode: string
 
     @return
     """
 
     return int(run_sql("""UPDATE crcLOAN
                              SET returned_on=NOW(), status=%s, due_date=NULL
                            WHERE barcode=%s and (status=%s or status=%s)
                       """, (CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED,
                             barcode,
                             CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN,
                             CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED)))
 
 
 def get_item_copies_details(recid):
     """
     Get copies details of a given recid.
 
     @param recid: identify the record. Primary key of bibrec.
     @type recid: int
 
     @return list with barcode, loan_period, library_name, library_id,
                       location, number_of_requests, status, collection,
                       description and due_date.
     """
     res = run_sql("""SELECT it.barcode, it.loan_period, lib.name,
                             lib.id, it.location, it.number_of_requests,
                             it.status, it.collection, it.description,
                             DATE_FORMAT(ln.due_date,'%%Y-%%m-%%d')
                      FROM crcITEM it
                             left join crcLOAN ln
                             on it.barcode = ln.barcode and ln.status != %s
                             left join crcLIBRARY lib
                             on lib.id = it.id_crcLIBRARY
                      WHERE it.id_bibrec=%s
                      ORDER BY it.creation_date
                   """, (CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED, recid))
 
     return res
 
 def get_copy_details(barcode):
 
     res = run_sql(""" SELECT *
                         FROM crcITEM it
                        WHERE barcode=%s""",
                   (barcode, ))
 
     if res is not None:
         return res[0]
     else:
         return None
 
 
 def get_library_copies(library_id):
 
     """
     Get copies details of a given recid.
 
     @param recid: identify the record. Primary key of bibrec.
     @type recid: int
 
     @return list with barcode, recid, loan_period,
                       location, status, collection,
                       description and due_date.
     """
     res = run_sql("""SELECT it.barcode, it.id_bibrec, it.loan_period,
                             it.location, it.status, it.collection, it.description,
                             DATE_FORMAT(ln.due_date,'%%Y-%%m-%%d')
                        FROM crcITEM it
                             left join crcLOAN ln
                             on it.barcode = ln.barcode and ln.status != %s
                       WHERE it.id_crcLIBRARY=%s
                   """, (CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED, library_id))
 
     return res
 
 
 def get_number_copies(recid):
     """
     Get the number of copies of a given recid.
 
     @param recid: identify the record. Primary key of bibrec.
     @type recid: int
 
     @return number_of_copies
     """
 
     if type(recid) is not int:
         return 0
 
     else:
 
         res = run_sql("""SELECT count(barcode)
                      FROM crcITEM
                      WHERE id_bibrec=%s
                   """, (recid, ))
 
         return res[0][0]
 
 def has_copies(recid):
     """
     Indicate if there are any physical copies of a document described
     by the record
 
     @param recid: The identifier of the record
     @type recid: int
 
     @return True or False according to the state
     """
-    return get_number_copies(recid) != 0
-
-
-def has_copies(recid):
-    """
-    Indicate if there are any physical copies of a document described
-    by the record
-
-    @param recid: The identifier of the record
-    @type recid: int
-
-    @return True or False according to the state
-    """
-    return get_number_copies(recid) != 0;
+    return (get_number_copies(recid) != 0)
 
 def bor_loans_historical_overview(borrower_id):
     """
     Get loans historical overview of a given borrower_id.
 
     @param borrower_id: identify the borrower. Primary key of crcBORROWER.
     @type borrower_id: int
 
     @return list with loans historical overview.
     """
     res = run_sql("""SELECT l.id_bibrec,
                             l.barcode,
                             lib.name,
                             it.location,
                             DATE_FORMAT(l.loaned_on,'%%Y-%%m-%%d'),
                             DATE_FORMAT(l.due_date,'%%Y-%%m-%%d'),
                             l.returned_on,
                             l.number_of_renewals,
                             l.overdue_letter_number
                      FROM crcLOAN l, crcITEM it, crcLIBRARY lib
                      WHERE l.id_crcBORROWER=%s and
                            lib.id = it.id_crcLIBRARY and
                            it.barcode = l.barcode and
                            l.status = %s
                 """, (borrower_id, CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED))
     return res
 
 def bor_requests_historical_overview(borrower_id):
     """
     Get requests historical overview of a given borrower_id.
 
     @param borrower_id: identify the borrower. Primary key of crcBORROWER.
     @type borrower_id: int
 
     @return list with requests historical overview.
     """
     res = run_sql("""SELECT lr.id_bibrec,
                             lr.barcode,
                             lib.name,
                             it.location,
                             DATE_FORMAT(lr.period_of_interest_from,'%%Y-%%m-%%d'),
                             DATE_FORMAT(lr.period_of_interest_to,'%%Y-%%m-%%d'),
                             lr.request_date
                        FROM crcLOANREQUEST lr, crcITEM it, crcLIBRARY lib
                       WHERE lr.id_crcBORROWER=%s and
                             lib.id = it.id_crcLIBRARY and
                             it.barcode = lr.barcode and
                             lr.status =%s
                 """, (borrower_id, CFG_BIBCIRCULATION_REQUEST_STATUS_DONE))
     return res
 
 def get_item_loans_historical_overview(recid):
     """
     @param recid: identify the record. Primary key of bibrec.
     @type recid: int
     """
     res = run_sql("""SELECT bor.name,
                             bor.id,
                             l.barcode,
                             lib.name,
                             it.location,
                             DATE_FORMAT(l.loaned_on,'%%Y-%%m-%%d'),
                             DATE_FORMAT(l.due_date,'%%Y-%%m-%%d'),
                             l.returned_on,
                             l.number_of_renewals,
                             l.overdue_letter_number
                      FROM crcLOAN l, crcBORROWER bor, crcITEM it, crcLIBRARY lib
                      WHERE l.id_crcBORROWER=bor.id and
                            lib.id = it.id_crcLIBRARY and
                            it.barcode = l.barcode and
                            l.id_bibrec = %s and
                            l.status = %s """
                   , (recid, CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED))
 
     return res
 
 
 def get_item_requests_historical_overview(recid):
     """
     recid: identify the record. It is also the primary key of
            the table bibrec.
     """
 
     res = run_sql("""
                   SELECT bor.name,
                          bor.id,
                          lr.barcode,
                          lib.name,
                          it.location,
                          DATE_FORMAT(lr.period_of_interest_from,'%%Y-%%m-%%d'),
                          DATE_FORMAT(lr.period_of_interest_to,'%%Y-%%m-%%d'),
                          lr.request_date
                   FROM crcLOANREQUEST lr, crcBORROWER bor, crcITEM it, crcLIBRARY lib
                   WHERE lr.id_crcBORROWER=bor.id and
                         lib.id = it.id_crcLIBRARY and
                         it.barcode = lr.barcode and
                         lr.id_bibrec = %s and
                         lr.status = %s
                   """, (recid, CFG_BIBCIRCULATION_REQUEST_STATUS_DONE))
 
     return res
 
 
 def get_library_details(library_id):
     """
     library_id: identify the library. It is also the primary key of
             the table crcLIBRARY.
     """
     res = run_sql("""SELECT id, name, address, email, phone, type, notes
                      FROM crcLIBRARY
                      WHERE id=%s;
                      """, (library_id, ))
 
     if res:
         return res[0]
     else:
         return None
 
 def get_main_libraries():
     """
     library_id: identify the library. It is also the primary key of
             the table crcLIBRARY.
     """
     res = run_sql("""SELECT id, name
                      FROM crcLIBRARY
                      WHERE type=%s
                      """, (CFG_BIBCIRCULATION_LIBRARY_TYPE_MAIN, ))
 
     if res:
         return res
     else:
         return None
 
 def get_loan_request_details(req_id):
 
     res = run_sql("""SELECT lr.id_bibrec,
                             bor.name,
                             bor.id,
                             lib.name,
                             it.location,
                             DATE_FORMAT(lr.period_of_interest_from,'%%Y-%%m-%%d'),
                             DATE_FORMAT(lr.period_of_interest_to,'%%Y-%%m-%%d'),
                             lr.request_date
                        FROM crcLOANREQUEST lr,
                             crcBORROWER bor,
                             crcITEM it,
                             crcLIBRARY lib
                       WHERE lr.id_crcBORROWER=bor.id AND it.barcode=lr.barcode
                         AND lib.id = it.id_crcLIBRARY
                         AND lr.id=%s
                    """, (req_id, ))
 
     if res:
         return res[0]
     else:
         return None
 
 def get_loan_request_by_status(status):
     """
     status: request status.
     """
 
     query = """SELECT DISTINCT
                         lr.id,
                         lr.id_bibrec,
                         bor.name,
                         bor.id,
                         lib.name,
                         it.location,
                         DATE_FORMAT(lr.period_of_interest_from,'%%Y-%%m-%%d'),
                         DATE_FORMAT(lr.period_of_interest_to,'%%Y-%%m-%%d'),
                         lr.request_date
                    FROM crcLOANREQUEST lr,
                         crcBORROWER bor,
                         crcITEM it,
                         crcLIBRARY lib
                   WHERE lr.id_crcBORROWER=bor.id AND it.barcode=lr.barcode AND
                         lib.id = it.id_crcLIBRARY AND lr.status=%s """
 
 
     res = run_sql(query , (status, ))
     return res
 
 
 
 def update_loan_request_status(request_id, status):
     """
     request_id: identify the hold request. It is also the primary key
                 of the table crcLOANREQUEST.
 
     status: new request status.
     """
     return int(run_sql("""UPDATE  crcLOANREQUEST
                              SET  status=%s
                            WHERE  id=%s""",
                        (status, request_id)))
 
 def get_all_requests():
     """
     Retrieve all requests.
     """
     res = run_sql("""SELECT lr.id,
                             bor.id,
                             bor.name,
                             lr.id_bibrec,
                             lr.status,
                             DATE_FORMAT(lr.period_of_interest_from,'%%Y-%%m-%%d'),
                             DATE_FORMAT(lr.period_of_interest_to,'%%Y-%%m-%%d'),
                             lr.request_date
                      FROM   crcLOANREQUEST lr,
                             crcBORROWER bor
                      WHERE  bor.id = lr.id_crcBORROWER
                             AND (lr.status=%s OR lr.status=%s)
                             AND lr.period_of_interest_to >= CURDATE()
                             ORDER BY lr.request_date
                     """, (CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING,
                           CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING))
 
     return res
 
 def get_item_requests(recid):
     """
     recid: identify the record. It is also the primary key of
            the table bibrec.
     """
     res = run_sql("""SELECT bor.id,
                             bor.name,
                             lr.id_bibrec,
                             lr.status,
                             lib.name,
                             it.location,
                             DATE_FORMAT(lr.period_of_interest_from,'%%Y-%%m-%%d'),
                             DATE_FORMAT(lr.period_of_interest_to,'%%Y-%%m-%%d'),
                             lr.id,
                             lr.request_date
                      FROM   crcLOANREQUEST lr,
                             crcBORROWER bor,
                             crcITEM it,
                             crcLIBRARY lib
                      WHERE  bor.id = lr.id_crcBORROWER and lr.id_bibrec=%s
                             and lr.status!=%s and lr.status!=%s
                             and lr.barcode = it.barcode and lib.id = it.id_crcLIBRARY
                      """, (recid,
                            CFG_BIBCIRCULATION_REQUEST_STATUS_DONE,
                            CFG_BIBCIRCULATION_REQUEST_STATUS_CANCELLED))
 
     return res
 
 
 def get_all_requests_for_item_order_by_status(recid):
     """
     recid: identify the record. It is also the primary key of
            the table bibrec.
     """
     res = run_sql("""SELECT bor.id,
                             bor.name,
                             lr.id_bibrec,
                             lr.status,
                             DATE_FORMAT(lr.period_of_interest_from,'%%Y-%%m-%%d'),
                             DATE_FORMAT(lr.period_of_interest_to,'%%Y-%%m-%%d')
                      FROM   crcLOANREQUEST lr,
                             crcBORROWER bor
                      WHERE  bor.id = lr.id_crcBORROWER
                        AND  lr.id_bibrec=%s
                        AND  lr.status!=%s
                    ORDER BY status
                      """, (recid, CFG_BIBCIRCULATION_REQUEST_STATUS_DONE))
 
     return res
 
 def get_all_requests_for_item_order_by_name(recid):
     """
     recid: identify the record. It is also the primary key of
            the table bibrec.
     """
     res = run_sql("""SELECT bor.id,
                             bor.name,
                             lr.id_bibrec,
                             lr.status,
                             DATE_FORMAT(lr.period_of_interest_from,'%%Y-%%m-%%d'),
                             DATE_FORMAT(lr.period_of_interest_to,'%%Y-%%m-%%d')
                      FROM   crcLOANREQUEST lr,
                             crcBORROWER bor
                      WHERE  bor.id = lr.id_crcBORROWER
                        AND  lr.id_bibrec=%s
                        AND  lr.status!=%s
                    ORDER BY name
                      """, (recid, CFG_BIBCIRCULATION_REQUEST_STATUS_DONE))
 
     return res
 
 def get_all_requests_order_by_status():
     """
     Get all requests ORDER BY status.
     """
     res = run_sql("""SELECT bor.id,
                             bor.name,
                             lr.id_bibrec,
                             lr.status,
                             DATE_FORMAT(lr.period_of_interest_from,'%%Y-%%m-%%d'),
                             DATE_FORMAT(lr.period_of_interest_to,'%%Y-%%m-%%d')
                      FROM   crcLOANREQUEST lr,
                             crcBORROWER bor
                      WHERE  bor.id = lr.id_crcBORROWER and lr.status!=%s ORDER BY status
                            """, (CFG_BIBCIRCULATION_REQUEST_STATUS_DONE, ))
 
     return res
 
 def get_all_requests_order_by_name():
     """
     Get all requests ORDER BY name.
     """
     res = run_sql("""SELECT bor.id,
                             bor.name,
                             lr.id_bibrec,
                             lr.status,
                             DATE_FORMAT(lr.period_of_interest_from,'%%Y-%%m-%%d'),
                             DATE_FORMAT(lr.period_of_interest_to,'%%Y-%%m-%%d')
                      FROM   crcLOANREQUEST lr,
                             crcBORROWER bor
                      WHERE  bor.id = lr.id_crcBORROWER and lr.status!=%s ORDER BY name
                          """, (CFG_BIBCIRCULATION_REQUEST_STATUS_DONE, ))
     return res
 
 
 
 def get_all_requests_order_by_item():
     """
     Get all requests ORDER BY item.
     """
     res = run_sql("""SELECT bor.id,
                             bor.name,
                             lr.id_bibrec,
                             lr.status,
                             DATE_FORMAT(lr.period_of_interest_from,'%%Y-%%m-%%d'),
                             DATE_FORMAT(lr.period_of_interest_to,'%%Y-%%m-%%d')
                      FROM   crcLOANREQUEST lr,
                             crcBORROWER bor
                      WHERE  bor.id = lr.id_crcBORROWER and lr.status!=%s ORDER BY id_bibrec
                   """, (CFG_BIBCIRCULATION_REQUEST_STATUS_DONE, ))
 
     return res
 
 def get_borrower_details(borrower_id):
     """
     borrower_id: identify the borrower. It is also the primary key of
                  the table crcBORROWER.
     """
     res =  run_sql("""SELECT id, ccid, name, email, phone, address, mailbox
                         FROM crcBORROWER
                        WHERE id=%s""", (borrower_id, ))
     if res:
         return res[0]
     else:
         return None
 
 def get_borrower_name(borrower_id):
     """
     borrower_id: identify the borrower. It is also the primary key of
                  the table crcBORROWER.
     """
     res = run_sql("""SELECT name
                        FROM crcBORROWER
                       WHERE id=%s
                   """, (borrower_id, ))
 
     if res:
         return res[0][0]
     else:
         return None
 
 def loan_on_desk_confirm(barcode, borrower_id):
     """
     barcode: identify the item. It is the primary key of the table
              crcITEM.
 
     borrower_id: identify the borrower. It is also the primary key of
                  the table crcBORROWER.
     """
     res = run_sql("""SELECT it.id_bibrec, bor.name
                        FROM crcITEM it, crcBORROWER bor
                       WHERE it.barcode=%s and bor.id=%s
                   """, (barcode, borrower_id))
 
     return res
 
 def search_borrower_by_name(string):
     """
     string: search pattern.
     """
     string = string.replace("'", "\\'")
 
     res = run_sql("""SELECT id, name
                        FROM crcBORROWER
                       WHERE upper(name) like upper('%%%s%%')
                    ORDER BY name
                   """ % (string))
 
     return res
 
 def search_borrower_by_email(string):
     """
     string: search pattern.
     """
 
     res = run_sql("""SELECT id, name
                        FROM crcBORROWER
                       WHERE email regexp %s
                      """, (string, ))
 
     return res
 
 
 
 def search_borrower_by_phone(string):
     """
     string: search pattern.
     """
 
     res = run_sql("""SELECT id, name
                        FROM crcBORROWER
                       WHERE phone regexp %s
                      """, (string, ))
 
     return res
 
 
 def search_borrower_by_id(string):
     """
     string: search pattern.
     """
 
     res = run_sql("""SELECT id, name
                        FROM crcBORROWER
                       WHERE id=%s
                      """, (string, ))
 
     return res
 
 def search_borrower_by_ccid(string):
     """
     string: search pattern.
     """
 
     res = run_sql("""SELECT id, name
                        FROM crcBORROWER
                       WHERE ccid regexp %s
                      """, (string, ))
 
     return res
 
 def search_user_by_email(string):
     """
     string: search pattern.
     """
 
     res = run_sql(""" SELECT id, email
                         FROM user
                        WHERE email regexp %s
                   """, (string, ))
 
     return res
 
 
 def get_borrower_loan_details(borrower_id):
     """
     borrower_id: identify the borrower. It is also the primary key of
                  the table crcBORROWER.
     """
 
     res = run_sql("""
                   SELECT it.id_bibrec,
                          l.barcode,
                          DATE_FORMAT(l.loaned_on,'%%Y-%%m-%%d'),
                          DATE_FORMAT(l.due_date,'%%Y-%%m-%%d'),
                          l.number_of_renewals,
                          l.overdue_letter_number,
                          DATE_FORMAT(l.overdue_letter_date,'%%Y-%%m-%%d'),
                          l.type,
                          l.notes,
                          l.id,
                          l.status
                     FROM crcLOAN l, crcITEM it
                    WHERE l.barcode=it.barcode
                      AND id_crcBORROWER=%s
                      AND l.status!=%s
     """, (borrower_id, CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED))
 
     return res
 
 
 def get_borrower_request_details(borrower_id):
     """
     borrower_id: identify the borrower. It is also the primary key of
                  the table crcBORROWER.
     """
 
     res = run_sql("""SELECT lr.id_bibrec,
                             lr.status,
                             lib.name,
                             it.location,
                             DATE_FORMAT(lr.period_of_interest_from,'%%Y-%%m-%%d'),
                             DATE_FORMAT(lr.period_of_interest_to,'%%Y-%%m-%%d'),
                             lr.request_date,
                             lr.id
                      FROM   crcLOANREQUEST lr,
                             crcITEM it,
                             crcLIBRARY lib
                      WHERE  lr.id_crcBORROWER=%s
                        AND  (lr.status=%s OR lr.status=%s)
                             and lib.id = it.id_crcLIBRARY and lr.barcode = it.barcode
                             """, (borrower_id,
                                   CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING,
                                   CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING))
 
     return res
 
 def get_borrower_request_details_order_by_item(borrower_id):
     """
     borrower_id: identify the borrower. It is also the primary key of
                  the table crcBORROWER.
     """
 
     res = run_sql("""SELECT lr.id_crcBORROWER,
                             lr.id_bibrec,
                             lr.status,
                             DATE_FORMAT(lr.period_of_interest_from,'%%Y-%%m-%%d'),
                             DATE_FORMAT(lr.period_of_interest_to,'%%Y-%%m-%%d')
                        FROM crcLOANREQUEST lr
                       WHERE lr.id_crcBORROWER =%s and lr.status!=%s
                    ORDER BY id_bibrec
                     """, (borrower_id, CFG_BIBCIRCULATION_REQUEST_STATUS_DONE))
 
     return res
 
 
 def get_borrower_request_details_order_by_status(borrower_id):
     """
     borrower_id: identify the borrower. It is also the primary key of
                  the table crcBORROWER.
     """
 
     res = run_sql("""SELECT lr.id_crcBORROWER,
                             lr.id_bibrec,
                             lr.status,
                             DATE_FORMAT(lr.period_of_interest_from,'%%Y-%%m-%%d'),
                             DATE_FORMAT(lr.period_of_interest_to,'%%Y-%%m-%%d')
                        FROM crcLOANREQUEST lr
                       WHERE lr.id_crcBORROWER =%s and lr.status!=%s
                       ORDER BY status
                             """, (borrower_id,
                                   CFG_BIBCIRCULATION_REQUEST_STATUS_DONE))
 
     return res
 
 
 def get_borrower_request_details_order_by_from(borrower_id):
     """
     borrower_id: identify the borrower. It is also the primary key of
                  the table crcBORROWER.
     """
 
     res = run_sql("""SELECT lr.id_crcBORROWER,
                             lr.id_bibrec,
                             lr.status,
                             DATE_FORMAT(lr.period_of_interest_from,'%%Y-%%m-%%d'),
                             DATE_FORMAT(lr.period_of_interest_to,'%%Y-%%m-%%d')
                        FROM crcLOANREQUEST lr
                       WHERE lr.id_crcBORROWER =%s and lr.status!=%s
                    ORDER BY period_of_interest_from
                             """, (borrower_id,
                                   CFG_BIBCIRCULATION_REQUEST_STATUS_DONE))
 
     return res
 
 
 def get_borrower_request_details_order_by_to(borrower_id):
     """
     borrower_id: identify the borrower. It is also the primary key of
                  the table crcBORROWER.
     """
 
     res = run_sql("""SELECT lr.id_crcBORROWER,
                             lr.id_bibrec,
                             lr.status,
                             DATE_FORMAT(lr.period_of_interest_from,'%%Y-%%m-%%d'),
                             DATE_FORMAT(lr.period_of_interest_to,'%%Y-%%m-%%d')
                      FROM   crcLOANREQUEST lr
                      WHERE  lr.id_crcBORROWER =%s and lr.status!=%s
                    ORDER BY period_of_interest_to
                 """, (borrower_id, CFG_BIBCIRCULATION_REQUEST_STATUS_DONE))
 
     return res
 
 def new_loan(borrower_id, recid, barcode,
              due_date, status, loan_type, notes):
     """
     Create a new loan.
 
     borrower_id: identify the borrower. It is also the primary key of
                  the table crcBORROWER.
 
     recid: identify the record. It is also the primary key of
            the table bibrec.
 
     barcode: identify the item. It is the primary key of the table
              crcITEM.
 
     loaned_on: loan date.
 
     due_date: due date.
 
     status: loan status.
 
     loan_type: loan type(normal, ILL, etc...)
 
     notes: loan notes.
     """
 
     res = run_sql(""" insert into crcLOAN (id_crcBORROWER, id_bibrec,
                                            barcode, loaned_on, due_date,
                                            status, type, notes)
                       values(%s, %s, %s, NOW(), %s, %s ,%s, %s)
                   """, (borrower_id, recid, barcode, due_date,
                         status, loan_type, str(notes)))
 
     res = run_sql(""" UPDATE crcITEM
                          SET status=%s
                        WHERE barcode=%s""", (status, barcode))
 
     return res
 
 def get_item_loans(recid):
     """
     recid: identify the record. It is also the primary key of
            the table bibrec.
     """
 
     res = run_sql(
     """
     SELECT bor.id,
            bor.name,
            l.barcode,
            DATE_FORMAT(l.loaned_on,'%%Y-%%m-%%d'),
            DATE_FORMAT(l.due_date,'%%Y-%%m-%%d'),
            l.number_of_renewals,
            l.overdue_letter_number,
            DATE_FORMAT(l.overdue_letter_date,'%%Y-%%m-%%d'),
            l.status,
            l.notes,
            l.id
     FROM crcLOAN l, crcBORROWER bor, crcITEM it
     WHERE l.id_crcBORROWER = bor.id
           and l.barcode=it.barcode
           and l.id_bibrec=%s
           and l.status!=%s
     """, (recid, CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED))
 
     return res
 
 def get_all_loans(limit):
     """
     Get all loans.
     """
 
     res = run_sql("""
         SELECT bor.id,
                bor.name,
                it.id_bibrec,
                l.barcode,
                DATE_FORMAT(l.loaned_on,'%%Y-%%m-%%d %%T'),
                DATE_FORMAT(l.due_date,'%%Y-%%m-%%d'),
                l.number_of_renewals,
                l.overdue_letter_number,
                DATE_FORMAT(l.overdue_letter_date,'%%Y-%%m-%%d'),
                l.notes,
                l.id
           FROM crcLOAN l, crcBORROWER bor, crcITEM it
          WHERE l.id_crcBORROWER = bor.id
            AND l.barcode = it.barcode
            AND l.status = %s
       ORDER BY 5 DESC
          LIMIT 0,%s
     """, (CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN, limit))
 
     return res
 
 def get_all_expired_loans():
     """
     Get all expired(overdue) loans.
     """
     res = run_sql(
     """
     SELECT bor.id,
            bor.name,
            it.id_bibrec,
            l.barcode,
            DATE_FORMAT(l.loaned_on,'%%Y-%%m-%%d'),
            DATE_FORMAT(l.due_date,'%%Y-%%m-%%d'),
            l.number_of_renewals,
            l.overdue_letter_number,
            DATE_FORMAT(l.overdue_letter_date,'%%Y-%%m-%%d'),
            l.notes,
            l.id
     FROM crcLOAN l, crcBORROWER bor, crcITEM it
     WHERE l.id_crcBORROWER = bor.id
           and l.barcode = it.barcode
           and ((l.status = %s and l.due_date < CURDATE())
                   or l.status = %s )
     """, (CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN,
           CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED))
 
     return res
 
 
 def get_overdue_loans():
     """
     Get overdue loans.
     """
     res = run_sql(
     """
     SELECT bor.id,
            bor.name,
            bor.email,
            it.id_bibrec,
            l.barcode,
            DATE_FORMAT(l.loaned_on,'%Y-%m-%d'),
            DATE_FORMAT(l.due_date,'%Y-%m-%d'),
            l.number_of_renewals,
            l.overdue_letter_number,
            DATE_FORMAT(l.overdue_letter_date,'%Y-%m-%d'),
            l.notes,
            l.id
     FROM crcLOAN l, crcBORROWER bor, crcITEM it
     WHERE l.id_crcBORROWER = bor.id
           and l.barcode = it.barcode
           and (l.status = %s and l.due_date < CURDATE())
     """, (CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN))
 
     return res
 
 
 def get_borrower_loans(borrower_id):
     """
     borrower_id: identify the borrower. It is also the primary key of
              the table crcBORROWER.
     """
 
     res = run_sql(""" SELECT id_bibrec,
                              barcode,
                              DATE_FORMAT(loaned_on,'%%Y-%%m-%%d'),
                              DATE_FORMAT(due_date,'%%Y-%%m-%%d'),
                              type
                       FROM crcLOAN
                       WHERE id_crcBORROWER=%s and status != %s
                   """, (borrower_id, CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED))
 
     return res
 
 def get_current_loan_id(barcode):
     res = run_sql(""" SELECT id
                         FROM crcLOAN
                        WHERE barcode=%s
                          AND (status=%s OR status=%s)
                   """, (barcode, CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN,
                         CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED))
 
     if res:
         return res[0][0]
 
 def update_due_date(loan_id, new_due_date):
     """
     loan_id: identify a loan. It is the primery key of the table
              crcLOAN.
 
     new_due_date: new due date.
     """
     return int(run_sql("""UPDATE  crcLOAN
                              SET  due_date=%s,
                                   number_of_renewals = number_of_renewals + 1
                            WHERE  id=%s""",
                        (new_due_date, loan_id)))
 
 def renew_loan(loan_id, new_due_date):
     run_sql("""UPDATE  crcLOAN
                   SET  due_date=%s,
                        number_of_renewals=number_of_renewals+1,
                        overdue_letter_number=0,
                        status=%s
                 WHERE  id=%s""", (new_due_date,
                                   CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN,
                                   loan_id))
 
 def get_queue_request(recid):
     """
     recid: identify the record. It is also the primary key of
            the table bibrec.
     """
     res = run_sql("""SELECT id_crcBORROWER,
                             status,
                             DATE_FORMAT(request_date,'%%Y-%%m-%%d') as rd
                        FROM crcLOANREQUEST
                       WHERE id_bibrec=%s
                         and (status=%s or status=%s)
                    ORDER BY rd
                   """, (recid, CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING,
                    CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING))
 
     return res
 
 def get_recid_borrower_loans(borrower_id):
     """
     borrower_id: identify the borrower. It is also the primary key of
                  the table crcBORROWER.
     """
 
     res = run_sql(""" SELECT id, id_bibrec, barcode
                       FROM crcLOAN
                       WHERE id_crcBORROWER=%s
                         AND status != %s
                         AND type != 'ill'
                   """, (borrower_id, CFG_BIBCIRCULATION_ILL_STATUS_RETURNED))
 
 
     return res
 
 def update_request_barcode(barcode, request_id):
     """
     Update the barcode of an hold request.
     barcode: new barcode (after update). It is also the
              primary key of the crcITEM table.
     request_id: identify the hold request who will be
                 cancelled. It is also the primary key of
                 the crcLOANREQUEST table.
     """
 
     run_sql("""UPDATE crcLOANREQUEST
                set barcode = %s
                WHERE id = %s
             """, (barcode, request_id))
 
 def get_historical_overview(borrower_id):
     """
     Get historical information overview (recid, loan date, return date
     and number of renewals).
     borrower_id: identify the borrower. All the old (returned) loans
                  associate to this borrower will be retrieved.
                  It is also the primary key of the crcBORROWER table.
     """
 
     res = run_sql("""SELECT id_bibrec,
                             DATE_FORMAT(loaned_on,'%%Y-%%m-%%d'),
                             returned_on,
                             number_of_renewals
                      FROM crcLOAN
                      WHERE id_crcBORROWER=%s and status=%s;
                   """, (borrower_id,
                         CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED))
 
     return res
 
 def get_borrower_requests(borrower_id):
     """
     Get the hold requests of a borrower.
     borrower_id: identify the borrower. All the hold requests
                  associate to this borrower will be retrieved.
                  It is also the primary key of the crcBORROWER table.
     """
     res = run_sql("""
                   SELECT id,
                          id_bibrec,
                          DATE_FORMAT(request_date,'%%Y-%%m-%%d'),
                          status
                   FROM   crcLOANREQUEST
                   WHERE  id_crcBORROWER=%s and
                          (status=%s or status=%s)""",
                   (borrower_id, CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING,
                    CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING))
 
     return res
 
 def cancel_request(request_id):
     """
     Cancel an hold request.
     request_id: identify the hold request who will be
                 cancelled. It is also the primary key of
                 the crcLOANREQUEST table.
     status: The new status of the hold request. In this case
             it will be CFG_BIBCIRCULATION_REQUEST_STATUS_CANCELLED.
     """
     run_sql("""UPDATE crcLOANREQUEST
                   SET status=%s
                 WHERE id=%s
             """, (CFG_BIBCIRCULATION_REQUEST_STATUS_CANCELLED, request_id))
 
 def get_nb_copies_on_loan(recid):
     """
     Get the number of copies on loan for a recid.
     recid: Invenio record identifier. The number of copies
            of this record will be retrieved.
     """
 
     res = run_sql("""SELECT count(barcode)
                      FROM crcITEM
                      WHERE id_bibrec=%s and status=%s;
                      """, (recid, CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN))
 
     return res[0][0]
 
 
 def get_loans_notes(loan_id):
     """
     Get loan's notes.
     loan_id: identify the loan. The notes of
              this loan will be retrieved. It is
              also the primary key of the table
              crcLOAN.
     """
 
     res = run_sql("""SELECT notes
                      FROM crcLOAN
                      WHERE id=%s
                      """, (loan_id, ))
 
     if res:
         return res[0][0]
     else:
         return None
 
 def add_new_note(new_note, borrower_id):
     """
     Add a new borrower's note.
     new_note: note who will be added.
     borrower_id: identify the borrower. A new note will be
                  associate to this borrower. It is also
                  the primary key of the crcBORROWER table.
     """
     run_sql("""UPDATE crcBORROWER
                set notes=concat(notes,%s)
                WHERE id=%s;
                 """, (new_note, borrower_id))
 
 def add_new_loan_note(new_note, loan_id):
     """
     Add a new loan's note.
     new_note: note who will be added.
     loan_id: identify the loan. A new note will
              added to this loan. It is also the
              primary key of the table crcLOAN.
     """
     run_sql("""UPDATE crcLOAN
                set notes=concat(notes,%s)
                WHERE id=%s;
                 """, (new_note, loan_id))
 
 def get_borrower_id_by_email(email):
     """
     Retrieve borrower's id by email.
     """
 
     res = run_sql("""SELECT id
                        FROM crcBORROWER
                       WHERE email=%s""",
                   (email, ))
 
     if res:
         return res[0][0]
     else:
         return None
 
 def new_borrower(ccid, name, email, phone, address, mailbox, notes):
     """
     Add/Register a new borrower on the crcBORROWER table.
     name: borrower's name.
     email: borrower's email.
     phone: borrower's phone.
     address: borrower's address.
     """
 
     return run_sql("""insert into crcBORROWER ( ccid,
                                                 name,
                                                 email,
                                                 phone,
                                                 address,
                                                 mailbox,
                                                 borrower_since,
                                                 borrower_until,
                                                 notes)
         values(%s, %s, %s, %s, %s, %s, NOW(), '0000-00-00 00:00:00', %s)""",
         (ccid, name, email, phone, address, mailbox, notes))
     # IntegrityError: (1062, "Duplicate entry '665119' for key 2")
 
 def get_borrower_address(email):
     """
     Get the address of a borrower using the email.
     email: borrower's email.
     """
 
     res = run_sql("""SELECT address
                      FROM crcBORROWER
                      WHERE email=%s""", (email, ))
 
     if len(res[0][0]) > 0:
         return res[0][0]
     else:
         return 0
 
 def add_borrower_address(address, email):
     """
     Add the email and the address of a borrower.
     address: borrower's address.
     email: borrower's email.
     """
 
     run_sql("""UPDATE crcBORROWER
                set address=%s
                WHERE email=%s""", (address, email))
 
 
 def get_invenio_user_email(uid):
     """
     Get the email of an invenio's user.
     uid: identify an invenio's user.
     """
 
     res = run_sql("""SELECT email
                      FROM user
                      WHERE id=%s""",
                   (uid, ))
 
     if res:
         return res[0][0]
     else:
         return None
 
 def get_borrower_notes(borrower_id):
     """
     Get the notes of a borrower.
     borrower_id: identify the borrower. The data associate
                  to this borrower will be retrieved. It is also
                  the primary key of the crcBORROWER table.
     """
 
     res = run_sql("""SELECT notes
                      FROM   crcBORROWER
                      WHERE id=%s""",
                   (borrower_id, ))
 
     if res:
         return res[0][0]
     else:
         return None
 
 def update_loan_status(status, loan_id):
     """
     Update the status of a loan.
     status: new status (after update)
     loan_id: identify the loan who will be updated.
              It is also the primary key of the table
              crcLOAN.
     """
     run_sql("""UPDATE crcLOAN
                set status = %s
                WHERE id = %s""",
             (status, loan_id))
 
 def get_loan_due_date(loan_id):
     """
     Get the due date of a loan.
     loan_id: identify the loan. The due date of
              this loan will be retrieved. It is
              also the primary key of the table
              crcLOAN.
     """
 
     res = run_sql("""SELECT DATE_FORMAT(due_date, '%%Y-%%m-%%d')
                      FROM crcLOAN
                      WHERE id = %s""",
                   (loan_id, ))
 
     if res:
         return res[0][0]
     else:
         return None
 
 def get_pdf_request_data(status):
     """
     status: request status.
     """
     res = run_sql("""SELECT DISTINCT
                             lr.id_bibrec,
                             bor.name,
                             lib.name,
                             it.location,
                             DATE_FORMAT(lr.period_of_interest_from,'%%Y-%%m-%%d'),
                             DATE_FORMAT(lr.period_of_interest_to,'%%Y-%%m-%%d'),
                             lr.request_date
                      FROM   crcLOANREQUEST lr,
                             crcBORROWER bor,
                             crcITEM it,
                             crcLIBRARY lib
                      WHERE  lr.id_crcBORROWER=bor.id AND
                             it.id_bibrec=lr.id_bibrec AND
                             lib.id = it.id_crcLIBRARY AND
                             lr.status=%s;
                   """ ,
                      (status, ))
     return res
 
 def get_last_loan():
     """
     Get the recid, the borrower_id and the due date of
     the last loan who was registered on the crcLOAN table.
     """
 
     res = run_sql("""SELECT id_bibrec,
                             id_crcBORROWER,
                             DATE_FORMAT(due_date, '%Y-%m-%d')
                      FROM   crcLOAN ORDER BY id DESC LIMIT 1""")
 
     if res:
         return res[0]
     else:
         return None
 
 def get_borrower_data_by_id(borrower_id):
     """
     Retrieve borrower's data by borrower_id.
     """
 
     res = run_sql("""SELECT id, ccid, name, email, phone,
                             address, mailbox
                        FROM crcBORROWER
                       WHERE id=%s""", (borrower_id, ))
 
     if res:
         return res[0]
     else:
         return None
 
 def get_borrower_data(borrower_id):
     """
     Get the borrower's information (name, address and email).
     borrower_id: identify the borrower. The data associate
                  to this borrower will be retrieved. It is also
                  the primary key of the crcBORROWER table.
     """
 
     res = run_sql("""SELECT name,
                             address,
                             mailbox,
                             email
                      FROM   crcBORROWER
                      WHERE  id=%s""",
                   (borrower_id, ))
 
     if res:
         return res[0]
     else:
         return None
 
 def update_borrower_info(borrower_id, name, email, phone, address, mailbox):
     """
     Update borrower info.
 
     borrower_id: identify the borrower. It is also the primary key of
                  the table crcBORROWER.
     """
     return int(run_sql("""UPDATE crcBORROWER
                              set name=%s,
                                  email=%s,
                                  phone=%s,
                                  address=%s,
                                  mailbox=%s
                           WHERE  id=%s""",
                        (name, email, phone, address, mailbox, borrower_id)))
 
 def add_new_library(name, email, phone, address, lib_type, notes):
     """
     Add a new Library.
     """
 
     run_sql("""insert into crcLIBRARY (name, email, phone,
                                        address, type, notes)
                            values (%s, %s, %s, %s, %s, %s)""",
             (name, email, phone, address, lib_type, notes))
 
 def search_library_by_name(string):
     """
     string: search pattern.
     """
 
     string = string.replace("'", "\\'")
 
     res = run_sql("""SELECT id, name
                      FROM crcLIBRARY
                      WHERE upper(name) like upper('%%%s%%')
                      ORDER BY name
                      """ % (string))
 
     return res
 
 def search_library_by_email(string):
     """
     string: search pattern.
     """
 
     res = run_sql("""SELECT id, name
                      FROM crcLIBRARY
                      WHERE email regexp %s
                      ORDER BY name
                      """, (string, ))
     return res
 
 def get_all_libraries():
     """
     """
     res = run_sql("""SELECT id, name
                        FROM crcLIBRARY
                        ORDER BY name""")
 
     return res
 
 def update_library_info(library_id, name, email, phone, address, lib_type):
     """
     Update library information.
 
     library_id: identify the library. It is also the primary key of
                 the table crcLIBRARY.
     """
 
     return int(run_sql("""UPDATE crcLIBRARY
                              set name=%s,
                                  email=%s,
                                  phone=%s,
                                  address=%s,
                                  type=%s
                            WHERE id=%s""",
                        (name, email, phone, address, lib_type, library_id)))
 
 def get_internal_libraries():
     """
     Get Libraries
     """
 
     res = run_sql("""SELECT id, name
                        FROM crcLIBRARY
                        WHERE (type=%s OR type=%s)
                        ORDER BY name
                   """, (CFG_BIBCIRCULATION_LIBRARY_TYPE_INTERNAL,
                         CFG_BIBCIRCULATION_LIBRARY_TYPE_MAIN))
 
     return res
 
 def get_hidden_libraries():
     """
     Get Libraries
     """
 
     res = run_sql("""SELECT id, name
                        FROM crcLIBRARY
                        WHERE type=%s
                        ORDER BY name
                   """, (CFG_BIBCIRCULATION_LIBRARY_TYPE_HIDDEN, ))
 
     return res
 
 def get_library_name(library_id):
     """
     Get Library's name.
 
     library_id: identify the library. It is also the primary key of
                 the table crcLIBRARY.
     """
 
     res = run_sql("""SELECT name
                      FROM   crcLIBRARY
                      WHERE  id=%s""",
                   (library_id, ))
 
     if res:
         return res[0][0]
     else:
         return None
 
 def get_library_type(library_id):
     """
     Get Library's type.
 
     library_id: identify the library. It is also the primary key of
                 the table crcLIBRARY.
     """
 
     res = run_sql("""SELECT type
                      FROM   crcLIBRARY
                      WHERE  id=%s""",
                   (library_id, ))
 
     if res:
         return res[0][0]
     else:
         return None
 
 def add_new_copy(barcode, recid, library_id, collection, location, description,
                     loan_period, status, expected_arrival_date):
 
     """
     Add a new copy
 
     barcode: identify the item. It is the primary key of the table
              crcITEM.
 
     recid: identify the record. It is also the primary key of
        the table bibrec.
 
     library_id: identify the library. It is also the primary key of
                 the table crcLIBRARY.
     """
 
     run_sql("""insert into crcITEM (barcode, id_bibrec, id_crcLIBRARY,
                                 collection, location, description, loan_period,
                                 status, expected_arrival_date, creation_date,
                                 modification_date)
                 values (%s, %s, %s, %s, %s, %s, %s, %s, %s, NOW(), NOW())""",
             (barcode, recid, library_id, collection, location, description,
              loan_period, status, expected_arrival_date))
 
 def delete_copy(barcode):
     res = run_sql("""delete FROM crcITEM WHERE barcode=%s""", (barcode, ))
     return res
 
 def get_item_info(barcode):
     """
     Get item's information.
 
     barcode: identify the item. It is the primary key of the table
              crcITEM.
     """
 
     res = run_sql("""SELECT it.barcode,
                             it.id_crcLIBRARY,
                             lib.name,
                             it.collection,
                             it.location,
                             it.description,
                             it.loan_period,
                             it.status
                        FROM crcITEM it,
                             crcLIBRARY lib
                       WHERE it.barcode=%s and it.id_crcLIBRARY = lib.id""",
                   (barcode, ))
 
     if res:
         return res[0]
     else:
         return None
 
 def update_item_info(barcode, library_id, collection, location, description,
                  loan_period, status, expected_arrival_date):
     """
     Update item's information.
 
     barcode: identify the item. It is the primary key of the table
              crcITEM.
 
     library_id: identify the library. It is also the primary key of
                 the table crcLIBRARY.
     """
 
     int(run_sql("""UPDATE crcITEM
                       set barcode=%s,
                           id_crcLIBRARY=%s,
                           collection=%s,
                           location=%s,
                           description=%s,
                           loan_period=%s,
                           status=%s,
                           expected_arrival_date=%s,
                           modification_date=NOW()
                    WHERE  barcode=%s""",
                 (barcode, library_id, collection, location, description,
                  loan_period, status, expected_arrival_date, barcode)))
 
 def update_item_recid(barcode, new_recid):
     """
     Update item's information.
 
     barcode: identify the item. It is the primary key of the table
              crcITEM.
 
     library_id: identify the library. It is also the primary key of
                 the table crcLIBRARY.
     """
 
     res = run_sql("""UPDATE crcITEM
                         SET id_bibrec=%s,
                             modification_date=NOW()
                       WHERE barcode=%s""", (new_recid, barcode))
 
     return res
 
 def get_library_items(library_id):
     """
     Get all items who belong to a library.
 
     library_id: identify the library. It is also the primary key of
                 the table crcLIBRARY.
     """
     res = run_sql("""SELECT barcode, id_bibrec, collection,
                             location, description, loan_period, status, number_of_requests
                        FROM crcITEM
                       WHERE id_crcLIBRARY=%s""",
                   (library_id, ))
 
     return res
 
 def get_library_notes(library_id):
     """
     Get the notes of a library.
     library_id: identify the library. The data associate
                  to this library will be retrieved. It is also
                  the primary key of the crcLIBRARY table.
     """
 
     res = run_sql("""SELECT notes
                        FROM crcLIBRARY
                       WHERE id=%s""",
                   (library_id, ))
 
     if res:
         return res[0][0]
     else:
         return None
 
 def add_new_library_note(new_note, library_id):
     """
     Add a new borrower's note.
     new_note: note who will be added.
     library_id: identify the borrower. A new note will be
                  associate to this borrower. It is also
                  the primary key of the crcBORROWER table.
     """
     run_sql("""UPDATE crcLIBRARY
                   SET notes=concat(notes,%s)
                 WHERE id=%s;
                 """, (new_note, library_id))
 
 def get_borrower_data_by_name(name):
     """
     Retrieve borrower's data by name.
     """
 
     res = run_sql("""SELECT id, ccid, name, email, phone,
                             address, mailbox
                        FROM crcBORROWER
                       WHERE name regexp %s ORDER BY name""",
                   (name, ))
 
     return res
 
 
 def get_borrower_data_by_email(email):
     """
     Retrieve borrower's data by email.
     """
 
     res = run_sql("""SELECT id, ccid, name, email, phone,
                             address, mailbox
                        FROM crcBORROWER
                       WHERE email regexp %s""",
                   (email, ))
 
     return res
 
 
 
 def get_borrower_data_by_ccid(borrower_ccid):
     """
     Retrieve borrower's data by borrower_id.
     """
 
     res = run_sql("""SELECT id, ccid, name, email, phone,
                             address, mailbox
                        FROM crcBORROWER
                       WHERE ccid regexp %s""",
                   (borrower_ccid, ))
 
     return res
 
 def get_number_requests_per_copy(barcode):
     """
     barcode: identify the item. It is the primary key of the table
          crcITEM.
     """
 
     res = run_sql("""SELECT count(barcode)
                        FROM crcLOANREQUEST
                       WHERE barcode=%s and
                             (status != %s and status != %s)""",
                   (barcode, CFG_BIBCIRCULATION_REQUEST_STATUS_DONE,
                    CFG_BIBCIRCULATION_REQUEST_STATUS_CANCELLED))
 
     return res[0][0]
 
 
 def get_requested_barcode(request_id):
     """
     request_id: identify the hold request. It is also the primary key
                 of the table crcLOANREQUEST.
     """
 
     res = run_sql("""SELECT barcode
                        FROM crcLOANREQUEST
                       WHERE id=%s""",
                   (request_id, ))
 
     if res:
         return res[0][0]
     else:
         return None
 
 def get_borrower_recids(borrower_id):
     """
     borrower_id: identify the borrower. It is also the primary key of
                  the table crcBORROWER.
     """
 
     res = run_sql("""SELECT id_bibrec
                        FROM crcLOAN
                       WHERE id_crcBORROWER=%s""",
                   (borrower_id,))
 
     return res
 
 def get_borrower_loans_barcodes(borrower_id):
     """
     borrower_id: identify the borrower. It is also the primary key of
                  the table crcBORROWER.
     """
 
     res = run_sql("""SELECT barcode
                        FROM crcLOAN
                       WHERE id_crcBORROWER=%s
                         AND (status=%s OR status=%s)
                          """,
                   (borrower_id, CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN,
                    CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED))
 
     list_of_barcodes = []
     for bc in res:
         list_of_barcodes.append(bc[0])
 
     return list_of_barcodes
 
 def get_loan_status(loan_id):
     """
     Get loan's status
 
     loan_id: identify a loan. It is the primery key of the table
              crcLOAN.
     """
 
     res = run_sql("""SELECT status
                        FROM crcLOAN
                       WHERE id=%s""",
                   (loan_id, ))
 
     if res:
         return res[0][0]
     else:
         return None
 
 def get_loan_period(barcode):
     """
     Retrieve the loan period of a book.
 
     barcode: identify the item. It is the primary key of the table
              crcITEM.
     """
 
     res = run_sql("""SELECT loan_period
                        FROM crcITEM
                       WHERE barcode=%s""",
                   (barcode, ))
 
     if res:
         return res[0][0]
     else:
         return None
 
 def get_loan_infos(loan_id):
     """
     loan_id: identify a loan. It is the primery key of the table
              crcLOAN.
     """
 
     res =  run_sql("""SELECT l.id_bibrec,
                              l.barcode,
                              DATE_FORMAT(l.loaned_on, '%%Y-%%m-%%d'),
                              DATE_FORMAT(l.due_date, '%%Y-%%m-%%d'),
                              l.status,
                              it.loan_period,
                              it.status
                         FROM crcLOAN l, crcITEM it, crcLOANREQUEST lr
                        WHERE l.barcode=it.barcode and
                              l.id=%s""",
                    (loan_id, ))
 
     if res:
         return res[0]
     else:
         return None
 
 def is_item_on_loan(barcode):
     """
     Check if an item is on loan.
 
     barcode: identify the item. It is the primary key of the table crcITEM.
     """
 
     res = run_sql("""SELECT id
                        FROM crcLOAN
                       WHERE (status=%s or status=%s)
                         and barcode=%s""",
                   (CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN,
                    CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED, barcode))
 
     try:
         return res[0][0]
     except IndexError:
         return None
 
 
 def order_new_copy(recid, vendor_id, order_date, cost,
                    status, notes, expected_date):
 
     """
     Register a new copy that has been ordered.
     """
 
     run_sql("""insert into crcPURCHASE(id_bibrec, id_crcVENDOR,
                                        ordered_date, price,
                                        status, notes, expected_date)
                            values (%s, %s, %s, %s, %s, %s, %s)""",
                                     (recid, vendor_id, order_date, cost,
                                      status, notes, expected_date))
 
 def get_ordered_books():
     """
     Get the list with all the ordered books.
     """
 
     res = run_sql("""SELECT id, id_bibrec, id_crcVENDOR,
                             DATE_FORMAT(ordered_date,'%Y-%m-%d'),
                             DATE_FORMAT(expected_date, '%Y-%m-%d'),
                             price, status, notes
                        FROM crcPURCHASE""")
 
     return res
 
 def get_purchase_notes(purchase_id):
     """
     Get the notes of a purchase.
     library_id: identify the purchase. The data associate
                  to this library will be retrieved. It is also
                  the primary key of the crcPURCHASE table.
     """
 
     res = run_sql("""SELECT notes
                        FROM crcPURCHASE
                       WHERE id=%s""",
                   (purchase_id, ))
 
     if res:
         return res[0][0]
     else:
         return None
 
 def update_purchase_notes(purchase_id, purchase_notes):
     """
     """
 
     run_sql("""UPDATE crcPURCHASE
                   SET notes=%s
                 WHERE id=%s """, (str(purchase_notes), purchase_id))
 
 def add_new_purchase_note(new_note, purchase_id):
     """
     Add a new purchase's note.
     new_note: note who will be added.
     library_id: identify the purchase. A new note will be
                  associate to this purchase. It is also
                  the primary key of the crcPURCHASE table.
     """
     run_sql("""UPDATE crcPURCHASE
                   SET notes=concat(notes,%s)
                 WHERE id=%s;
             """, (new_note, purchase_id))
 
 
 
 def ill_register_request(item_info, borrower_id, period_of_interest_from,
                          period_of_interest_to, status, additional_comments,
                          only_edition, request_type, budget_code=''):
     """
     """
 
     run_sql("""insert into crcILLREQUEST(id_crcBORROWER,
                                 period_of_interest_from,
                                 period_of_interest_to, status, item_info,
                                 borrower_comments, only_this_edition,
                                 request_type, budget_code)
                     values (%s, %s, %s, %s, %s, %s, %s, %s, %s)""",
                         (borrower_id, period_of_interest_from,
                          period_of_interest_to, status, str(item_info),
                          additional_comments, only_edition,
                          request_type, budget_code))
 
 
 def ill_register_request_on_desk(borrower_id, item_info,
                                  period_of_interest_from,
                                  period_of_interest_to,
                                  status, notes, only_edition, request_type,
                                  budget_code=''):
     """
     """
 
     run_sql("""insert into crcILLREQUEST(id_crcBORROWER,
                                 period_of_interest_from, period_of_interest_to,
                                 status, item_info, only_this_edition,
                                 library_notes, request_type, budget_code)
                            values (%s, %s, %s, %s, %s, %s, %s, %s, %s)""",
             (borrower_id, period_of_interest_from, period_of_interest_to,
              status, str(item_info), only_edition, notes, request_type,
              budget_code))
 
 
 def get_ill_requests(status):
     """
     """
 
     if status == None:
         res = run_sql("""
                 SELECT ill.id, ill.id_crcBORROWER, bor.name,
                        ill.id_crcLIBRARY, ill.status,
                        DATE_FORMAT(ill.period_of_interest_from,'%%Y-%%m-%%d'),
                        DATE_FORMAT(ill.period_of_interest_to,'%%Y-%%m-%%d'),
                        DATE_FORMAT(ill.due_date,'%%Y-%%m-%%d'),
                        ill.item_info, ill.request_type
                   FROM crcILLREQUEST ill, crcBORROWER bor
                  WHERE ill.id_crcBORROWER=bor.id
                    AND (ill.request_type=%s OR ill.request_type=%s)
               ORDER BY ill.id desc
               """, ('article', 'book'))
     else:
         res = run_sql("""
                 SELECT ill.id, ill.id_crcBORROWER, bor.name,
                        ill.id_crcLIBRARY, ill.status,
                        DATE_FORMAT(ill.period_of_interest_from,'%%Y-%%m-%%d'),
                        DATE_FORMAT(ill.period_of_interest_to,'%%Y-%%m-%%d'),
                        DATE_FORMAT(ill.due_date,'%%Y-%%m-%%d'),
                        ill.item_info, ill.request_type
                   FROM crcILLREQUEST ill, crcBORROWER bor
                  WHERE ill.id_crcBORROWER=bor.id
                    AND (ill.request_type=%s OR ill.request_type=%s)
                    AND ill.status=%s
               ORDER BY ill.id desc
               """, ('article', 'book', status))
 
     return res
 
 def get_acquisitions(status):
     """
     """
 
     if status == None:
         res = run_sql("""
                 SELECT ill.id, ill.id_crcBORROWER, bor.name,
                        ill.id_crcLIBRARY, ill.status,
                        DATE_FORMAT(ill.period_of_interest_from,'%%Y-%%m-%%d'),
                        DATE_FORMAT(ill.period_of_interest_to,'%%Y-%%m-%%d'),
                        DATE_FORMAT(ill.due_date,'%%Y-%%m-%%d'),
                        ill.item_info, ill.cost, ill.request_type
                   FROM crcILLREQUEST ill, crcBORROWER bor
                  WHERE ill.id_crcBORROWER=bor.id
                    AND (ill.request_type=%s OR ill.request_type=%s)
               ORDER BY ill.id desc""", ('acq-standard', 'acq-book'))
     else:
         res = run_sql("""
                 SELECT ill.id, ill.id_crcBORROWER, bor.name,
                        ill.id_crcLIBRARY, ill.status,
                        DATE_FORMAT(ill.period_of_interest_from,'%%Y-%%m-%%d'),
                        DATE_FORMAT(ill.period_of_interest_to,'%%Y-%%m-%%d'),
                        DATE_FORMAT(ill.due_date,'%%Y-%%m-%%d'),
                        ill.item_info, ill.cost, ill.request_type
                   FROM crcILLREQUEST ill, crcBORROWER bor
                  WHERE ill.id_crcBORROWER=bor.id
                    AND (ill.request_type=%s OR ill.request_type=%s)
                    AND ill.status=%s
               ORDER BY ill.id desc""", ('acq-standard', 'acq-book', status))
 
     return res
 
 def search_ill_requests_title(title, date_from, date_to):
 
     title     = title.replace("'", "\\'")
     date_from = date_from.replace("'", "\\'")
     date_to   = date_to.replace("'", "\\'")
 
     tokens = title.split()
     tokens_query = ""
     for token in tokens:
         tokens_query += " AND ill.item_info like '%%%s%%' " % token
 
 
     query = """SELECT ill.id, ill.id_crcBORROWER, bor.name,
                       ill.id_crcLIBRARY, ill.status,
                       DATE_FORMAT(ill.period_of_interest_from,'%Y-%m-%d'),
                       DATE_FORMAT(ill.period_of_interest_to,'%Y-%m-%d'),
                       DATE_FORMAT(ill.due_date,'%Y-%m-%d'),
                       ill.item_info, ill.request_type
                  FROM crcILLREQUEST ill, crcBORROWER bor
                 WHERE ill.id_crcBORROWER=bor.id """
     query += tokens_query
     query += """  AND DATE_FORMAT(ill.request_date,'%%Y-%%m-%%d') >= '%s'
                   AND DATE_FORMAT(ill.request_date,'%%Y-%%m-%%d') <= '%s'
              ORDER BY ill.id desc""" % (date_from, date_to)
 
     return run_sql(query)
 
 
 def search_ill_requests_id(reqid, date_from, date_to):
 
     res = run_sql("""
                 SELECT ill.id, ill.id_crcBORROWER, bor.name,
                        ill.id_crcLIBRARY, ill.status,
                        DATE_FORMAT(ill.period_of_interest_from,'%%Y-%%m-%%d'),
                        DATE_FORMAT(ill.period_of_interest_to,'%%Y-%%m-%%d'),
                        DATE_FORMAT(ill.due_date,'%%Y-%%m-%%d'),
                        ill.item_info, ill.request_type
                   FROM crcILLREQUEST ill, crcBORROWER bor
                  WHERE ill.id_crcBORROWER=bor.id
                    AND ill.id = %s
                    AND DATE_FORMAT(ill.request_date,'%%Y-%%m-%%d') >=%s
                    AND DATE_FORMAT(ill.request_date,'%%Y-%%m-%%d') <=%s
               ORDER BY ill.id desc
                   """, (reqid, date_from, date_to))
 
     return res
 
 def search_acq_requests_cost(cost, date_from, date_to):
 
     cost = cost.replace("'", "\\'")
 
     res = run_sql("""
                 SELECT ill.id, ill.id_crcBORROWER, bor.name,
                        ill.id_crcLIBRARY, ill.status,
                        DATE_FORMAT(ill.period_of_interest_from,'%%Y-%%m-%%d'),
                        DATE_FORMAT(ill.period_of_interest_to,'%%Y-%%m-%%d'),
                        DATE_FORMAT(ill.due_date,'%%Y-%%m-%%d'),
                        ill.item_info, ill.cost, ill.request_type
                   FROM crcILLREQUEST ill, crcBORROWER bor
                  WHERE ill.id_crcBORROWER=bor.id
                    AND ill.cost like upper('%%%s%%')
                    AND (ill.request_type='acq-book'
                         OR ill.request_type='acq-standard')
                    AND DATE_FORMAT(ill.request_date,'%%Y-%%m-%%d') >= %s
                    AND DATE_FORMAT(ill.request_date,'%%Y-%%m-%%d') <= %s
               ORDER BY ill.id desc
                   """ % (cost.upper(), date_from, date_to))
 
     return res
 
 def search_acq_requests_notes(notes, date_from, date_to):
 
     notes = notes.replace("'", "\\'")
 
     res = run_sql("""
                 SELECT ill.id, ill.id_crcBORROWER, bor.name,
                        ill.id_crcLIBRARY, ill.status,
                        DATE_FORMAT(ill.period_of_interest_from,'%%Y-%%m-%%d'),
                        DATE_FORMAT(ill.period_of_interest_to,'%%Y-%%m-%%d'),
                        DATE_FORMAT(ill.due_date,'%%Y-%%m-%%d'),
                        ill.item_info, ill.cost, ill.request_type
                   FROM crcILLREQUEST ill, crcBORROWER bor
                  WHERE ill.id_crcBORROWER=bor.id
                    AND ill.library_notes like upper('%%%s%%')
                    AND (ill.request_type='acq-book'
                         OR ill.request_type='acq-standard')
                    AND DATE_FORMAT(ill.request_date,'%%Y-%%m-%%d') >= %s
                    AND DATE_FORMAT(ill.request_date,'%%Y-%%m-%%d') <= %s
               ORDER BY ill.id desc
                   """ % (notes.upper(), date_from, date_to))
 
     return res
 
 def get_ill_request_details(ill_request_id):
 
     res = run_sql("""SELECT id_crcLIBRARY,
                             DATE_FORMAT(request_date,'%%Y-%%m-%%d'),
                             DATE_FORMAT(expected_date,'%%Y-%%m-%%d'),
                             DATE_FORMAT(arrival_date,'%%Y-%%m-%%d'),
                             DATE_FORMAT(due_date,'%%Y-%%m-%%d'),
                             DATE_FORMAT(return_date,'%%Y-%%m-%%d'),
                             cost,
                             barcode,
                             library_notes,
                             status
                        FROM crcILLREQUEST
                       WHERE id=%s""", (ill_request_id, ))
 
     if res:
         return res[0]
     else:
         return None
 
 def get_ill_request_type(ill_request_id):
 
     """
     """
 
     res = run_sql("""SELECT request_type
                        FROM crcILLREQUEST
                       WHERE id=%s""", (ill_request_id, ))
 
     if res:
         return res[0][0]
     else:
         return None
 
 def get_ill_request_borrower_details(ill_request_id):
     """
     """
 
     res = run_sql("""
         SELECT ill.id_crcBORROWER, bor.name, bor.email, bor.mailbox,
                DATE_FORMAT(ill.period_of_interest_from,'%%Y-%%m-%%d'),
                DATE_FORMAT(ill.period_of_interest_to,'%%Y-%%m-%%d'),
                ill.item_info, ill.borrower_comments,
                ill.only_this_edition, ill.request_type
           FROM crcILLREQUEST ill, crcBORROWER bor
          WHERE ill.id_crcBORROWER=bor.id and ill.id=%s""", (ill_request_id, ))
 
     if res:
         return res[0]
     else:
         return None
 
 def get_acq_request_borrower_details(ill_request_id):
     """
     """
 
     res = run_sql("""
         SELECT ill.id_crcBORROWER, bor.name, bor.email, bor.mailbox,
                DATE_FORMAT(ill.period_of_interest_from,'%%Y-%%m-%%d'),
                DATE_FORMAT(ill.period_of_interest_to,'%%Y-%%m-%%d'),
                ill.item_info, ill.borrower_comments,
                ill.only_this_edition, ill.budget_code, ill.request_type
           FROM crcILLREQUEST ill, crcBORROWER bor
          WHERE ill.id_crcBORROWER=bor.id and ill.id=%s""", (ill_request_id, ))
 
     if res:
         return res[0]
     else:
         return None
 
 def get_ill_item_received(ill_request_id):
     """
     """
 
     res = run_sql("""SELECT id_crcLIBRARY,
                             DATE_FORMAT(request_date,'%%Y-%%m-%%d'),
                             DATE_FORMAT(expected_date,'%%Y-%%m-%%d'),
                             library_notes
                        FROM crcILLREQUEST
                       WHERE id=%s""", (ill_request_id, ))
 
     if res:
         return res[0]
     else:
         return None
 
 def get_ill_item_returned(ill_request_id):
     """
     """
 
     res = run_sql("""SELECT id_crcLIBRARY,
                             DATE_FORMAT(request_date,'%%Y-%%m-%%d'),
                             DATE_FORMAT(expected_date,'%%Y-%%m-%%d'),
                             DATE_FORMAT(arrival_date,'%%Y-%%m-%%d'),
                             DATE_FORMAT(due_date,'%%Y-%%m-%%d'),
                             barcode,
                             library_notes
                        FROM crcILLREQUEST
                       WHERE id=%s""", (ill_request_id, ))
 
     if res:
         return res[0]
     else:
         return None
 
 def get_ill_request_closed(ill_request_id):
     """
     """
 
     res = run_sql("""SELECT id_crcLIBRARY,
                             DATE_FORMAT(request_date,'%%Y-%%m-%%d'),
                             DATE_FORMAT(expected_date,'%%Y-%%m-%%d'),
                             DATE_FORMAT(arrival_date,'%%Y-%%m-%%d'),
                             DATE_FORMAT(due_date,'%%Y-%%m-%%d'),
                             DATE_FORMAT(return_date,'%%Y-%%m-%%d'),
                             cost,
                             barcode,
                             library_notes
                        FROM crcILLREQUEST
                       WHERE id=%s""", (ill_request_id, ))
 
     if res:
         return res[0]
     else:
         return None
 
 def get_external_libraries():
     """
     Get Libraries
     """
 
     res = run_sql("""SELECT id, name
                        FROM crcLIBRARY
                       WHERE type=%s
                 """, (CFG_BIBCIRCULATION_LIBRARY_TYPE_EXTERNAL, ))
 
     return res
 
 
 def update_ill_request(ill_request_id, library_id, request_date,
                        expected_date, arrival_date, due_date, return_date,
                        status, cost, barcode, library_notes):
     """
     Update an ILL request.
     """
 
     run_sql("""UPDATE crcILLREQUEST
                   SET id_crcLIBRARY=%s,
                       request_date=%s,
                       expected_date=%s,
                       arrival_date=%s,
                       due_date=%s,
                       return_date=%s,
                       status=%s,
                       cost=%s,
                       barcode=%s,
                       library_notes=%s
                 WHERE id=%s""",
             (library_id, request_date, expected_date,
              arrival_date, due_date, return_date, status, cost,
              barcode, library_notes, ill_request_id))
 
 def update_acq_request(ill_request_id, library_id, request_date,
                        expected_date, arrival_date, due_date, return_date,
                        status, cost, budget_code, library_notes):
     """
     Update an ILL request.
     """
 
     run_sql("""UPDATE crcILLREQUEST
                   SET id_crcLIBRARY=%s,
                       request_date=%s,
                       expected_date=%s,
                       arrival_date=%s,
                       due_date=%s,
                       return_date=%s,
                       status=%s,
                       cost=%s,
                       budget_code=%s,
                       library_notes=%s
                 WHERE id=%s""",
             (library_id, request_date, expected_date,
              arrival_date, due_date, return_date, status, cost,
              budget_code, library_notes, ill_request_id))
 
 def update_ill_request_status(ill_request_id, new_status):
 
     run_sql("""UPDATE crcILLREQUEST
                   SET status=%s
                 WHERE id=%s""", (new_status, ill_request_id))
 
 def update_ill_request_sent(ill_request_id, ill_status, library_id,
                             request_date, expected_date,
                             cost_format, barcode, library_notes):
     """
     """
 
     run_sql("""UPDATE crcILLREQUEST
                   SET status=%s,
                       id_crcLIBRARY=%s,
                       request_date=%s,
                       expected_date=%s,
                       cost=%s,
                       barcode=%s,
                       library_notes=%s
                 WHERE id=%s""", (ill_status, library_id,
                                  request_date, expected_date,
                                  cost_format, barcode, library_notes,
                                  ill_request_id))
 
 def update_ill_request_cancelled(ill_request_id, ill_status,
                                  cost_format, barcode, library_notes):
     """
     """
 
     run_sql("""UPDATE crcILLREQUEST
                   SET status=%s,
                       cost=%s,
                       barcode=%s,
                       library_notes=%s
                 WHERE id=%s""", (ill_status, cost_format,
                                  barcode, library_notes,
                                  ill_request_id))
 
 def update_ill_item_received(ill_request_id, ill_status,
                              arrival_date, due_date,
                              cost_format, barcode, library_notes):
     """
     """
 
     run_sql("""UPDATE crcILLREQUEST
                   SET status=%s,
                       arrival_date=%s,
                       due_date=%s,
                       cost=%s,
                       barcode=%s,
                       library_notes=%s
                 WHERE id=%s""", (ill_status,
                                  arrival_date, due_date,
                                  cost_format, barcode, library_notes,
                                  ill_request_id))
 
 def update_ill_item_returned(ill_request_id, ill_status,
                              return_date, cost_format,
                              library_notes):
     """
     """
 
     run_sql("""UPDATE crcILLREQUEST
                   SET status=%s,
                       return_date=%s,
                       cost=%s,
                       library_notes=%s
                 WHERE id=%s""", (ill_status, return_date,
                                  cost_format, library_notes,
                                  ill_request_id))
 
 def update_ill_request_closed(ill_request_id, ill_status, library_notes):
     """
     """
 
     run_sql("""UPDATE crcILLREQUEST
                   SET status=%s,
                       library_notes=%s
                 WHERE id=%s""", (ill_status,
                                  library_notes,
                                  ill_request_id))
 
 def get_order_details(purchase_id):
     """
     """
 
     res = run_sql("""SELECT id, id_bibrec, id_crcVENDOR,
                             DATE_FORMAT(ordered_date,'%%Y-%%m-%%d'),
                             DATE_FORMAT(expected_date,'%%Y-%%m-%%d'),
                             price, status, notes
                        FROM crcPURCHASE
                       WHERE id=%s""", (purchase_id, ))
 
     if res:
         return res[0]
     else:
         return None
 
 def update_purchase(purchase_id, recid, vendor_id, price,
                     status, order_date, expected_date, notes):
 
     """
     """
 
     run_sql("""UPDATE crcPURCHASE
                   SET id_bibrec=%s,
                       id_crcVENDOR=%s,
                       ordered_date=%s,
                       expected_date=%s,
                       price=%s,
                       status=%s,
                       notes=%s
                 WHERE id=%s""",
             (recid, vendor_id, order_date, expected_date, price, status,
              notes, purchase_id))
 
 def add_new_vendor(name, email, phone, address, notes):
     """
     Add a new vendor.
     """
 
     run_sql("""insert into crcVENDOR (name, email, phone,
                                       address, notes)
                            values (%s, %s, %s, %s, %s)""",
             (name, email, phone, address, notes))
 
 def search_vendor_by_name(string):
     """
     string: search pattern.
     """
 
     res = run_sql("""SELECT id, name
                        FROM crcVENDOR
                       WHERE name regexp %s
                      """, (string, ))
 
     return res
 
 def search_vendor_by_email(string):
     """
     string: search pattern.
     """
 
     res = run_sql("""SELECT id, name
                        FROM crcVENDOR
                       WHERE email regexp %s
                      """, (string, ))
 
     return res
 
 def get_all_vendors():
     """
     """
     res = run_sql("""SELECT id, name
                        FROM crcVENDOR""")
     return res
 
 def update_vendor_info(vendor_id, name, email, phone, address):
     """
     Update vendor information.
 
     vendor_id: identify the vendor. It is also the primary key of
                 the table crcVENDOR.
     """
     return int(run_sql("""UPDATE crcVENDOR
                              SET name=%s,
                                  email=%s,
                                  phone=%s,
                                  address=%s
                           WHERE  id=%s""",
                        (name, email, phone, address, vendor_id)))
 
 def get_vendors():
     """
     Get vendors
     """
 
     res = run_sql("""SELECT id, name
                        FROM crcVENDOR""")
 
     return res
 
 def get_vendor_details(vendor_id):
     """
     vendor_id: identify the vendor. It is also the primary key of
             the table crcVENDOR.
     """
     res = run_sql("""SELECT id, name, address, email, phone, notes
                        FROM crcVENDOR
                       WHERE id=%s;
                      """, (vendor_id, ))
 
     if res:
         return res[0]
     else:
         return None
 
 def get_vendor_notes(vendor_id):
     """
     Get the notes of a vendor.
     vendor_id: identify the vendor. The data associate
                to this vendor will be retrieved. It is also
                the primary key of the crcVENDOR table.
     """
 
     res = run_sql("""SELECT notes
                        FROM crcVENDOR
                       WHERE id=%s""",
                   (vendor_id, ))
 
     if res:
         return res[0][0]
     else:
         return None
 
 def add_new_vendor_note(new_note, vendor_id):
     """
     Add a new vendor's note.
     new_note:  note who will be added.
     vendor_id: identify the vendor. A new note will be
                associate to this vendor. It is also
                the primary key of the crcVENDOR table.
     """
     run_sql("""UPDATE crcVENDOR
                   SET notes=concat(notes,%s)
                 WHERE id=%s;
                 """, (new_note, vendor_id))
 
 def get_list_of_vendors():
     """
     Get vendors
     """
 
     res = run_sql("""SELECT id, name
                        FROM crcVENDOR""")
 
     return res
 
 def get_vendor_name(vendor_id):
     """
     Get Vendor's name.
 
     vendor_id: identify the vendor. It is also the primary key of
                 the table crcVENDOR.
     """
 
     res = run_sql("""SELECT name
                        FROM crcVENDOR
                       WHERE id=%s""",
                   (vendor_id, ))
 
     if res:
         return res[0][0]
     else:
         return None
 
 def get_ill_request_notes(ill_request_id):
     """
     """
 
     res = run_sql("""SELECT library_notes
                        FROM crcILLREQUEST
                       WHERE id=%s""",
                   (ill_request_id, ))
 
     if res:
         return res[0][0]
     else:
         return None
 
 def update_ill_request_notes(ill_request_id, library_notes):
     """
     """
 
     run_sql("""UPDATE crcILLREQUEST
                   SET library_notes=%s
                 WHERE id=%s""", (str(library_notes), ill_request_id))
 
 def update_ill_request_item_info(ill_request_id, item_info):
     """
     """
 
     run_sql("""UPDATE crcILLREQUEST
                   SET item_info=%s
                 WHERE id=%s""", (str(item_info), ill_request_id))
 
 def get_ill_borrower(ill_request_id):
     """
     """
 
     res = run_sql("""SELECT id_crcBORROWER
                        FROM crcILLREQUEST
                       WHERE id=%s""", (ill_request_id, ))
 
     if res:
         return res[0][0]
     else:
         return None
 
 def get_ill_barcode(ill_request_id):
     """
     """
 
     res = run_sql("""SELECT barcode
                        FROM crcILLREQUEST
                       WHERE id=%s""", (ill_request_id, ))
 
     if res:
         return res[0][0]
     else:
         return None
 
 def update_ill_loan_status(borrower_id, barcode, return_date, loan_type):
     """
     """
 
     run_sql("""UPDATE crcLOAN
                   SET status = %s,
                       returned_on = %s
                 WHERE id_crcBORROWER = %s
                   AND barcode = %s
                   AND type = %s """,
             (CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED,
              return_date, borrower_id, barcode, loan_type))
 
 def get_recid(barcode):
     """
     Get the id bibrec.
 
     barcode: identify the item. It is the primary key of the table
              crcITEM.
     """
 
     res = run_sql("""SELECT id_bibrec
                        FROM crcITEM
                       WHERE barcode=%s""", (barcode, ))
 
     try:
         return res[0][0]
     except IndexError:
         return None
 
 def get_ill_requests_details(borrower_id):
     """
     """
 
     res = run_sql("""SELECT id, item_info, id_crcLIBRARY,
                             DATE_FORMAT(request_date,'%%Y-%%m-%%d'),
                             DATE_FORMAT(expected_date,'%%Y-%%m-%%d'),
                             DATE_FORMAT(arrival_date,'%%Y-%%m-%%d'),
                             DATE_FORMAT(due_date,'%%Y-%%m-%%d'),
                             status, library_notes, request_type
                        FROM crcILLREQUEST
                       WHERE id_crcBORROWER=%s
                         AND status!=%s
                         AND status!=%s
                         AND status!=%s
                   """, (borrower_id, CFG_BIBCIRCULATION_ILL_STATUS_RETURNED,
                         CFG_BIBCIRCULATION_ILL_STATUS_RECEIVED,
                         CFG_BIBCIRCULATION_ILL_STATUS_CANCELLED))
 
     return res
 
 def bor_ill_historical_overview(borrower_id):
     """
     """
 
     res = run_sql("""SELECT id, item_info, id_crcLIBRARY,
                             DATE_FORMAT(request_date,'%%Y-%%m-%%d'),
                             DATE_FORMAT(expected_date,'%%Y-%%m-%%d'),
                             DATE_FORMAT(arrival_date,'%%Y-%%m-%%d'),
                             DATE_FORMAT(due_date,'%%Y-%%m-%%d'),
                             status, library_notes, request_type
                        FROM crcILLREQUEST
                       WHERE id_crcBORROWER=%s
                         AND (status=%s OR status=%s)
                         """, (borrower_id, CFG_BIBCIRCULATION_ILL_STATUS_RETURNED,
                               CFG_BIBCIRCULATION_ILL_STATUS_RECEIVED))
 
     return res
 
 def get_ill_notes(ill_id):
     """
     """
 
     res = run_sql("""SELECT library_notes
                        FROM crcILLREQUEST
                       WHERE id=%s""",
                   (ill_id, ))
 
     if res:
         return res[0][0]
     else:
         return None
 
 def update_ill_notes(ill_id, ill_notes):
     """
     """
 
     run_sql("""UPDATE crcILLREQUEST
                   SET library_notes=%s
                 WHERE id=%s """, (str(ill_notes), ill_id))
 
 def is_on_loan(barcode):
     """
     """
 
     res = run_sql("""SELECT id
                        FROM crcLOAN
                       WHERE barcode=%s
                         AND (status=%s or status=%s)
                       """, (barcode,
                             CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN,
                             CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED))
 
     if res:
         return True
     else:
         return False
 
 def is_requested(barcode):
     """
     """
 
     res = run_sql("""SELECT id
                        FROM crcLOANREQUEST
                       WHERE barcode=%s
                         AND (status = %s or status = %s)
                     """, (barcode,
                           CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING,
                           CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING))
 
     try:
         return res
     except IndexError:
         return None
 
 def get_lib_location(barcode):
     """
     """
 
     res = run_sql("""SELECT id_crcLIBRARY, location
                        FROM crcITEM
                       WHERE barcode=%s""",
                   (barcode, ))
 
     if res:
         return res[0]
     else:
         return None
 
 def get_barcodes(recid):
     """
     """
 
     res = run_sql("""SELECT barcode
                        FROM crcITEM
                       WHERE id_bibrec=%s""",
                   (recid, ))
 
     barcodes = []
     for i in range(len(res)):
         barcodes.append(res[i][0])
 
     return barcodes
 
 def barcode_in_use(barcode):
     """
     """
 
     res = run_sql("""SELECT id_bibrec
                        FROM crcITEM
                       WHERE barcode=%s""",
                   (barcode, ))
 
     if len(res)>0:
         return True
     else:
         return False
 
 def get_expired_loans_with_requests():
     """
     """
     res = run_sql("""SELECT DISTINCT
                             lr.id,
                             lr.id_bibrec,
                             lr.id_crcBORROWER,
                             it.id_crcLIBRARY,
                             it.location,
                             DATE_FORMAT(lr.period_of_interest_from,'%%Y-%%m-%%d'),
                             DATE_FORMAT(lr.period_of_interest_to,'%%Y-%%m-%%d'),
                             lr.request_date
                        FROM crcLOANREQUEST lr,
                             crcITEM it,
                             crcLOAN l
                       WHERE it.barcode=l.barcode
                         AND lr.id_bibrec=it.id_bibrec
                         AND (lr.status=%s or lr.status=%s)
                         AND (l.status=%s or (l.status=%s
                         AND l.due_date < CURDATE()))
                    ORDER BY lr.request_date;
                   """, ( CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING,
                          CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING,
                          CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED,
                          CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN))
     return res
 
 def get_total_of_loans():
     """
     """
 
     res = run_sql("""SELECT count(id)
                        FROM crcLOAN
                       WHERE status=%s
                   """, (CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN))
 
     return res[0][0]
 
 def update_borrower_notes(borrower_id, borrower_notes):
     """
     """
     run_sql("""UPDATE crcBORROWER
                   SET notes=%s
                 WHERE id=%s """, (str(borrower_notes), borrower_id))
 
 def get_loan_notes(loan_id):
     """
     """
 
     res = run_sql("""SELECT notes
                        FROM crcLOAN
                       WHERE id=%s""",
                   (loan_id, ))
 
     if res:
         return res[0][0]
     else:
         return None
 
 def update_loan_notes(loan_id, loan_notes):
     """
     """
     run_sql("""UPDATE crcLOAN
                   SET notes=%s
                 WHERE id=%s """, (str(loan_notes), loan_id))
 
 def update_library_notes(library_id, library_notes):
     """
     """
     run_sql("""UPDATE crcLIBRARY
                   SET notes=%s
                 WHERE id=%s """, (str(library_notes), library_id))
 
 def get_ill_book_info(ill_request_id):
     """
     """
 
     res = run_sql("""SELECT item_info
                        FROM crcILLREQUEST
                       WHERE id=%s""",
                   (ill_request_id, ))
 
     if res:
         return res[0][0]
     else:
         return None
 
 def get_copies_status(recid):
     """
     """
 
     res = run_sql("""SELECT status
                        FROM crcITEM
                       WHERE id_bibrec=%s""", (recid, ))
 
     list_of_statuses = []
     for status in res:
         list_of_statuses.append(status[0])
 
     if list_of_statuses == []:
         return None
     else:
         return list_of_statuses
 
     #if res:
     #    return res[0]
     #else:
     #    return None
 
 
 def get_loan_recid(loan_id):
     """
     """
 
     res = run_sql("""SELECT id_bibrec
                        FROM crcLOAN
                       WHERE id=%s""",
                   (loan_id, ))
 
     if res:
         return res[0][0]
     else:
         return None
 
 def update_loan_recid(barcode, new_recid):
 
     res = run_sql("""UPDATE crcLOAN
                         SET id_bibrec=%s
                       WHERE barcode=%s
                   """, (new_recid, barcode))
 
     return res
 
 
 def update_barcode(old_barcode, barcode):
 
     res = run_sql("""UPDATE crcITEM
                         SET barcode=%s
                       WHERE barcode=%s
                 """, (barcode, old_barcode))
 
     run_sql("""UPDATE crcLOAN
                   SET barcode=%s
                 WHERE barcode=%s
                 """, (barcode, old_barcode))
 
     run_sql("""UPDATE crcLOANREQUEST
                   SET barcode=%s
                 WHERE barcode=%s
                 """, (barcode, old_barcode))
 
     return res > 0
 
 def tag_requests_as_done(barcode, user_id):
     run_sql("""UPDATE crcLOANREQUEST
                   SET status=%s
                 WHERE barcode=%s
                   and id_crcBORROWER=%s
           """,  (CFG_BIBCIRCULATION_REQUEST_STATUS_DONE,
                  barcode, user_id))
 
 def get_expected_arrival_date(barcode):
     res = run_sql("""SELECT expected_arrival_date
                        FROM crcITEM
                       WHERE barcode=%s """, (barcode,))
     if res:
         return res[0][0]
     else:
         return ''
 
 def merge_libraries(library_from, library_to):
 
     run_sql("""UPDATE crcITEM
                   SET id_crcLIBRARY=%s
                 WHERE id_crcLIBRARY=%s
                   """, (library_to, library_from))
 
     run_sql("""UPDATE crcILLREQUEST
                   SET id_crcLIBRARY=%s
                 WHERE id_crcLIBRARY=%s
                   """, (library_to, library_from))
 
     run_sql("""DELETE FROM crcLIBRARY
                 WHERE id=%s
                   """, (library_from,))
 
 def get_borrower_ccid(user_id):
 
     res = run_sql("""SELECT ccid
                        FROM crcBORROWER
                       WHERE id=%s""", (user_id, ))
 
     if res:
         return res[0][0]
     else:
         return None
 
 def update_borrower(user_id, name, email, phone, address, mailbox):
     return run_sql(""" UPDATE crcBORROWER
                           SET name=%s,
                               email=%s,
                               phone=%s,
                               address=%s,
                               mailbox=%s
                         WHERE id=%s
             """, (name, email, phone, address, mailbox, user_id))
 
 def get_all_borrowers():
     res = run_sql("""SELECT id, ccid
                        FROM crcBORROWER""")
 
     return res
diff --git a/modules/bibcirculation/lib/bibcirculation_templates.py b/modules/bibcirculation/lib/bibcirculation_templates.py
index 237d1064c..0a3f03351 100644
--- a/modules/bibcirculation/lib/bibcirculation_templates.py
+++ b/modules/bibcirculation/lib/bibcirculation_templates.py
@@ -1,18048 +1,18045 @@
 # -*- coding: utf-8 -*-
 ##
 ## This file is part of Invenio.
 ## Copyright (C) 2008, 2009, 2010, 2011 CERN.
 ##
 ## Invenio is free software; you can redistribute it and/or
 ## modify it under the terms of the GNU General Public License as
 ## published by the Free Software Foundation; either version 2 of the
 ## License, or (at your option) any later version.
 ##
 ## Invenio is distributed in the hope that it will be useful, but
 ## WITHOUT ANY WARRANTY; without even the implied warranty of
 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 ## General Public License for more details.
 ##
 ## You should have received a copy of the GNU General Public License
 ## along with Invenio; if not, write to the Free Software Foundation, Inc.,
 ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 
 """ Templates for bibcirculation module """
 
 __revision__ = "$Id$"
 
 import datetime
 #import time
 import cgi
 
 from invenio.urlutils import create_html_link
 from invenio.config import CFG_SITE_URL, CFG_SITE_LANG, \
      CFG_CERN_SITE, CFG_SITE_SECURE_URL, CFG_SITE_RECORD, \
      CFG_SITE_NAME
 from invenio.bibcirculation_config import CFG_BIBCIRCULATION_LIBRARIAN_EMAIL
 from invenio.messages import gettext_set_language
 
 import invenio.bibcirculation_dblayer as db
 import invenio.dateutils as dateutils
 from invenio.search_engine import get_fieldvalues
 from invenio.bibcirculation_utils import get_book_cover, \
       book_information_from_MARC, \
       book_title_from_MARC, \
       renew_loan_for_X_days, \
       get_item_info_for_search_result, \
       all_copies_are_missing, \
       is_periodical
 
 from invenio.bibcirculation_config import \
     CFG_BIBCIRCULATION_ITEM_LOAN_PERIOD, \
     CFG_BIBCIRCULATION_COLLECTION, \
     CFG_BIBCIRCULATION_LIBRARY_TYPE, \
     CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN, \
     CFG_BIBCIRCULATION_LIBRARIAN_EMAIL, \
     CFG_BIBCIRCULATION_ITEM_STATUS, \
     CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN, \
     CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF, \
     CFG_BIBCIRCULATION_ITEM_STATUS_CANCELLED, \
     CFG_BIBCIRCULATION_ITEM_STATUS_NOT_ARRIVED, \
     CFG_BIBCIRCULATION_ITEM_STATUS_ON_ORDER, \
     CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED, \
     CFG_BIBCIRCULATION_REQUEST_STATUS_CANCELLED, \
     CFG_BIBCIRCULATION_ILL_STATUS_NEW, \
     CFG_BIBCIRCULATION_ILL_STATUS_REQUESTED, \
     CFG_BIBCIRCULATION_ILL_STATUS_ON_LOAN, \
     CFG_BIBCIRCULATION_ILL_STATUS_RETURNED, \
     CFG_BIBCIRCULATION_ILL_STATUS_CANCELLED, \
     CFG_BIBCIRCULATION_ILL_STATUS_RECEIVED, \
     CFG_BIBCIRCULATION_ITEM_LOAN_PERIOD, \
     CFG_BIBCIRCULATION_ACQ_STATUS_NEW, \
     CFG_BIBCIRCULATION_ACQ_STATUS_ON_ORDER, \
     CFG_BIBCIRCULATION_ACQ_STATUS_PARTIAL_RECEIPT, \
     CFG_BIBCIRCULATION_ACQ_STATUS_RECEIVED, \
     CFG_BIBCIRCULATION_ACQ_STATUS_CANCELLED, \
     CFG_BIBCIRCULATION_ACQ_TYPE, \
     CFG_BIBCIRCULATION_ACQ_STATUS
 
 
 def load_menu(ln=CFG_SITE_LANG):
 
     _ = gettext_set_language(ln)
 
     _MENU_ = """
 
       <div>
       <map name="Navigation_Bar" id="cdlnav">
       <div id="bibcircmenu" class="cdsweb">
       <!-- <h2><a name="localNavLinks">%(links)s:</a></h2> -->
       <ul>
       <!-- <li>
        <a href="%(url)s/admin2/bibcirculation">%(Home)s</a>
       </li> -->
 
     <li>
         <a href="%(url)s/admin2/bibcirculation/loan_on_desk_step1?ln=%(ln)s">%(Loan)s</a>
     </li>
 
     <li>
         <a href="%(url)s/admin2/bibcirculation/loan_return?ln=%(ln)s">%(Return)s</a>
     </li>
 
     <li>
         <a href="%(url)s/admin2/bibcirculation/borrower_search?redirect_to_new_request=yes&ln=%(ln)s">%(Request)s</a>
     </li>
 
     <li>
         <a href="%(url)s/admin2/bibcirculation/borrower_search?ln=%(ln)s">%(Borrowers)s</a>
     </li>
 
     <li>
         <a href="%(url)s/admin2/bibcirculation/item_search?ln=%(ln)s">%(Items)s</a>
     </li>
     """ % {'url': CFG_SITE_URL, 'links': _("Main navigation links"),
            'Home': _("Home"), 'Loan': _("Loan"), 'Return': _("Return"),
            'Request': _("Request"), 'Borrowers': _("Borrowers"),
            'Items': _("Items"), 'ln': ln}
 
     _MENU_ += """
 
     <li class="hassubmenu"> <a href="#">%(Lists)s</a>
         <ul class="submenu">
             <li><a href="%(url)s/admin2/bibcirculation/all_loans?ln=%(ln)s">%(Last_loans)s</a></li>
             <li><a href="%(url)s/admin2/bibcirculation/all_expired_loans?ln=%(ln)s">%(Overdue_loans)s</a></li>
             <li><a href="%(url)s/admin2/bibcirculation/get_pending_requests?ln=%(ln)s">%(Items_on_shelf_with_holds)s</a></li>
             <li><a href="%(url)s/admin2/bibcirculation/get_waiting_requests?ln=%(ln)s">%(Items_on_loan_with_holds)s</a></li>
             <li><a href="%(url)s/admin2/bibcirculation/get_expired_loans_with_requests?ln=%(ln)s">%(Overdue_loans_with_holds)s</a></li>
         <!--
             <li><a href="%(url)s/admin2/bibcirculation/ordered_books?ln=%(ln)s">%(Ordered_books)s</a></li>
         -->
         </ul>
     </li>
 
     <li class="hassubmenu"> <a href="#">%(Others)s</a>
         <ul class="submenu">
             <li> <a href="#">%(Libraries)s</a>
                 <ul class="subsubmenu">
                     <li><a href="%(url)s/admin2/bibcirculation/search_library_step1?ln=%(ln)s">%(Search)s...</a></li>
                     <li><a href="%(url)s/admin2/bibcirculation/add_new_library_step1?ln=%(ln)s">%(Add_new_library)s</a></li>
                     <li><a href="%(url)s/admin2/bibcirculation/update_library_info_step1?ln=%(ln)s">%(Update_info)s</a></li>
                 </ul>
             </li>
             <li> <a href="#">%(Acquisitions)s</a>
                 <ul class="subsubmenu">
                     <li><a href="%(url)s/admin2/bibcirculation/ordered_books?ln=%(ln)s">%(List_of_ordered_books)s</a></li>
                     <li><a href="%(url)s/admin2/bibcirculation/new_book_step1?ln=%(ln)s">%(Order_new_book)s</a></li>
                 </ul>
             </li>
             <li> <a href="#">%(Vendors)s</a>
                 <ul class="subsubmenu">
                     <li><a href="%(url)s/admin2/bibcirculation/search_vendor_step1?ln=%(ln)s">%(Search)s...</a></li>
                     <li><a href="%(url)s/admin2/bibcirculation/add_new_vendor_step1?ln=%(ln)s">%(Add_new_vendor)s</a></li>
                     <li><a href="%(url)s/admin2/bibcirculation/update_vendor_info_step1?ln=%(ln)s">%(Update_info)s</a></li>
                 </ul>
             </li>
         </ul>
     </li>
     """ % {'url': CFG_SITE_URL, 'Lists': _("Lists"),
            'Last_loans': _("Last loans"),
            'Overdue_loans': _("Overdue loans"),
            'Items_on_shelf_with_holds': _("Items on shelf with holds"),
            'Items_on_loan_with_holds': _("Items on loan with holds"),
            'Overdue_loans_with_holds': _("Overdue loans with holds"),
            'Ordered_books': _("Ordered books"), 'Others': _("Others"),
            'Libraries': _("Libraries"), 'Search': _("Search"),
            'Add_new_library': _("Add new library"),
            'Update_info': _("Update info"),
            'Acquisitions': _("Acquisitions"),
            'List_of_ordered_books': _("List of ordered books"),
            'Order_new_book': _("Order new book"),
            'Vendors': _("Vendors"),
            'Add_new_vendor': _("Add new vendor"),
            'ln': ln}
 
     _MENU_ += """
 
     <li class="hassubmenu"> <a href="#">%(ILL)s<!--Inter Library Loan--></a>
         <ul class="submenu">
             <li><a href="%(url)s/admin2/bibcirculation/register_ill_book_request?ln=%(ln)s">%(Register_Book_request)s</a></li>
             <li><a href="%(url)s/admin2/bibcirculation/register_ill_article_request_step1">%(Register_Article)s request</a></li>
              <li><a href="%(url)s/admin2/bibcirculation/register_purchase_request_step1?ln=%(ln)s">%(Register_Purchase_request)s</a></li>
             <li><a href="%(url)s/admin2/bibcirculation/ill_search?ln=%(ln)s">%(Search)s...</a></li>
             <li><a href="#">%(Lists)s</a>
                 <ul class="subsubmenu">
                     <li><a href="%(url)s/admin2/bibcirculation/list_ill_request?status=new&ln=%(ln)s">%(ILL)s - %(ill-new)s</a></li>
                     <li><a href="%(url)s/admin2/bibcirculation/list_ill_request?status=requested&ln=%(ln)s">%(ILL)s - %(Requested)s</a></li>
                     <li><a href="%(url)s/admin2/bibcirculation/list_ill_request?status=on loan&ln=%(ln)s">%(ILL)s - %(On_loan)s</a></li>
                     <li><a href="%(url)s/admin2/bibcirculation/list_acquisition?status=%(acq-new)s&ln=%(ln)s">%(Purchase)s - %(acq-new)s</a></li>
                     <li><a href="%(url)s/admin2/bibcirculation/list_acquisition?status=%(on_order)s&ln=%(ln)s">%(Purchase)s - %(on_order)s</a></li>
                 </ul>
             </li>
         </ul>
     </li>
 
     <li class="hassubmenu">
          <a href="#">%(Help)s</a>
         <ul class="submenu">
           <li><a href="%(url)s/help/admin/bibcirculation-admin-guide" target="_blank">%(Admin_guide)s</a></li>
              <!-- <li><a href="%(url)s/admin2/bibcirculation/help_contactsupport">%(Contact_Support)s</a></li> -->
         </ul>
     </li>
     </ul>
     <div class="clear"></div>
     </div>
     </map>
     </div>
     """ % {'url': CFG_SITE_URL, 'ILL': _("ILL"),
            'Register_Book_request': _("Register Book request"),
            'Register_Article': _("Register Article"),
            'Register_Purchase_request': _("Register purchase request"),
            'Search': _("Search"),
            'Lists': _("Lists"),
            'Purchase': _("Purchase"),
            'ill-new':  _(CFG_BIBCIRCULATION_ILL_STATUS_NEW),
            'acq-new':  _(CFG_BIBCIRCULATION_ACQ_STATUS_NEW),
            'on_order': _(CFG_BIBCIRCULATION_ACQ_STATUS_ON_ORDER),
            'Requested': _(CFG_BIBCIRCULATION_ILL_STATUS_REQUESTED),
            'On_loan':  _(CFG_BIBCIRCULATION_ILL_STATUS_ON_LOAN),
            'Help': _("Help"),
            'Admin_guide': _("Admin guide"),
            'Contact_Support': _("Contact Support"),
            'ln': ln}
 
     return _MENU_
 
 
 class Template:
     """Templates for BibCirculation module"""
 
     def tmpl_infobox(self, infos, ln=CFG_SITE_LANG):
         """
         Display len(infos) information fields
         @param infos: list of strings
         @param ln: language
         @return html output
         """
         _ = gettext_set_language(ln)
         if not((type(infos) is list) or (type(infos) is tuple)):
             infos = [infos]
         infobox = ""
         for info in infos:
             infobox += "<div class=\"infobox\">"
             lines = info.split("\n")
             for line in lines[0:-1]:
                 infobox += line + "<br />\n"
             infobox += lines[-1] + "</div><br />\n"
         return infobox
 
     def tmpl_holdings_information2(self, recid, req, holdings_info,
                                    ln=CFG_SITE_LANG):
         """
         This template is used in the user interface. In this template
         it is possible to see all details (loan period, number of copies, location, etc)
         about a book.
 
         @param recid: identify the record. Primary key of bibrec.
         @type recid: int
 
         @param holdings_info: book's information (all copies)
         @type holdings_info: list
         """
 
         from invenio.bibcirculationadminlib import is_adminuser
         (auth_code, _auth_message) = is_adminuser(req)
 
         _ = gettext_set_language(ln)
 
         if not book_title_from_MARC(recid):
             out = """<div align="center"
                      <div class="bibcircinfoboxmsg">%s</div>
                   """ % (_("This record does not exist."))
             return out
 
         elif not db.has_copies(recid):
             message = _("This record has no copies.")
 
 
             if auth_code == 0:
                 new_copy_link = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/add_new_copy_step3',
                                     {'recid': recid, 'ln': ln},
                                     _("Add a new copy"))
                 message += ' ' + new_copy_link
 
             out = """<div align="center"
                      <div class="bibcircinfoboxmsg">%s</div>
                   """ % (message)
             return out
 
         # verify if all copies are missing
         elif all_copies_are_missing(recid):
 
             ill_link = """<a href='%(url)s/ill/book_request_step1?%(ln)s'>%(ILL_services)s</a>
                        """ % {'url': CFG_SITE_URL, 'ln': ln,
                               'ILL_services': _("ILL services")}
 
             out = """<div align="center"
                      <div class="bibcircinfoboxmsg">%(message)s.</div>
                     """ % {'message': _('All the copies of %(strong_tag_open)s%(title)s%(strong_tag_close)s are missing. You can request a copy using %(strong_tag_open)s%(ill_link)s%(strong_tag_close)s') % {'strong_tag_open': '<strong>', 'strong_tag_close': '</strong>', 'title': book_title_from_MARC(recid), 'ill_link': ill_link}}
             return out
 
         # verify if there are no copies
         elif not holdings_info:
             out = """<div align="center"
                      <div class="bibcircinfoboxmsg">%s</div>
                 """ % (_("This item has no holdings."))
             return out
 
         out = """
             <style type="text/css"> @import url("/img/tablesorter.css"); </style>
             <script src="/js/jquery/jquery.js" type="text/javascript"></script>
             <script src="/js/jquery/jquery.tablesorter.js" type="text/javascript"></script>
             <script type="text/javascript">
             """
 
         if is_periodical(recid):
             out += """
             $(document).ready(function(){
                 $("#table_holdings")
                     .tablesorter({sortList: [[4,1]],
                                 widthFixed: true,
                                    widgets: ['zebra']})
                     .bind("sortStart",function(){$("#overlay").show();})
                     .bind("sortEnd",function(){$("#overlay").hide()})
                     .tablesorterPager({container: $("#pager"), positionFixed: false, size: 40});
             });
             </script>
             """
         else:
             out += """
             $(document).ready(function(){
                 $("#table_holdings")
                     .tablesorter({sortList: [[6,1],[1,0]],
                                 widthFixed: true,
                                    widgets: ['zebra']})
                     .bind("sortStart",function(){$("#overlay").show();})
                     .bind("sortEnd",function(){$("#overlay").hide()})
                     .tablesorterPager({container: $("#pager"), positionFixed: false});
             });
             </script>
             """
 
         out += """
                 <table id="table_holdings" class="tablesorter" border="0"
                                            cellpadding="0" cellspacing="1">
                     <thead>
                         <tr>
                             <th>%s</th>
                             <th>%s</th>
                             <th>%s</th>
                             <th>%s</th>
                             <th>%s</th>
                             <th>%s</th>
                             <th>%s</th>
                             <th>%s</th>
                             <th>%s</th>
                         </tr>
                     </thead>
                     <tbody>
                 """ % (_("Options"), _("Library"), _("Collection"),
                        _("Location"), _("Description"), _("Loan period"),
                        _("Status"), _("Due date"), _("Barcode"))
 
         for (barcode, library, collection, location, description,
              loan_period, status, due_date) in holdings_info:
 
             if loan_period == 'Reference':
                 request_button = '-'
             else:
                 request_button = """
                 <input type=button
                 onClick="location.href='%s/%s/%s/holdings/request?barcode=%s&ln=%s'"
                 value='%s' class="bibcircbutton" onmouseover="this.className='bibcircbuttonover'"
                 onmouseout="this.className='bibcircbutton'">
                 """ % (CFG_SITE_URL, CFG_SITE_RECORD, recid, barcode, ln, _("Request"))
 
             if status in (CFG_BIBCIRCULATION_ITEM_STATUS_ON_ORDER,
                           'claimed'):
                 expected_arrival_date = db.get_expected_arrival_date(barcode)
                 if expected_arrival_date != '':
                     status = status + ' - ' + expected_arrival_date
 
             if status != 'missing':
                 out += """
                 <tr>
                     <td>%s</td>
                     <td>%s</td>
                     <td>%s</td>
                     <td>%s</td>
                     <td>%s</td>
                     <td>%s</td>
                     <td>%s</td>
                     <td>%s</td>
                     <td align='center'>%s</td>
                 </tr>
                 """ % (request_button, library, collection or '-', location,
                        description or '-', loan_period, status,
                        due_date or '-', barcode)
 
         if auth_code != 0:
             bibcirc_link = ''
         else:
             bibcirc_link = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_item_details',
                                     {'recid': recid, 'ln': ln},
                                     _("See this book on BibCirculation"))
 
         out += """
             </tbody>
             </table>
             <div id="pager" class="pager">
                         <form>
                             <br />
                             <img src="/img/sb.gif" class="first" />
                             <img src="/img/sp.gif" class="prev" />
                             <input type="text" class="pagedisplay" />
                             <img src="/img/sn.gif" class="next" />
                             <img src="/img/se.gif" class="last" />
             """
 
         if is_periodical(recid):
             out += """
                             <select class="pagesize">
                                 <option value="10">10</option>
                                 <option value="20">20</option>
                                 <option value="30">30</option>
                                 <option value="40" selected="selected">40</option>
                             </select>
                 """
         else:
             out += """
                             <select class="pagesize">
                                 <option value="10" selected="selected">10</option>
                                 <option value="20">20</option>
                                 <option value="30">30</option>
                                 <option value="40">40</option>
                             </select>
                 """
         out += """
                         </form>
                     </div>
            <br />
            <br />
            <table class="bibcirctable">
              <tr>
                <td class="bibcirctableheader">%s</td>
              </tr>
            </table>
            """ % (bibcirc_link)
 
         return out
 
     def tmpl_book_not_for_loan(self, ln=CFG_SITE_LANG):
         _ = gettext_set_language(ln)
         message = """<div align="center"
                      <div class="bibcircinfoboxmsg">%s</div>
                   """ % (_("This item is not for loan."))
         return message
 
     def tmpl_message_sever_busy(self, ln=CFG_SITE_LANG):
         _ = gettext_set_language(ln)
         message = _('Server busy. Please, try again in a few seconds.')
         return message
 
     def tmpl_message_request_send_ok_cern(self, ln=CFG_SITE_LANG):
         _ = gettext_set_language(ln)
         message = _("Your request has been registered and the document will be sent to you via internal mail.")
         return message
 
     def tmpl_message_request_send_ok_other(self, ln=CFG_SITE_LANG):
         _ = gettext_set_language(ln)
         message = _("Your request has been registered.")
         return message
 
     def tmpl_message_request_send_fail_cern(self, ln=CFG_SITE_LANG):
         _ = gettext_set_language(ln)
         message = _("It is not possible to validate your request. ")
         message += _("Your office address is not available. ")
         message += _("Please contact %(librarian_email)s") \
                     % {'librarian_email': CFG_BIBCIRCULATION_LIBRARIAN_EMAIL}
         return message
 
     def tmpl_message_request_send_fail_other(self, ln=CFG_SITE_LANG):
         _ = gettext_set_language(ln)
         message = _("It is not possible to validate your request. ")
         message += _("Your office address is not available. ")
         message += _("Please contact %(librarian_email)s") \
                     % {'librarian_email': CFG_BIBCIRCULATION_LIBRARIAN_EMAIL}
         return message
 
     def tmpl_message_purchase_request_send_ok_other(self, ln=CFG_SITE_LANG):
         _ = gettext_set_language(ln)
         message = _("Your purchase request has been registered.")
         return message
 
     def tmpl_display_infos(self, infos, ln=CFG_SITE_LANG):
         """
         Returns a page where the only content are infoboxes.
 
         @param infos: messages to be displayed
         @type infos: list
 
         @param ln: language
         """
 
         _ = gettext_set_language(ln)
 
         out = load_menu(ln)
         out += """ <br /> """
 
         if type(infos) is not list or len(infos) == 0:
             out += """<div class="infobox">"""
             out += _("No messages to be displayed")
             out += """</div> <br /> """
         else:
             for info in infos:
                 out += """<div class="infobox">"""
                 out += info
                 out += """</div> <br /> """
 
         return out
 
     def tmpl_borrower_search_result(self, result, redirect_to_new_request=False,
                                           ln=CFG_SITE_LANG):
         """
         When the admin features 'borrower_seach' is used, this template
         show the result.
 
         @param result: search result
         @type result:list
 
         @param ln: language
         """
 
         _ = gettext_set_language(ln)
 
         out = """ """
 
         out += load_menu(ln)
 
         if len(result) == 0:
             if CFG_CERN_SITE:
                 message = _("0 borrowers found.") + ' ' +_("Search by CCID.")
             else:
                 new_borrower_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/add_new_borrower_step1',
                                 {'ln': ln}, _("Register new borrower."))
                 message = _("0 borrowers found.") + ' ' + new_borrower_link
 
             out += """
             <div class="bibcircbottom">
             <br />
             <div class="bibcircinfoboxmsg">%s</div>
             <br />
           """ % (message)
 
         else:
             out += """
         <style type="text/css"> @import url("/img/tablesorter.css"); </style>
         <div class="bibcircbottom" align="center">
         </form>
         <br />
         <table class="bibcirctable">
           <tr align="center">
             <td class="bibcirccontent">
               <strong>%s borrower(s) found</strong>
             </td>
           </tr>
         </table>
         <br />
         <table class="tablesortersmall" border="0" cellpadding="0" cellspacing="1">
           <th align="center">%s</th>
         """ % (len(result), _("Borrower(s)"))
 
 
             for (borrower_id, name) in result:
                 if redirect_to_new_request:
                     borrower_link = create_html_link(CFG_SITE_URL +
                             '/admin2/bibcirculation/create_new_request_step1',
                             {'borrower_id': borrower_id, 'ln': ln}, (name))
                 else:
                     borrower_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_borrower_details',
                                 {'borrower_id': borrower_id, 'ln': ln}, (name))
 
                 out += """
             <tr align="center">
                  <td width="70">%s
                  <input type=hidden name=uid value='%s'></td>
             </tr>
 
             """ % (borrower_link, borrower_id)
 
         out += """
              </table>
              <br />
              <table class="bibcirctable">
              <tr align="center">
                 <td>
                     <input type=button value='%s'
                            onClick="history.go(-1)"
                            class="formbutton">
                 </td>
              </tr>
         </table>
         <br />
         <br />
         <br />
         </form>
         </div>
         """ % (_("Back"))
 
         return out
 
     def tmpl_yourloans(self, loans, requests, borrower_id,
                        infos, ln=CFG_SITE_LANG):
         """
         When an user is logged in, it is possible to check his loans.
         In the section 'yourloans', it is also possible to renew a single
         loan or all loans.
 
         @param result: show all loans of an user who is logged in
         @param uid: user ID
         @param infos: display information about holdings
         @param ln: language
         """
         _ = gettext_set_language(ln)
 
         renew_all_link = create_html_link(CFG_SITE_SECURE_URL +
                             '/yourloans/display',
                             {'borrower_id': borrower_id, 'action': 'renew_all'},
                             (_("Renew all loans")))
 
         loanshistoricaloverview_link = create_html_link(CFG_SITE_SECURE_URL +
                                         '/yourloans/loanshistoricaloverview',
                                         {'ln': ln},
                                         (_("Loans - historical overview")))
 
         out = self.tmpl_infobox(infos, ln)
 
         if len(loans) == 0:
             out += """
             <div class="bibcirctop_bottom">
             <br />
             <br />
             <table class="bibcirctable_contents">
                  <td align="center" class="bibcirccontent">%s</td>
             </table>
             <br />
             <br />
             """ % (_("You don't have any book on loan."))
 
         else:
             out += """<br />
                       <style type="text/css"> @import url("/img/tablesorter.css"); </style>
                       <script src="/js/jquery/jquery.js" type="text/javascript"></script>
                       <script src="/js/jquery/jquery.tablesorter.js" type="text/javascript"></script>
                       <script type="text/javascript">
                       $(document).ready(function() {
                         $('#table_loans').tablesorter()
                       });
                       </script>
 
                       <table class="tablesortermedium" id="table_loans"
                              border="0" cellpadding="0" cellspacing="1">
                       <thead>
                         <tr>
                          <th>%s</th>
                          <th>%s</th>
                          <th>%s</th>
                          <th>%s</th>
                         </tr>
                       </thead>
                       <tbody>
                      """ % (_("Item"),
                             _("Loaned on"),
                             _("Due date"),
                             _("Action(s)"))
 
             for(recid, barcode, loaned_on, due_date, loan_type) in loans:
                 record_link = "<a href=" + CFG_SITE_URL + "/%s/%s>" % (CFG_SITE_RECORD, recid) + \
                               (book_title_from_MARC(recid)) + "</a>"
 
                 if loan_type == 'ill':
                     renew_link = '-'
                 else:
                     renew_link = create_html_link(CFG_SITE_SECURE_URL +
                                         '/yourloans/display',
                                         {'barcode': barcode, 'action': 'renew'},
                                         (_("Renew")))
 
                 out += """
                 <tr>
                   <td>%s</td>
                   <td>%s</td>
                   <td>%s</td>
                   <td>%s</td>
                 </tr>
                 """ % (record_link,
                        loaned_on,
                        due_date,
                        renew_link)
 
             out += """    </tbody>
                           </table>
                           <br />
                           <table class="bibcirctable">
                           <tr>
                           <td width="430"></td>
                           <td class="bibcirccontent" width="700">%s</td>
                           </tr>
                           </table>
                           <br />
                           <br />
                           <br />
                           """ % (renew_all_link)
 
         if len(requests) == 0:
             out += """
                    <h1 class="headline">%s</h1>
                    <div class="bibcirctop">
                    <br /> <br />
                    <table class="bibcirctable_contents">
                    <td align="center" class="bibcirccontent">%s</td>
                    </table>
                    <br /> <br />
                    <hr>
                    <br />
                    <table class="bibcirctable">
                    <tr>
                    <td class="bibcirccontent" width="70">%s</td>
                    </tr>
                    </table>
                    <br />
                    <table class="bibcirctable">
                    <tr>
                    <td>
                    <input type=button onClick="location.href='%s'" value='%s' class='formbutton'>
                    </td>
                    </tr>
                    </table>
                    <br />
                    """ % (_("Your Requests"),
                         _("You don't have any request (waiting or pending)."),
                         loanshistoricaloverview_link,
                         CFG_SITE_URL, _("Back to home"))
 
         else:
             out += """
                    <h1 class="headline">%s</h1>
                    <div class="bibcirctop">
                    <br />
                    <style type="text/css"> @import url("/img/tablesorter.css"); </style>
                    <script src="/js/jquery/jquery.js" type="text/javascript"></script>
                    <script src="/js/jquery/jquery.tablesorter.js" type="text/javascript"></script>
                    <script type="text/javascript">
                    $(document).ready(function() {
                         $('#table_requests').tablesorter()
                    });
                    </script>
                    <table class="tablesortermedium" id="table_requests"
                           border="0" cellpadding="0" cellspacing="1">
                    <thead>
                    <tr>
                      <th>%s</th>
                      <th>%s</th>
                      <th>%s</th>
                      <th>%s</th>
                    </tr>
                    </thead>
                    <tbody>
                    """ % (_("Your Requests"),
                           _("Item"),
                           _("Request date"),
                           _("Status"),
                           _("Action(s)"))
 
             for(request_id, recid, request_date, status) in requests:
 
                 record_link = "<a href=" + CFG_SITE_URL + "/%s/%s?ln=%s>" % (CFG_SITE_RECORD, recid, ln) + \
                               (book_title_from_MARC(recid)) + "</a>"
 
                 cancel_request_link = create_html_link(CFG_SITE_URL +
                                                 '/yourloans/display',
                                                 {'request_id': request_id,
                                                  'action': 'cancel',
                                                  'ln': ln},
                                                  (_("Cancel")))
                 out += """
                 <tr>
                   <td>%s</td>
                   <td>%s</td>
                   <td>%s</td>
                   <td>%s</td>
                 </tr>
                 """ % (record_link, request_date,
                        status, cancel_request_link)
 
             out += """     </tbody>
                           </table>
                           <br />
                           <br />
                           <br />
                           <hr>
                           <br />
                           <table class="bibcirctable">
                           <tr>
                           <td class="bibcirccontent" width="70">%s</td>
                           </tr>
                           </table>
                           <br />
                           <table class="bibcirctable">
                           <tr>
                           <td>
                           <input type=button
                                  onClick="location.href='%s'"
                                  value='%s'
                                  class='formbutton'>
                           </td>
                           </tr>
                           </table>
                           <br />
                           <br />
                           </div>
                           """ % (loanshistoricaloverview_link,
                                  CFG_SITE_URL,
                                  _("Back to home"))
 
         return out
 
     def tmpl_loanshistoricaloverview(self, result, ln=CFG_SITE_LANG):
         """
         In the section 'yourloans' it is possible to see the loans historical overview
         of the user who is logged in. Bibcirculation display all loans where the status is
         CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED.
 
         @param result: show all loans where status = CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED
         @param ln: language
         """
 
         _ = gettext_set_language(ln)
 
         out = """<div class="bibcirctop_bottom">
                     <br /> <br />
                     <style type="text/css"> @import url("/img/tablesorter.css"); </style>
                     <script src="/js/jquery/jquery.js" type="text/javascript"></script>
                     <script src="/js/jquery/jquery.tablesorter.js" type="text/javascript"></script>
                     <script type="text/javascript">
                     $(document).ready(function(){
                         $('#table_hist').tablesorter()
                     });
                     </script>
                     <table class="tablesortermedium" id="table_hist"
                            border="0" cellpadding="0" cellspacing="1">
                     <thead>
                     <tr>
                       <th>%s</th>
                       <th>%s</th>
                       <th>%s</th>
                       <th>%s</th>
                     </tr>
                     </thead>
                     <tbody>
                     """ % (_("Item"),
                            _("Loaned"),
                            _("Returned"),
                            _("Renewalls"))
 
         for(recid, loaned_on, returned_on, nb_renewalls) in result:
 
             record_link = "<a href=" + CFG_SITE_URL + "/%s/%s>" % (CFG_SITE_RECORD, recid) + \
                           (book_title_from_MARC(recid)) + "</a>"
 
             out += """
                 <tr>
                   <td>%s</td>
                   <td>%s</td>
                   <td>%s</td>
                   <td>%s</td>
                 </tr>
                 """ % (record_link, loaned_on,
                        returned_on, nb_renewalls)
 
         out += """</tbody>
                   </table>
                   <br />
                   <table class="bibcirctable">
                     <tr>
                         <td>
                             <input type=button value='%s'
                                    onClick="history.go(-1)" class="formbutton">
                         </td>
                     </tr>
                   </table>
                   <br />
                   <br />
                   </div>
                   """ % (_("Back"))
 
         return out
 
     def tmpl_new_request(self, recid, barcode, ln=CFG_SITE_LANG):
         """
         This template is used when an user want to request a book. Here it is
         possible to define the 'period of interest'
 
         @param uid: user ID
         @param recid: recID - Invenio record identifier
         @param barcode: book's barcode
         @param ln: language
         """
 
         _ = gettext_set_language(ln)
 
         today = datetime.date.today()
         gap = datetime.timedelta(days=180)
         more_6_months = (today + gap).strftime('%Y-%m-%d')
 
         out = """
         <style type="text/css"> @import url("/img/jquery/tablesorter.css"); </style>
         <link rel=\"stylesheet\" href=\"%s/img/jquery/jquery-ui.css\" type=\"text/css\" />
         <script type="text/javascript" language='JavaScript' src="%s/js/jquery/jquery.ui.datepicker.min.js"></script>
 
         <form name="request_form" action="%s/%s/%s/holdings/send" method="post" >
         <br />
         <div align=center>
           <table class="bibcirctable_contents" align=center>
             <tr>
               <td class="bibcirctableheader" align=center>%s</td>
             </tr>
           </table>
           <br />
 
           <table align=center class="tablesorterborrower" width="100" border="0" cellspacing="1" align="center">
 
             <tr align=center>
               <th align=center>%s</th>
               <td>
 
                 <script type="text/javascript">
                     $(function() {
                         $("#date_picker1").datepicker({dateFormat: 'yy-mm-dd', showOn: 'button', buttonImage: "%s/img/jquery/calendar.gif", buttonImageOnly: true});
                     });
                 </script>
                 <input type="text" size="12" id="date_picker1" name="period_from" value="%s" style='border: 1px solid #cfcfcf'>
 
               </td>
             </tr>
             <tr align=center>
               <th align=center>%s</th>
               <td>
 
                  <script type="text/javascript">
                     $(function() {
                         $("#date_picker2").datepicker({dateFormat: 'yy-mm-dd', showOn: 'button', buttonImage: "%s/img/jquery/calendar.gif", buttonImageOnly: true});
                     });
                 </script>
                 <input type="text" size="12" id="date_picker2" name="period_to" value="%s" style='border: 1px solid #cfcfcf'>
 
               </td>
             </tr>
           </table>
           </div>
           <br />
           <br />
           <table class="bibcirctable_contents">
           <input type=hidden name=barcode value='%s'>
             <tr>
               <td align="center">
                 <input type=button value='%s' onClick="history.go(-1)" class="formbutton">
                 <input type="submit" name="submit_button" value='%s' class="formbutton">
               </td>
             </tr>
           </table>
           <br />
           <br />
         </form>
         """ % (CFG_SITE_URL, CFG_SITE_URL,
                CFG_SITE_URL, CFG_SITE_RECORD, recid,
                _("Enter your period of interest"),
                _("From"), CFG_SITE_URL, today, _("To"),
                CFG_SITE_URL, more_6_months,
                barcode, _("Back"), _("Confirm"))
 
         return out
 
     def tmpl_new_request_send(self, message, ln=CFG_SITE_LANG):
         """
         This template is used in the user interface.
 
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         out = """
         <br />
         <br />
         <table class="bibcirctable">
             <tr>
                 <td class="bibcirccontent" width="30">%s</td>
             </tr>
             <tr>
                 <td class="bibcirccontent" width="30">%s</td>
             </tr>
         </table>
         <br />
         <br />
         <table class="bibcirctable">
             <td>
                 <input type=button onClick="location.href='%s'" value='%s' class='formbutton'>
             </td>
         </table>
         <br />
         <br />
         """ % (message,
                _("You can see your loans %(x_url_open)shere%(x_url_close)s."
                     % {'x_url_open': '<a href="' + CFG_SITE_URL + \
                        '/yourloans/display' + '">', 'x_url_close': '</a>'}),
                CFG_SITE_URL,
                _("Back to home"))
 
         return out
 
     def tmpl_next_loan_request_done(self, ln=CFG_SITE_LANG):
         """
         This template is used in the admin interface, when a request is
         'waiting' in the queue.
 
         @param ln: language of the page
         """
         _ = gettext_set_language(ln)
 
         out = load_menu(ln)
 
         out += """
         <div class="bibcircbottom">
             <br />
             <br />
             <table class="bibcirctable">
                 <td class="bibcirccontent" width="30">%s</td>
             </table>
             <br />
             <br />
             <table class="bibcirctable">
                 <td>
                     <input type=button
                            onClick="location.href='%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s'"
                            value='%s'
                            class='formbutton'>
                 </td>
             </table>
             <br />
             <br />
         </div>
         """ % (_("A new loan has been registered."),
                CFG_SITE_URL, ln,
                _("Back to home"))
 
         return out
 
     def tmpl_get_pending_requests(self, result, ln=CFG_SITE_LANG):
 
         """
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         out = load_menu(ln)
 
         out += """
             <style type="text/css"> @import url("/js/jquery/tablesorter/themes/blue/style.css"); </style>
             <style type="text/css"> @import url("/js/jquery/tablesorter/addons/pager/jquery.tablesorter.pager.css"); </style>
 
             <script src="/js/jquery/tablesorter/jquery.tablesorter.js" type="text/javascript"></script>
             <script src="/js/jquery/tablesorter/addons/pager/jquery.tablesorter.pager.js" type="text/javascript"></script>
             <script type="text/javascript">
 
             $(document).ready(function(){
                 $("#table_all_loans")
                     .tablesorter({sortList: [[4,0], [0,0]],widthFixed: true, widgets: ['zebra']})
                     .bind("sortStart",function(){$("#overlay").show();})
                     .bind("sortEnd",function(){$("#overlay").hide()})
                     .tablesorterPager({container: $("#pager"), positionFixed: false});
             });
             </script>
 
             <script type="text/javascript">
                 function confirmation(rqid) {
                   var answer = confirm("%s")
                   if (answer){
             window.location = "%s/admin2/bibcirculation/get_pending_requests?request_id="+rqid;
                     }
                   else{
                     alert("%s")
                     }
                  }
             </script>
 
             <br />
 
             <div class="bibcircbottom">
             """ % (_("Delete this request?"), CFG_SITE_URL,
                    _("Request not deleted."))
 
         if len(result) == 0:
             out += """
               <br />
               <table class="bibcirctable">
                 <tr>
                     <td class="bibcirccontent">%s</td>
                 </tr>
                 </table>
                 <br />
                 <table class="bibcirctable">
                 <tr>
                   <td>
                     <input type=button value='%s' onClick="history.go(-1)" class="formbutton">
                   </td>
                 </tr>
                 </table>
                 <br />
                 <br />
                 </div>
                 """ % (_("No more requests are pending."),
                        _("Back"))
 
         else:
             out += """
             <form name="borrower_form" action="%s/admin2/bibcirculation/all_loans" method="get" >
             <br />
             <table id="table_all_loans" class="tablesorter"
                    border="0" cellpadding="0" cellspacing="1">
                <thead>
                     <tr>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                     </tr>
               </thead>
               <tbody>
                     """ % (CFG_SITE_URL,
                             _("Name"),
                             _("Item"),
                             _('Library'),
                             _("Location"),
                             _("Vol."),
                             _("Ed."),
                             _("From"),
                             _("To"),
                             _("Request date"),
                             _("Actions"))
 
             for (request_id, recid, name, borrower_id, library, location,
                  date_from, date_to, request_date) in result:
 
                 title_link = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_item_details',
                                     {'recid': recid, 'ln': ln},
                                     (book_title_from_MARC(recid)))
 
                 borrower_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_borrower_details',
                                 {'borrower_id': borrower_id, 'ln': ln}, (name))
 
                 volume = get_fieldvalues(recid, "773__v")
 
                 if volume == []:
                     volume = ''
                 else:
                     volume = volume[0]
 
                 edition = get_fieldvalues(recid, "250__a")
 
                 if edition == []:
                     edition = ''
                 else:
                     edition = edition[0]
 
                 out += """
                 <tr>
                  <td width='150'>%s</td>
                  <td width='250'>%s</td>
                  <td>%s</td>
                  <td>%s</td>
                  <td>%s</td>
                  <td>%s</td>
                  <td>%s</td>
                  <td>%s</td>
                  <td>%s</td>
                  <td algin='center'>
                  <input type="button" value='%s' style="background: url(/img/jquery/dialog-cancel.png)
                  no-repeat; width: 75px; text-align: right;"
                  onClick="confirmation(%s)"
                  onmouseover="this.className='bibcircbuttonover'"
                  onmouseout="this.className='bibcircbutton'"
                  class="bibcircbutton">
 
                  <input type="button" value='%s' class="bibcircbutton"
                         style="background: url(/img/dialog-yes.png) no-repeat;
                         width: 150px; text-align: right;"
     onmouseover="this.className='bibcircbuttonover'"
     onmouseout="this.className='bibcircbutton'"
     onClick="location.href='%s/admin2/bibcirculation/associate_barcode?ln=%s&request_id=%s&recid=%s&borrower_id=%s'">
                  </td>
                 </tr>
                 """ % (borrower_link,
                        title_link,
                        library,
                        location,
                        volume,
                        edition,
                        date_from,
                        date_to,
                        request_date,
                        _("Delete"),
                        request_id,
                        _("Associate barcode"),
                        CFG_SITE_URL, ln,
                        request_id,
                        recid,
                        borrower_id)
 
             out += """
                     </tbody>
                     </table>
                     </form>
 
                     <div id="pager" class="pager">
                         <form>
                             <br />
                             <img src="/img/sb.gif" class="first" />
                             <img src="/img/sp.gif" class="prev" />
                             <input type="text" class="pagedisplay" />
                             <img src="/img/sn.gif" class="next" />
                             <img src="/img/se.gif" class="last" />
                             <select class="pagesize">
                                 <option value="10" selected="selected">10</option>
                                 <option value="20">20</option>
                                 <option value="30">30</option>
                                 <option value="40">40</option>
                             </select>
                         </form>
                     </div>
                     """
             out += """
                     <div class="back" style="position: relative; top: 5px;">
                         <br />
                         <table class="bibcirctable">
                             <tr>
                                 <td>
                                     <input type=button
                                            value='%s'
                                            onClick="history.go(-1)"
                                            class="formbutton">
                                 </td>
                             </tr>
                         </table>
                     <br />
                     <br />
                     </form>
                     </div>
                     </div>
                     """ % (_("Back"))
 
         return out
 
     def tmpl_get_waiting_requests(self, result, ln=CFG_SITE_LANG):
         """
         Template for the admin interface. Show pending requests(all, on loan, available)
 
         @param result: items with status = 'pending'
         @param ln: language
         """
 
         _ = gettext_set_language(ln)
 
         out = load_menu(ln)
 
         out += """
             <style type="text/css"> @import url("/js/jquery/tablesorter/themes/blue/style.css"); </style>
             <style type="text/css"> @import url("/js/jquery/tablesorter/addons/pager/jquery.tablesorter.pager.css"); </style>
 
             <script src="/js/jquery/tablesorter/jquery.tablesorter.js" type="text/javascript"></script>
             <script src="/js/jquery/tablesorter/addons/pager/jquery.tablesorter.pager.js" type="text/javascript"></script>
             <script type="text/javascript">
             $(document).ready(function(){
                 $("#table_all_loans")
                     .tablesorter({sortList: [[4,0], [0,0]],widthFixed: true, widgets: ['zebra']})
                     .bind("sortStart",function(){$("#overlay").show();})
                     .bind("sortEnd",function(){$("#overlay").hide()})
                     .tablesorterPager({container: $("#pager"), positionFixed: false});
             });
             </script>
 
             <br />
 
             <div class="bibcircbottom">
             """
 
         if len(result) == 0:
             out += """
               <br />
               <table class="bibcirctable">
                 <tr>
                     <td class="bibcirccontent">%s</td>
                 </tr>
                 </table>
                 <br />
                 <table class="bibcirctable">
                 <tr>
                   <td>
                     <input type=button value='%s' onClick="history.go(-1)" class="formbutton">
                   </td>
                 </tr>
                 </table>
                 <br />
                 <br />
                 </div>
                 """ % (_("No more requests are pending."),
                        _("Back"))
 
         else:
             out += """
             <form name="borrower_form" action="%s/admin2/bibcirculation/all_loans" method="get" >
             <br />
             <table id="table_all_loans" class="tablesorter"
                     border="0" cellpadding="0" cellspacing="1">
                <thead>
                     <tr>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                     </tr>
                 </thead>
                 <tbody>
          """% (CFG_SITE_URL,
                _("Name"),
                _("Item"),
                _('Library'),
                _("Location"),
                _("From"),
                _("To"),
                _("Request date"),
                _("Options"))
 
             out += """
                 <script type="text/javascript">
                     function confirmation(rqid) {
                         var answer = confirm("Delete this request?")
                         if (answer){
             window.location = "%s/admin2/bibcirculation/get_waiting_requests?request_id="+rqid;
                         }
                         else{
                             alert("%s")
                         }
                     }
                 </script>
                 """ % (CFG_SITE_URL, _("Request not deleted."))
 
             for (request_id, recid, name, borrower_id, library, location,
                  date_from, date_to, request_date) in result:
 
                 title_link = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_item_details',
                                     {'recid': recid, 'ln': ln},
                                     (book_title_from_MARC(recid)))
 
                 borrower_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_borrower_details',
                                 {'borrower_id': borrower_id, 'ln': ln}, (name))
 
                 out += """
                 <tr>
                  <td>%s</td>
                  <td>%s</td>
                  <td>%s</td>
                  <td>%s</td>
                  <td>%s</td>
                  <td>%s</td>
                  <td>%s</td>
                  <td align="center">
                  <input type="button" value='%s' style="background: url(/img/jquery/dialog-cancel.png)
                  no-repeat; width: 75px; text-align: right;"
                  onClick="confirmation(%s)"
                  class="bibcircbutton">
 
                  <input type=button
                         style="background: url(/img/dialog-yes.png) no-repeat;
                                width: 150px; text-align: right;"
 onClick="location.href='%s/admin2/bibcirculation/associate_barcode?ln=%s&request_id=%s&recid=%s&borrower_id=%s'"
                  value='%s' class="bibcircbutton">
                  </td>
                 </tr>
                 """ % (borrower_link,
                        title_link,
                        library,
                        location,
                        date_from,
                        date_to,
                        request_date,
                        _("Cancel"),
                        request_id,
                        CFG_SITE_URL, ln,
                        request_id,
                        recid,
                        borrower_id,
                        _("Associate barcode"))
 
             out += """
                     </tbody>
                     </table>
                     </form>
 
                     <div id="pager" class="pager">
                         <form>
                             <br />
                             <img src="/img/sb.gif" class="first" />
                             <img src="/img/sp.gif" class="prev" />
                             <input type="text" class="pagedisplay" />
                             <img src="/img/sn.gif" class="next" />
                             <img src="/img/se.gif" class="last" />
                             <select class="pagesize">
                                 <option value="10" selected="selected">10</option>
                                 <option value="20">20</option>
                                 <option value="30">30</option>
                                 <option value="40">40</option>
                             </select>
                         </form>
                     </div>
                     """
             out += """
                     <div class="back" style="position: relative; top: 5px;">
                         <br />
                         <table class="bibcirctable">
                             <tr>
                                 <td>
                                 <input type=button value='%s' onClick="history.go(-1)"
                                         class="formbutton"></td>
                             </tr>
                         </table>
                     <br />
                     <br />
                     </form>
                     </div>
                     </div>
                     """ % (_("Back"))
 
         return out
 
     def tmpl_get_next_waiting_loan_request(self, result, recid, barcode,
                                            ln=CFG_SITE_LANG):
         """
         Template for the admin interface. Show the next request in the queue.
 
         @param result: next request with status = 'waiting'
         @param barcode: book's barcode
         @param ln: language
         """
 
         _ = gettext_set_language(ln)
 
         out = load_menu(ln)
 
         if len(result) == 0:
             out += """
             <div class="bibcircbottom">
             <br />
             <br />
             <br />
             <br />
             <table class="bibcirctable_contents">
                  <td class="bibcirccontent" align="center">%s</td>
             </table>
             <br />
             <br />
             <br />
             <table class="bibcirctable_contents">
             <td align="center">
                 <input type=button
                     onClick="location.href='%s/admin2/bibcirculation/loan_on_desk_step1ln=%s'"
             value="%s" class='formbutton'>
             </td>
             </table>
             <br />
             </div>
             """ % (_("No hold requests waiting."),
                    CFG_SITE_URL, ln, _("Back to home"))
 
 
         else:
             out += """
             <form name="list_form"
                   action="%s/admin2/bibcirculation/get_next_waiting_loan_request"
                   method="get" >
             <div class="bibcircbottom">
             <br />
             <br />
              <table class="bibcirctable">
                     <tr>
                        <td class="bibcirctableheader">%s</td>
                        <td class="bibcirctableheader">%s</td>
                        <td class="bibcirctableheader" align="center">%s</td>
                        <td class="bibcirctableheader" align="center">%s</td>
                        <td class="bibcirctableheader" align="center">%s</td>
                        <td class="bibcirctableheader" align="center">%s</td>
                        <td class="bibcirctableheader" align="center">%s</td>
                        <td width="10"><input type=hidden name=barcode value='%s'></td>
                        <td width="10"><input type=hidden name=recid value='%s'></td>
                     </tr>
 
                     """% (CFG_SITE_URL,
                           _("Name"),
                           _("Item"),
                           _("Request status"),
                           _("From"),
                           _("To"),
                           _("Request date"),
                           _("Request options"),
                           barcode,
                           recid)
 
             for (id_lr, name, recid, status, date_from,
                  date_to, request_date) in result:
 
                 out += """
                 <tr onMouseOver="this.className='highlight'"
                     onmouseout="this.className='normal'">
                  <td class="bibcirccontent">%s</td>
                  <td class="bibcirccontent">%s</td>
                  <td class="bibcirccontent" align="center">%s</td>
                  <td class="bibcirccontent" align="center">%s</td>
                  <td class="bibcirccontent" align="center">%s</td>
                  <td class="bibcirccontent" align="center">%s</td>
                  <td class="bibcirccontent" align="center">
                  <input type=button onClick="location.href='%s/admin2/bibcirculation/get_next_waiting_loan_request?ln=%s&check_id=%s&recid=%s&barcode=%s'"
                  value='%s' class="formbutton">
                  <input type=button onClick="location.href='%s/admin2/bibcirculation/make_new_loan_from_request?ln=%s&check_id=%s&barcode=%s'"
                  value='%s' class="formbutton"></td>
                  </td>
                  </tr>
                  """ % (
                         name, book_title_from_MARC(recid),
                         status, date_from, date_to,
                         request_date, CFG_SITE_URL, ln,
                         id_lr, recid, barcode,
                         _("Cancel"), CFG_SITE_URL, ln,
                         id_lr, barcode,
                         _('Select hold request'))
 
             out += """</table>
                   <br />
                   <br />
                   <br />
                   <table class="bibcirctable">
                        <tr>
                             <td>
                                  <input type=button value='%s'
                                   onClick="history.go(-1)" class="formbutton">
                             </td>
                            </tr>
                   </table>
                   </form>
                   <br />
                   <br />
                   <br />
                   </div>
                   """ % (_("Back"))
 
 
         return out
 
     def tmpl_loan_return(self, infos, ln=CFG_SITE_LANG):
         """
         Template for the admin interface. Used when a book return.
 
         @param ln: language
         """
 
         out = self.tmpl_infobox(infos, ln)
 
         _ = gettext_set_language(ln)
 
         out += load_menu(ln)
 
         out += """
         <form name="return_form"
               action="%s/admin2/bibcirculation/loan_return_confirm?ln=%s" method="post">
         <div class="bibcircbottom">
         <br />
         <br />
         <br />
         <table class="bibcirctable_contents">
           <tr align="center">
             <td class="bibcirctableheader">
             %s
             <input type="text" size=45 id="barcode" name="barcode"
                    style='border: 1px solid #cfcfcf'>
             <script language="javascript" type="text/javascript">
                 document.getElementById("barcode").focus();
             </script>
             </td>
 
           </tr>
         </table>
 
         """ % (CFG_SITE_URL, ln,
                _("Barcode"))
 
         out += """
         <br />
         <table class="bibcirctable_contents">
           <tr align="center">
             <td>
               <input type="reset" name="reset_button" value='%s' class="formbutton">
               <input type="submit" name="ok_button" value='%s' class="formbutton">
             </td>
           </tr>
         </table>
         <br />
         <br />
         <br />
         </div>
         </form>
         """ % (_("Reset"),
                _("OK"))
 
         return out
 
     def tmpl_loan_return_confirm(self, infos, borrower_name, borrower_id, recid,
                                 barcode, return_date, result, ln=CFG_SITE_LANG):
         """
         @param borrower_name: person who returned the book
         @param id_bibrec: book's recid
         @param barcode: book's barcode
         @param ln: language
         """
 
         _ = gettext_set_language(ln)
 
         out = load_menu(ln)
 
         borrower_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_borrower_details',
                                 {'borrower_id': borrower_id, 'ln': ln},
                                 (borrower_name))
 
         title_link = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_item_details',
                                     {'recid': recid, 'ln': ln},
                                     (book_title_from_MARC(recid)))
 
         if len(result) == 0 and len(infos) == 0:
             out += """
             <script type="text/javascript" language='JavaScript' src="%(url)s/js/jquery/jquery.min.js">
             </script>
             <script type="text/javascript">
                 $(window).keydown(function(event){
                     window.location.href="%(url)s/admin2/bibcirculation/loan_return?ln=%(ln)s";
                 });
             </script>
             """ % {'url': CFG_SITE_URL, 'ln': ln}
 
         out += """
            <form name="return_form"
                  action="%s/admin2/bibcirculation/loan_return?ln=%s" method="get" >
              <div class="bibcircbottom">
              <br />
              <div class="infoboxsuccess">""" % (CFG_SITE_URL, ln)
 
         out += _("The item %(x_strong_tag_open)s%(x_title)s%(x_strong_tag_close)s, with barcode %(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s, has been returned with success.") % {'x_title': book_title_from_MARC(recid), 'x_barcode': barcode, 'x_strong_tag_open': '<strong>', 'x_strong_tag_close': '</strong>'}
         out += """</div>
                   <br />"""
 
         for info in infos:
-                out += """<div class="infobox">"""
-                out += info
-                out += """</div> <br /> """
+            out += """<div class="infobox">"""
+            out += info
+            out += """</div> <br /> """
 
         if len(result) > 0:
             out += """
              <br />
              <div class="infoboxmsg">%s</div>
              <br />
             """ % (_("There are %(x_strong_tag_open)s%(x_number_of_requests)s requests%(x_strong_tag_close)s on the book that has been returned." % {'x_number_of_requests': len(result), 'x_strong_tag_open': '<strong>', 'x_strong_tag_close': '</strong>'}))
 
         (_book_title, book_year, book_author,
                     book_isbn, book_editor) = book_information_from_MARC(recid)
 
         if book_isbn:
             book_cover = get_book_cover(book_isbn)
         else:
             book_cover = "%s/img/book_cover_placeholder.gif" % (CFG_SITE_URL)
 
         out += """
 
         <table class="bibcirctable">
             <tr valign='top'>
                 <td width="350">
                     <table class="bibcirctable">
                         <th class="bibcirctableheader" align='left'>%s</th>
                     </table>
                     <style type="text/css"> @import url("/img/tablesorter.css"); </style>
                     <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                         <tr>
                             <th width="80">%s</th>
                             <td class="bibcirccontent">%s</td>
                         </tr>
                         <tr>
                             <th width="80">%s</th>
                             <td class="bibcirccontent">%s</td>
                         </tr>
                         <tr>
                             <th width="80">%s</th>
                             <td class="bibcirccontent">%s</td>
                         </tr>
                         <tr>
                             <th width="80">%s</th>
                             <td class="bibcirccontent">%s</td>
                         </tr>
                         <tr>
                             <th width="80">%s</th>
                             <td class="bibcirccontent">%s</td>
                         </tr>
                         <tr>
                             <th width="80">%s</th>
                             <td class="bibcirccontent">%s</td>
                         </tr>
                         <tr>
                             <th width="80">%s</th>
                             <td class="bibcirccontent">%s</td>
                         </tr>
                     </table>
                 </td>
                 <td class="bibcirccontent">
                     <img style='border: 1px solid #cfcfcf' src="%s" alt="Book Cover"/>
                 </td>
             </tr>
 
             <input type=hidden name=recid value='%s'>
             <input type=hidden name=barcode value='%s'>
         </table>
 
         """ % (_("Loan informations"),
                _("Borrower"), borrower_link,
                _("Item"), title_link,
                _("Author"), book_author,
                _("Year"), book_year,
                _("Publisher"), book_editor,
                _("ISBN"), book_isbn,
                _("Return date"), return_date,
                str(book_cover),
                recid,
                barcode)
 
 
         if result:
             out += """
             <style type="text/css"> @import url("/img/tablesorter.css"); </style>
             <script src="/js/jquery/jquery.js" type="text/javascript"></script>
             <script src="/js/jquery/jquery.tablesorter.js" type="text/javascript"></script>
             <script type="text/javascript">
             $(document).ready(function() {
               $('#table_requests').tablesorter({widthFixed: true, widgets: ['zebra']})
             });
             </script>
             <table class="bibcirctable">
               <tr>
                 <td class="bibcirctableheader">%s</td>
               </tr>
             </table>
             <table id="table_requests" class="tablesorter" border="0"
                                        cellpadding="0" cellspacing="1">
             <thead>
               <tr>
                 <th>%s</th>
                 <th>%s</th>
                 <th>%s</th>
                 <th>%s</th>
                 <th>%s</th>
                 <th>%s</th>
                 <th>%s</th>
               </tr>
             </thead>
             </tbody>
 
             """% (_("Waiting requests"),
                   _("Name"),
                   _("Item"),
                   _("Request status"),
                   _("From"),
                   _("To"),
                   _("Request date"),
                   _("Request options"))
 
             for (request_id, name, recid, status, date_from,
                  date_to, request_date) in result:
 
                # out += """
                #<script type="text/javascript">
                #function confirmation() {
                #  var answer = confirm("Delete this request?")
                #  if (answer){
                #    window.location = "%s/admin2/bibcirculation/get_next_waiting_loan_request?check_id=%s&recid=%s&barcode=%s";
                #    }
                #  }
                #</script>
                #
                #""" % (CFG_SITE_URL, request_id, recid, barcode)
 
                 out += """
                 <tr>
                   <td>%s</td>
                   <td>%s</td>
                   <td>%s</td>
                   <td>%s</td>
                   <td>%s</td>
                   <td>%s</td>
                   <td>
 
                  <input type=button onClick="location.href='%s/admin2/bibcirculation/make_new_loan_from_request?ln=%s&check_id=%s&barcode=%s'"
                  value='%s' class="bibcircbutton" style="background: url(/img/dialog-yes.png) no-repeat; width: 125px; text-align: right;"></td>
                  </td>
                  </tr>
                  """ % (
                         name, book_title_from_MARC(recid),
                         status, date_from, date_to,
                         request_date, CFG_SITE_URL, ln, request_id, barcode,
                         _('Select request'))
 
             out += """
             </table>
             """
 
         #else:
         #    out += """
         #      <div class="infoboxmsg">%s</div>""" % (_("There are no requests waiting on the item <strong>%s</strong>." % book_title_from_MARC(recid)))
 
             out += """
              </table>
             <br />
             <br />
             <br />
             </div>
             </form>
             """
 
         return out
 
     def tmpl_index(self, ln=CFG_SITE_LANG):
         """
         Main page of the Admin interface.
 
         @param pending_request: display the number of pending requests
         @param ln: language
         """
 
         _ = gettext_set_language(ln)
 
         out = load_menu(ln)
 
         out += """
         <div class="bibcircbottom">
         <br />
         <div class="bibcircsubtitle">
         %s
         </div>
         <br />
         """ % (_("Welcome to Invenio BibCirculation Admin"))
 
         out += """
         <br /><br />
         <br /><br />
         <br /><br />
         <br /><br />
         <br /><br />
         </div>
         """
 
         return out
 
     def tmpl_borrower_search(self, infos, redirect_to_new_request=False,
                              ln=CFG_SITE_LANG):
         """
         Template for the admin interface. Search borrower.
 
         @param ln: language
         """
         _ = gettext_set_language(ln)
 
 
         if CFG_CERN_SITE == 1:
             id_string = 'ccid'
         else:
             id_string = _('id')
 
         out = self.tmpl_infobox(infos, ln)
 
         out += load_menu(ln)
 
         if redirect_to_new_request:
             redirect_to_new_request = 'yes'
         else:
             redirect_to_new_request = 'no'
 
         new_borrower_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/add_new_borrower_step1',
                                 {'ln': ln}, _("register new borrower"))
 
         out += """
         <div class="bibcircbottom">
         <br />
         <br />
         <br />
         <form name="borrower_search"
               action="%s/admin2/bibcirculation/borrower_search_result"
               method="get" >
              <table class="bibcirctable">
                <tr align="center">
                  <td class="bibcirctableheader">%s
                    <input type="radio" name="column" value="id">%s
                    <input type="radio" name="column" value="name" checked>%s
                    <input type="radio" name="column" value="email">%s
                    <input type="hidden" name="redirect_to_new_request" value="%s">
                    <br>
                    <br>
                  </td>
                </tr>
                <tr align="center">
                  <td>
                     <input type="text" size="45" name="string" id="string"
                            style='border: 1px solid #cfcfcf'>
                     <script language="javascript" type="text/javascript">
                             document.getElementById("string").focus();
                     </script>
                  </td>
                </tr>
         """ % (CFG_SITE_URL,
                _("Search borrower by"), id_string,
                _("name"), _("email"),
                redirect_to_new_request)
 
         if not CFG_CERN_SITE:
             out += """
                 <tr align="center">
                     <td class="bibcirctableheader">%s</td>
                 </tr>
             """ % (new_borrower_link)
 
         out += """
          </table>
         <br />
         <table class="bibcirctable">
              <tr align="center">
                <td>
                  <input type=button value='%s'
                         onClick="history.go(-1)" class="formbutton">
                  <input type="submit" value='%s' class="formbutton">
                </td>
              </tr>
         </table>
         <form>
         <br />
         <br />
         <br />
         <br />
         </div>
         """ % (_("Back"), _("Search"))
 
 
         return out
 
     def tmpl_item_search(self, infos, ln=CFG_SITE_LANG):
         """
         @param ln: language of the page
         """
         _ = gettext_set_language(ln)
 
         out = self.tmpl_infobox(infos, ln)
 
         out += load_menu(ln)
 
         out += """
         <div class="bibcircbottom">
         <form name="search_form"
               action="%s/admin2/bibcirculation/item_search_result"
               method="get" >
         <br />
         <br />
         <br />
         <input type=hidden value="0">
         <input type=hidden value="10">
         """ % (CFG_SITE_URL)
 
         out += """
         <table class="bibcirctable">
           <tr align="center">
             <td class="bibcirctableheader">%s
               <input type="radio" name="f" value="">%s
               <input type="radio" name="f" value="barcode" checked>%s
               <input type="radio" name="f" value="recid">%s
         <!---
               <input type="radio" name="f" value="author">%s
               <input type="radio" name="f" value="title">%s
         --->
               <br />
               <br />
             </td>
           </tr>
           """ % (_("Search item by"), _("any field"), _("barcode"), _("recid"), _("author"),
                  _("title"))
 
         out += """
           <tr align="center">
             <td>
                 <input type="text" size="50" name="p" id="p" style='border: 1px solid #cfcfcf'>
                 <script language="javascript" type="text/javascript">
                     document.getElementById("p").focus();
                 </script>
             </td>
           </tr>
             """
 
         out += """
             </td>
           </tr>
         </table>
         <br />
         <table class="bibcirctable">
           <tr align="center">
             <td>
               <input type=button   value='%s' class="formbutton" onClick="history.go(-1)">
               <input type="submit" value='%s' class="formbutton">
             </td>
           </tr>
         </table>
         <br />
         <br />
         <br />
         <br />
         </div>
         <form>
         """ % (_("Back"), _("Search"))
 
         return out
 
     def tmpl_item_search_result(self, result, ln=CFG_SITE_LANG):
         """
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         out = load_menu(ln)
 
         try:
             number_of_results = len(result)
         except:
             number_of_results = 1
 
         if result == None:
             out += """
             <div class="bibcircbottom">
             <br />
             <div class="bibcircinfoboxmsg">%s</div>
             <br />
             """ % (_("0 item(s) found."))
 ### por aqui voy ###
         else:
             out += """
         <style type="text/css"> @import url("/img/tablesorter.css"); </style>
         <div class="bibcircbottom">
         <br />
         <table class="bibcirctable">
           <tr align="center">
             <td>
                <strong>%s</strong>
             </td>
           </tr>
         </table>
         <br />
           <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
             <thead>
               <tr>
                 <th>%s</th>
                 <th>%s</th>
                 <th>%s</th>
                 <th>%s</th>
               </tr>
             </thead>
           <tbody>
         """ % (_("%i items found.") % number_of_results, _("Title"),
                _("Author"), _("Publisher"),
                _("# copies"))
 
 ### FIXME: If one result -> go ahead ###
             for recid in result:
 
                 (book_author, book_editor,
                  book_copies) = get_item_info_for_search_result(recid)
 
                 title_link = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_item_details',
                                     {'recid': recid, 'ln': ln},
                                     (book_title_from_MARC(recid)))
 
                 out += """
                 <tr>
                     <td>%s</td>
                     <td>%s</td>
                     <td>%s</td>
                     <td>%s</td>
                 </tr>
                 """ % (title_link, book_author,
                        book_editor, book_copies)
 
         out += """
           </tbody>
           </table>
         <br />
         <table class="bibcirctable">
           <tr align="center">
             <td>
               <input type=button value='%s'
                onClick="history.go(-1)" class="formbutton">
             </td>
           </tr>
         </table>
         <br />
         <br />
         <br />
         </div>
 
         """ % (_("Back"))
 
         return out
 
     def tmpl_loan_on_desk_step1(self, result, key, string, infos,
                                 ln=CFG_SITE_LANG):
         """
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         out = self.tmpl_infobox(infos, ln)
         out += load_menu(ln)
 
         out += """
         <div class="bibcircbottom">
         <form name="step1_form1" action="%s/admin2/bibcirculation/loan_on_desk_step1"
               method="get" >
         <br />
         <br />
         <br />
           <table class="bibcirctable" align="center">
             """ % (CFG_SITE_URL)
 
         if CFG_CERN_SITE == 1:
 
             out += """
                 <tr>
                    <td class="bibcirctableheader" align="center">%s
                    """ % (_("Search user by"))
 
             if key == 'email':
                 out += """
                    <input type="radio" name="key" value="ccid">%s
                    <input type="radio" name="key" value="name">%s
                    <input type="radio" name="key" value="email" checked>%s
                    """ % ('ccid', _('name'), _('email'))
 
             elif key == 'name':
                 out += """
                    <input type="radio" name="key" value="ccid">%s
                    <input type="radio" name="key" value="name" checked>%s
                    <input type="radio" name="key" value="email">%s
                    """ % ('ccid', _('name'), _('email'))
 
             else:
                 out += """
                    <input type="radio" name="key" value="ccid" checked>%s
                    <input type="radio" name="key" value="name">%s
                    <input type="radio" name="key" value="email">%s
                    """ % ('ccid', _('name'), _('email'))
 
         else:
             out += """
                  <tr>
                    <td align="center" class="bibcirctableheader">%s
                    """ % (_("Search borrower by"))
 
             if key == 'email':
                 out += """
                    <input type="radio" name="key" value="id">%s
                    <input type="radio" name="key" value="name">%s
                    <input type="radio" name="key" value="email" checked>%s
                    """ % (_('id'), _('name'), _('email'))
 
             elif key == 'id':
                 out += """
                    <input type="radio" name="key" value="id" checked>%s
                    <input type="radio" name="key" value="name">%s
                    <input type="radio" name="key" value="email">%s
                    """ % (_('id'), _('name'), _('email'))
 
             else:
                 out += """
                    <input type="radio" name="key" value="id">%s
                    <input type="radio" name="key" value="name" checked>%s
                    <input type="radio" name="key" value="email">%s
                    """ % (_('id'), _('name'), _('email'))
 
         out += """
                     <br><br>
                     </td>
                     </tr>
                     <tr>
                         <td align="center">
                             <input type="text" size="40" id="string" name="string"
                                    value='%s' style='border: 1px solid #cfcfcf'>
                             <script language="javascript" type="text/javascript">
                                 document.getElementById("string").focus();
                             </script>
                         </td>
                     </tr>
                     <tr>
                         <td align="center">
                             <br>
                             <input type="submit" value="%s" class="formbutton">
                         </td>
                     </tr>
 
                    </table>
           </form>
         """ % (string or '', _("Search"))
 
         if result:
             out += """
             <br />
             <form name="step1_form2"
                   action="/admin2/bibcirculation/loan_on_desk_step2"
                   method="get">
             <table class="bibcirctable">
               <tr width="200">
                 <td align="center">
                   <select name="user_id" size="8" style='border: 1px solid #cfcfcf; width:200'>
 
               """
             for user_info in result:
                 name = user_info[0]
                 user_id = user_info[2]
                 out += """
                        <option value='%s'>%s
                        """ % (name, user_id)
 
             out += """
                     </select>
                   </td>
                 </tr>
               </table>
               <table class="bibcirctable">
                 <tr>
                   <td align="center">
                     <input type="submit" value='%s' class="formbutton">
                   </td>
                 </tr>
               </table>
             </form>
             """ % (_("Select user"))
 
         out += """
               <br />
               <br />
               <br />
               </div>
               """
 
         return out
 
     def tmpl_loan_on_desk_step2(self, user_id, infos, ln=CFG_SITE_LANG):
         """
         @param ln: language of the page
         """
 
         user_info = db.get_borrower_details(user_id)
         (borrower_id, ccid, name, email, phone, address, mailbox) = user_info
 
         _ = gettext_set_language(ln)
 
         display_id = borrower_id
         id_string = _("ID")
         if CFG_CERN_SITE == 1:
             display_id = ccid
             id_string = _("CCID")
 
         out = self.tmpl_infobox(infos, ln)
 
         out += load_menu(ln)
 
         out += """
             <div class="bibcircbottom">
             <style type="text/css"> @import url("/img/tablesorter.css"); </style>
             <form name="step2_form" action="%s/admin2/bibcirculation/loan_on_desk_step3"
                   method="get" >
               <br />
               <br />
               <table class="bibcirctable">
                           <tr>
                                <td class="bibcirctableheader">%s</td>
                           </tr>
                 """ % (CFG_SITE_URL, _("User information"))
 
         out += """
               </table>
               <table class="tablesortersmall" border="0" cellpadding="0" cellspacing="1">
                 <tr>
                   <th width="70">%s</th>
                   <td>%s</td>
                 </tr> """ % (id_string, display_id)
 
         out += """
                 <tr>
                   <th width="70">%s</th>
                   <td>%s</td>
                 </tr>
                 <tr>
                   <th width="70">%s</th>
                   <td>%s</td>
                   </tr>
                 <tr>
                   <th width="70">%s</th>
                   <td>%s</td>
                 </tr>
                 <tr>
                   <th width="70">%s</th>
                   <td>%s</td>
                 </tr>
                 <tr>
                   <th width="70">%s</th>
                   <td>%s</td>
                 </tr>
                 </table>
                 <br />
                 <table class="bibcirctable">
                   <tr>
                     <td class="bibcirctableheader" width="77">%s</td>
                   </tr>
                   <tr>
                     <td>
                         <textarea rows="5" cols="43" name="barcode" id="barcode"
                                   style='border: 1px solid #cfcfcf'></textarea>
                         <script language="javascript" type="text/javascript">
                             document.getElementById("barcode").focus();
                         </script>
                     </td>
                   </tr>
                 </table>
                 <br />
                 <table class="bibcirctable">
                 <tr>
                   <td>
                        <input type=button value="%s"
                         onClick="history.go(-1)" class="formbutton">
 
                        <input type="submit"
                        value="%s" class="formbutton">
 
                       <input type=hidden name="user_id" value="%s">
 
                   </td>
                  </tr>
                 </table>
                 </form>
                 <br />
                 <br />
                 </div>
                 """ % (_("Name"), name,
                        _("Address"), address,
                        _("Mailbox"), mailbox,
                        _("Email"), email,
                        _("Phone"), phone,
                        _("Barcode(s)"), _("Back"),
                        _("Continue"), user_id)
 
         return out
 
     def tmpl_loan_on_desk_step3(self, user_id, list_of_books, infos,
                                 ln=CFG_SITE_LANG):
         """
         @param ln: language of the page
         """
 
         user_info = db.get_borrower_details(user_id)
         (borrower_id, ccid, name, email, phone, address, mailbox) = user_info
 
         list_of_barcodes = []
 
         for book in list_of_books:
             list_of_barcodes.append(book[1])
 
         _ = gettext_set_language(ln)
 
         display_id = borrower_id
         id_string = _("ID")
         if CFG_CERN_SITE == 1:
             display_id = ccid
             id_string = _("CCID")
 
         out = self.tmpl_infobox(infos, ln)
 
         out += load_menu(ln)
 
         out += """
             <div class="bibcircbottom">
             <style type="text/css"> @import url("/img/tablesorter.css"); </style>
             <script type="text/javascript" language='JavaScript'>
             function groupDatePicker(){
                 var index = 0;
                 var datepicker = null;
                 var datepickerhidden = this.document.getElementById("datepickerhidden")
                     do{
                 datepicker = this.document.getElementById("date_picker"+index)
                 if(datepicker != null){
                     if (index != 0){
                         datepickerhidden.value += ",";
                     }
                     datepickerhidden.value += datepicker.value ;
                 }
                 index = index + 1;
             }while(datepicker != null);
             }
             </script>
             <form name="step3_form" action="%s/admin2/bibcirculation/loan_on_desk_step4"
                   method="post" >
               <br />
               <br />
               <input type=hidden name="list_of_barcodes" value="%s">
               <input type=hidden name="datepickerhidden" id="datepickerhidden"  value="">
               <table class="bibcirctable">
                           <tr>
                                <td class="bibcirctableheader">%s</td>
                           </tr>
               </table>
               <table class="tablesortersmall" border="0" cellpadding="0" cellspacing="1">
                 <tr>
                   <th width="70">%s</th>
                   <td>%s</td>
                 </tr>
                 <tr>
                   <th width="70">%s</th>
                   <td>%s</td>
                 </tr>
                 <tr>
                   <th width="70">%s</th>
                   <td>%s</td>
                 </tr>
                 <tr>
                   <th width="70">%s</th>
                   <td>%s</td>
                 </tr>
                 <tr>
                   <th width="70">%s</th>
                   <td>%s</td>
                 </tr>
                 <tr>
                   <th width="70">%s</th>
                   <td>%s</td>
                 </tr>
                 </table>
                 <br />
                 <table class="bibcirctable">
                           <tr>
                                <td class="bibcirctableheader">%s</td>
                           </tr>
                 </table>
 
                 <script type="text/javascript" language='JavaScript' src="%s/js/jquery/jquery.ui.datepicker.min.js"></script>
 
                 <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                 <thead>
                  <tr>
                     <th>%s</th>
                     <th width="65">%s</th>
                     <th width="100">%s</th>
                     <th width="80">%s</th>
                     <th width="130">%s</th>
                     <th>%s</th>
                  </tr>
                 </thead>
                 <tbody>
                 """ % (CFG_SITE_URL, str(list_of_barcodes),
                        _("User information"),
                          id_string, display_id,
                         _("Name"), name,
                         _("Address"), address,
                         _("Mailbox"), mailbox,
                         _("Email"), email,
                         _("Phone"), phone,
                         _("List of borrowed books"),
                         CFG_SITE_URL,
                         _("Item"), _("Barcode"),
                         _("Library"), _("Location"),
                         _("Due date"), _("Write note(s)"))
 
 
         iterator = 0
 
         for (recid, barcode, library_id, location) in list_of_books:
 
             due_date = renew_loan_for_X_days(barcode)
 
             library_name = db.get_library_name(library_id)
 
             out += """
                  <tr>
                     <td>%s</td>
                     <td width="65">%s</td>
                     <td width="100">%s</td>
                     <td width="80">%s</td>
                     <td width="130" class="bibcirccontent">
                     <script type="text/javascript">
                         $(function() {
                             $("%s").datepicker({dateFormat: 'yy-mm-dd', showOn: 'button', buttonImage: "%s/img/jquery/calendar.gif", buttonImageOnly: true});
                         });
                     </script>
                     <input type="text" size="12" id="%s" name="%s"
                            value="%s" style='border: 1px solid #cfcfcf'>
 
                     </td>
                   <td>
                     <textarea name='note' rows="1" cols="40"
                               style='border: 1px solid #cfcfcf'></textarea>
                   </td>
                 </tr>
                 """ % (book_title_from_MARC(recid), barcode,
                        library_name, location, "#date_picker"+str(iterator),
                        CFG_SITE_URL, "date_picker"+str(iterator),
                        'due_date'+str(iterator), due_date)
 
             iterator += 1
 
         out += """
                 </tbody>
                 </table>
                 <br />
                 <table class="bibcirctable">
                 <tr>
                   <td>
                        <input type=button value="%s"
                        onClick="history.go(-1)" class="formbutton">
 
                        <input type="submit"
                        value="%s" class="formbutton" onmousedown="groupDatePicker();">
 
                        <input type=hidden name="user_id" value="%s">
                   </td>
                  </tr>
                 </table>
                 </form>
                 <br />
                 <br />
                 </div>
                 """ % (_("Back"), _("Continue"), user_id)
 
         return out
 
     def tmpl_loan_on_desk_step4(self, ln=CFG_SITE_LANG):
         """
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         out = """
         """
         out += load_menu(ln)
 
         out += """<div class="bibcircbottom">
                  <br />
                  <br />
                  <br />
                  <br />
                  A new loan has been registered.
                  <br />
                  <br />
                  <br />
                  <br />
                  <table class="bibcirctable_contents">
                  <td align="center">
                  <input type=button onClick="location.href='%s'" value="%s" class='formbutton'>
                  </td>
                  </table>
                  <br />
                  </div>
                  """ % (CFG_SITE_URL, _("Back to home"))
 
         return out
 
     def tmpl_send_notification(self, ln=CFG_SITE_LANG):
         """
         @param ln: language of the page
         """
         _ = gettext_set_language(ln)
 
         out = """
               """
         out += load_menu(ln)
 
         out += """
         <div class="bibcircbottom">
         <br />
         <br />
             <table class="bibcirctable">
                 <td class="bibcirccontent" width="30">%s</td>
             </table>
             <br /> <br />
             <table class="bibcirctable">
             <td>
              <input
                 type=button
                 onClick="location.href='%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s'"
                 value='%s'
                 class='formbutton'>
             </td>
             </table>
         <br />
         <br />
         </div>
         """ % (_("Notification has been sent!"),
                CFG_SITE_URL, ln, _("Back to home"))
 
         return out
 
     def tmpl_register_new_loan(self, borrower_info, infos,
                                recid, ln=CFG_SITE_LANG):
         """
         @param ln: language of the page
         """
 
         (borrower_id, ccid, name,
          email, phone, address, mailbox) = borrower_info
         (book_title, book_year, book_author,
          book_isbn, book_editor) = book_information_from_MARC(recid)
 
         _ = gettext_set_language(ln)
 
         display_id = borrower_id
         id_string = _("ID")
         if CFG_CERN_SITE == 1:
             display_id = ccid
             id_string = _("CCID")
 
         out = load_menu(ln)
         out += "<br />"
         out += self.tmpl_infobox(infos, ln)
 
         out += """
         <style type="text/css"> @import url("/img/tablesorter.css"); </style>
         <div class="bibcircbottom">
         <table class="tablesorterborrower" border="0" cellpadding="0" cellspacing="1">
             <tr>
                 <th width="100">%s</th>
                 <td>%s</td>
             </tr>
             <tr>
                 <th width="100">%s</th>
                 <td>%s</td>
             </tr>
             <tr>
                 <th width="100">%s</th>
                 <td>%s</td>
             </tr>
             <tr>
                 <th width="100">%s</th>
                 <td>%s</td>
             </tr>
             <tr>
                 <th width="100">%s</th>
                 <td>%s</td>
             </tr>
         </table>
         <br />
         <table class="tablesorterborrower" border="0" cellpadding="0" cellspacing="1">
             <tr>
                 <th width="100">%s</th>
                 <td>%s</td>
             </tr>
             <tr>
                 <th width="100">%s</th>
                 <td>%s</td>
             </tr>
             <tr>
                 <th width="100">%s</th>
                 <td>%s</td>
             </tr>
             <tr>
                 <th width="100">%s</th>
                 <td>%s</td>
             </tr>
             <tr>
                 <th width="100">%s</th>
                 <td>%s</td>
             </tr>
             <tr>
                 <th width="100">%s</th>
                 <td>%s</td>
             </tr>
         </table>
         <br />
         <table class="bibcirctable">
             <td>
                 <input type="button"
                        value="%s" class="formbutton"
                     onClick="location.href='%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s'"
                 >
                 <input type="button"
                        value="%s" class="formbutton"
     onClick="location.href='%s/admin2/bibcirculation/register_new_loan?ln=%s&print_data=true'"
                 >
             </td>
         </table>
         <br />
         <br />
         </div>
         """ % (id_string, display_id,
                _("Name"), name,
                _("Address"), address,
                _("Mailbox"), mailbox,
                _("Email"), email,
                _("Phone"), phone,
                _("Title"), book_title,
                _("Author(s)"), book_author,
                _("Year"), book_year,
                _("Publisher"), book_editor,
                _("ISBN"), book_isbn,
                _("Back to home"),
                CFG_SITE_URL, ln,
                _("Print loan information"),
                CFG_SITE_URL, ln)
 
         return out
 
     def tmpl_loan_on_desk_confirm(self, barcode,
                                   borrower, infos, ln=CFG_SITE_LANG):
         """
         @param ln: language of the page0
         """
 
         _ = gettext_set_language(ln)
 
         out = self.tmpl_infobox(infos, ln)
 
         out += load_menu(ln)
 
         borrower_email = borrower.split(' [')[0]
         borrower_id = borrower.split(' [')[1]
         borrower_id = int(borrower_id[:-1])
 
         out += """
         <form name="return_form"
               action="%s/admin2/bibcirculation/register_new_loan"
               method="post" >
             <div class="bibcircbottom">
                 <input type=hidden name=borrower_id value="%s">
                 <br />
                     <table class="bibcirctable">
                         <tr>
                             <td class="bibcirctableheader" width="70">%s</td>
                             <td class="bibcirccontent" width="600">%s</td>
                         </tr>
         """ % (CFG_SITE_URL,
                borrower_id,
                _("Borrower"),
                borrower_email)
 
         for (bar) in barcode:
             recid = db.get_id_bibrec(bar)
 
             out += """
                         <tr>
                             <td class="bibcirctableheader" width="70">%s</td>
                             <td class="bibcirccontent" width="600">%s</td>
                         </tr>
                 <input type=hidden name=barcode value='%s'>
             """ % (_("Item"),
                    book_title_from_MARC(recid),
                    bar)
 
 
         out += """
         </table>
         <br />
         <table class="bibcirctable_contents">
              <tr>
                   <td>
                        <input type=button value='%s' onClick="history.go(-1)" class="formbutton">
                        <input type="submit"   value="%s" class="formbutton">
                   </td>
              </tr>
         </table>
         <br />
         </div>
         </form>
         """ % (_("Back"),
                _("Confirm"))
 
 
         return out
 
     def tmpl_all_requests(self, result, ln=CFG_SITE_LANG):
         """
         @param ln: language of the page
         """
         _ = gettext_set_language(ln)
 
         out = """
         """
         out += load_menu(ln)
 
         out += """
         <form name="all_requests_form"
               action="%s/admin2/bibcirculation/all_requests"
               method="get" >
             <div class="bibcircbottom">
                 <br />
                 <table class="bibcirctable">
                     <tr>
                         <td class="bibcirctableheader">%s</td>
                         <td class="bibcirctableheader">%s</td>
                         <td class="bibcirctableheader" align="center">%s</td>
                         <td class="bibcirctableheader" align="center">%s</td>
                         <td class="bibcirctableheader" align="center">%s</td>
                         <td class="bibcirctableheader" align="center">%s</td>
                         <td class="bibcirctableheader" align="center">%s</td>
                     </tr>
         """ % (CFG_SITE_URL,
                _("Borrower"),
                _("Item"),
                _("Status"),
                _("From"),
                _("To"),
                _("Request date"),
                _("Option(s)"))
 
         for (id_lr, borid, name, recid, status, date_from,
              date_to, request_date) in result:
 
             borrower_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_borrower_details',
                                 {'borrower_id': borid, 'ln': ln},(name))
 
             title_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_item_details',
                                 {'recid': recid, 'ln': ln},
                                 (book_title_from_MARC(recid)))
 
             out += """
             <tr onMouseOver="this.className='highlight'" onmouseout="this.className='normal'">
                  <td class="bibcirccontent">%s</td>
                  <td class="bibcirccontent">%s</td>
                  <td class="bibcirccontent" align="center">%s</td>
                  <td class="bibcirccontent" align="center">%s</td>
                  <td class="bibcirccontent" align="center">%s</td>
                  <td class="bibcirccontent" align="center">%s</td>
                  <td class="bibcirccontent" align="center">
                    <input type=button
                     onClick="location.href='%s/admin2/bibcirculation/all_requests?ln=%s&request_id=%s'"
                     value='%s' class="formbutton">
                  </td>
             </tr>
             """ % (borrower_link,
                    title_link,
                    status,
                    date_from,
                    date_to,
                    request_date,
                    CFG_SITE_URL, ln,
                    id_lr,
                    _("Cancel hold request"))
 
         out += """
         </table>
         <br />
         <table class="bibcirctable">
              <tr>
                   <td>
                      <input type=button value="%s" onClick="history.go(-1)" class="formbutton">
                   </td>
              </tr>
         </table>
         <br />
         <br />
         </div>
         </form>
         """ % (_("Back"))
 
         return out
 
     def tmpl_get_item_requests_details(self, recid, result, ln=CFG_SITE_LANG):
         """
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         out = load_menu(ln)
 
         if len(result) == 0:
             out += """
             <div class="bibcircbottom">
             <br />
             <div class="bibcircinfoboxmsg">%s</div>
             <br />
             """ % (_("There are no requests."))
 
         else:
             out += """
             <style type="text/css"> @import url("/img/tablesorter.css"); </style>
             <script src="/js/jquery/jquery.js" type="text/javascript"></script>
             <script src="/js/jquery/jquery.tablesorter.js" type="text/javascript"></script>
             <script type="text/javascript">
             $(document).ready(function() {
               $('#table_requests').tablesorter({widthFixed: true, widgets: ['zebra']})
             });
             </script>
         <form name="all_loans_form"
               action="%s/admin2/bibcirculation/update_loan_request_status" method="get" >
             <div class="bibcircbottom">
             <br />
             <table id="table_requests" class="tablesorter"
                    border="0" cellpadding="0" cellspacing="1">
                 <thead>
                     <tr>
                         <th>%s</th>
                         <th>%s</th>
                         <th>%s</th>
                         <th>%s</th>
                         <th>%s</th>
                         <th>%s</th>
                         <th>%s</th>
                         <th>%s</th>
                     </tr>
                 </thead>
                 <tbody>
                   """% (CFG_SITE_URL,
                         _("Borrower"),
                         _("Status"),
                         _("Library"),
                         _("Location"),
                         _("From"),
                         _("To"),
                         _("Request date"),
                         _("Option(s)"))
 
 
             for (borrower_id, name, id_bibrec, status, library,
                  location, date_from, date_to, request_id,
                  request_date) in result:
 
                 borrower_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_borrower_details',
                                 {'borrower_id': borrower_id, 'ln': ln}, (name))
 
                 out += """
             <tr>
                 <td>%s</td>
                 <td>%s</td>
                 <td>%s</td>
                 <td>%s</td>
                 <td>%s</td>
                 <td>%s</td>
                 <td>%s</td>
                 <td align="center">
                    <input type=button
 onClick="location.href='%s/admin2/bibcirculation/get_item_requests_details?recid=%s&request_id=%s'" value='%s' class='formbutton'>
                 </td>
             </tr>
             """ % (borrower_link, status, library, location,
                    date_from, date_to, request_date, CFG_SITE_URL,
                    id_bibrec, request_id, _("Cancel hold request"))
 
         out += """
         </tbody>
         </table>
         <br />
         <table class="bibcirctable">
             <tr>
                 <td>
                     <input type=button
                     onClick="location.href='%s/admin2/bibcirculation/get_item_details?ln=%s&recid=%s'"
                     value='%s' class='formbutton'>
                 </td>
             </tr>
         </table>
         <br />
         <br />
         <br />
        </div>
         </form>
         """ % (CFG_SITE_URL, ln,
                recid,
                _("Back"))
 
         return out
 
     def tmpl_get_item_details(self, recid, copies, requests, loans,
                               req_hist_overview, loans_hist_overview, infos,
                               ln=CFG_SITE_LANG):
         """
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         record_is_periodical = is_periodical(recid)
 
         out = self.tmpl_infobox(infos, ln)
 
         out += load_menu(ln)
 
         (book_title, book_year, book_author,
                      book_isbn, book_editor) = book_information_from_MARC(recid)
 
         if book_isbn:
             try:
                 book_cover = get_book_cover(book_isbn)
             except KeyError:
                 book_cover = """%s/img/book_cover_placeholder.gif
                             """ % (CFG_SITE_URL)
         else:
             book_cover = "%s/img/book_cover_placeholder.gif" % (CFG_SITE_URL)
 
         link_to_detailed_record = "<a href='%s/%s/%s' target='_blank'>%s</a>" % (CFG_SITE_URL, CFG_SITE_RECORD, recid, book_title)
 
         out += """
            <div class="bibcircbottom">
                 <br />
                 <table class="bibcirctable">
                   <tr>
                      <td class="bibcirctableheader">%s</td>
                   </tr>
                 </table>
 
                 <table class="bibcirctable">
                  <tr valign='top'>
                     <td width="400">
                     <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      </table>
                       <input type=button onClick="window.open('%s/%s/%s/edit')"
                       value='%s' class="formbutton">
                      </td>
                      <td>
                      <img style='border: 1px solid #cfcfcf' src="%s" alt="%s"/>
                      </td>
                      </tr>
               </table>
            <br />
            <table class="bibcirctable">
                 <tr>
                      <td class="bibcirctableheader">%s</td>
                 </tr>
            </table>
            """ % (_("Item details"),
                    _("Name"), link_to_detailed_record,
                    _("Author(s)"), book_author,
                    _("Year"), book_year,
                    _("Publisher"), book_editor,
                    _("ISBN"), book_isbn,
                    CFG_SITE_URL, CFG_SITE_RECORD, recid,
                    _("Edit this record"),
                    str(book_cover), _("Book Cover"),
                    _("Additional details"))
 
         out += """
             <style type="text/css">
                 @import url("/img/tablesorter.css");
             </style>
             <script src="/js/jquery/jquery.min.js" type="text/javascript"></script>
             <script src="/js/jquery/jquery.tablesorter.js" type="text/javascript"></script>
-
             <style type="text/css">
                 @import url("/js/jquery/tablesorter/themes/blue/style.css");
             </style>
             <style type="text/css">
                 @import url("/js/jquery/tablesorter/addons/pager/jquery.tablesorter.pager.css");
             </style>
 
             <script src="/js/jquery/jquery.min.js" type="text/javascript"></script>
             <script src="/js/jquery/tablesorter/jquery.tablesorter.js" type="text/javascript"></script>
             <script src="/js/jquery/tablesorter/addons/pager/jquery.tablesorter.pager.js"
                     type="text/javascript"></script>
             """
 
         if record_is_periodical:
             out += """
             <script type="text/javascript">
                 $(document).ready(function(){
                     $("#table_copies")
                       .tablesorter({sortList: [[7,1],[4,0]],widthFixed: true,widgets: ['zebra']})
                       .bind("sortStart",function(){$("#overlay").show();})
                       .bind("sortEnd",function(){$("#overlay").hide()})
                       .tablesorterPager({container: $("#pager"),
                                          positionFixed: false,
                                          size: 40
                                         });
                 });
             </script>
             """
         else:
             out += """
             <script type="text/javascript">
                 $(document).ready(function(){
                     $('#table_copies').tablesorter({sortList: [[1,1],[4,0]],
                                                     widthFixed: true,
                                                     widgets: ['zebra']})
                 });
             </script>
             """
 
         out += """
                   <table class="tablesorter" id="table_copies" border="0"
                          cellpadding="0" cellspacing="1">
                   <thead>
                     <tr>
                       <th>%s</th>
                       <th>%s</th>
                       <th>%s</th>
                       <th>%s</th>
                       <th>%s</th>
                """ % (_("Barcode"),
                       _("Status"),
                       _(CFG_BIBCIRCULATION_ILL_STATUS_REQUESTED), #_("Requested"),
                       _("Due date"),
                       _("Library"))
 
         if not record_is_periodical:
             out += """
                       <th>%s</th>
                    """ % (_("Location"))
 
         out += """
                       <th>%s</th>
                       <th>%s</th>
                 """ % (_("Loan period"),
                        _("No of loans"))
 
         if not record_is_periodical:
             out += """
                       <th>%s</th>
                    """ % (_("Collection"))
 
         out += """
                       <th>%s</th>
                       <th>%s</th>
                     </tr>
                   </thead>
                   <tboby>
                     """ % (_("Description"),
                            _("Actions"))
 
         for (barcode, loan_period, library_name, library_id,
              location, nb_requests, status, collection,
              description, due_date) in copies:
 
             number_of_requests = db.get_number_requests_per_copy(barcode)
             if number_of_requests > 0:
                 requested = 'Yes'
             else:
                 requested = 'No'
 
             if status in ('on order', 'claimed'):
                 expected_arrival_date = db.get_expected_arrival_date(barcode)
                 if expected_arrival_date != '':
                     status = status + ' - ' + expected_arrival_date
 
             library_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_library_details',
                                 {'library_id': library_id, 'ln': ln},
                                 (library_name))
 
             out += """
                  <tr>
                      <td>%s</td>
                      <td>%s</td>
                      <td>%s</td>
                      <td>%s</td>
                      <td>%s</td>
                      """ % (barcode, status, requested,
                             due_date or '-', library_link)
 
             if not record_is_periodical:
                 out += """
                      <td>%s</td>
                      """ % (location)
 
             out += """
                      <td>%s</td>
                      <td>%s</td>
                      """ % (loan_period, nb_requests)
 
             if not record_is_periodical:
                 out += """
                      <td>%s</td>
                      """ % (collection or '-')
 
             out += """
                      <td>%s</td>
                      """ % (description or '-')
 
             if status == CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN:
                 out += """
                   <td align="center">
                     <SELECT style='border: 1px solid #cfcfcf'
                             ONCHANGE="location = this.options[this.selectedIndex].value;">
                       <OPTION VALUE="">%s
                       <OPTION VALUE="update_item_info_step4?barcode=%s">%s
                       <OPTION VALUE="add_new_copy_step3?recid=%s&barcode=%s">%s
                       <OPTION VALUE="place_new_request_step1?barcode=%s">%s
                       <OPTION VALUE="" DISABLED>%s
                       <OPTION VALUE="" DISABLED>%s
                     </SELECT>
                   </td>
                  </tr>
                  """ % (_("Select an action"),
                         barcode, _("Update"),
                         recid, barcode, _("Add similar copy"),
                         barcode, _("New request"),
                         _("New loan"),
                         _("Delete copy"))
 
             elif status == 'missing':
                 out += """
                      <td align="center">
                        <SELECT style='border: 1px solid #cfcfcf'
                                ONCHANGE="location = this.options[this.selectedIndex].value;">
                          <OPTION VALUE="">%s
                          <OPTION VALUE="update_item_info_step4?barcode=%s">%s
                          <OPTION VALUE="add_new_copy_step3?recid=%s&barcode=%s">%s
                          <OPTION VALUE="" DISABLED>%s
                          <OPTION VALUE="" DISABLED>%s
                          <OPTION VALUE="delete_copy_step1?barcode=%s">%s
                        </SELECT>
                      </td>
                  </tr>
                  """ % (_("Select an action"),
                         barcode, _("Update"),
                         recid, barcode, _("Add similar copy"),
                         _("New request"),
                         _("New loan"),
                         barcode, _("Delete copy"))
 
             elif status == 'Reference':
                 out += """
                      <td align="center">
                        <SELECT style='border: 1px solid #cfcfcf'
                                ONCHANGE="location = this.options[this.selectedIndex].value;">
                          <OPTION VALUE="">%s
                          <OPTION VALUE="update_item_info_step4?barcode=%s">%s
                          <OPTION VALUE="add_new_copy_step3?recid=%s&barcode=%s">%s
                          <OPTION VALUE="place_new_request_step1?barcode=%s">%s
                          <OPTION VALUE="place_new_loan_step1?barcode=%s">%s
                          <OPTION VALUE="delete_copy_step1?barcode=%s">%s
                        </SELECT>
                      </td>
                  </tr>
                  """ % (_("Select an action"),
                         barcode, _("Update"),
                         recid, barcode, _("Add similar copy"),
                         barcode, _("New request"),
                         barcode, _("New loan"),
                         barcode, _("Delete copy"))
 
             else:
                 out += """
                      <td align="center">
                        <SELECT style='border: 1px solid #cfcfcf'
                                ONCHANGE="location = this.options[this.selectedIndex].value;">
                          <OPTION VALUE="">%s
                          <OPTION VALUE="update_item_info_step4?barcode=%s">%s
                          <OPTION VALUE="add_new_copy_step3?recid=%s&barcode=%s">%s
                          <OPTION VALUE="place_new_request_step1?barcode=%s">%s
                          <OPTION VALUE="place_new_loan_step1?barcode=%s">%s
                          <OPTION VALUE="delete_copy_step1?barcode=%s">%s
                        </SELECT>
                      </td>
                  </tr>
                  """ % (_("Select an action"),
                         barcode, _("Update"),
                         recid, barcode, _("Add similar copy"),
                         barcode, _("New request"),
                         barcode, _("New loan"),
                         barcode, _("Delete copy"))
 
         out += """
              </tbody>
             </table>
             """
 
         if record_is_periodical:
             out += """
             <div id="pager" class="pager">
                         <form>
                             <img src="/img/sb.gif" class="first" />
                             <img src="/img/sp.gif" class="prev" />
                             <input type="text" class="pagedisplay" />
                             <img src="/img/sn.gif" class="next" />
                             <img src="/img/se.gif" class="last" />
                             <select class="pagesize">
                                 <option value="10">10</option>
                                 <option value="20">20</option>
                                 <option value="30">30</option>
                                 <option value="40" selected="selected">40</option>
                             </select>
                         </form>
             </div>
             """
 
         out += """
             </br>
             <table class="bibcirctable">
                 <tr>
                     <td>
                     <input type=button
                 onClick="location.href='%s/admin2/bibcirculation/add_new_copy_step3?ln=%s&recid=%s'"
                     value='%s' class="formbutton">
 
                     <input
                     type=button
                 onClick="location.href='%s/admin2/bibcirculation/register_purchase_request_step1?ln=%s&recid=%s'"
                     value='%s' class="formbutton">
 
                 <!--<input
                 type=button
         onClick="location.href='%s/admin2/bibcirculation/register_ill_request_step0?ln=%s&recid=%s'"
                      value='%s'class="formbutton"> -->
                      </td>
                 </tr>
             </table>
             <br />
             <table class="bibcirctable">
                 <tr>
                     <td class="bibcirctableheader">%s</td>
                 </tr>
             </table>
             <table class="tablesortersmall" border="0" cellpadding="0" cellspacing="1">
                 <tr>
                     <th width="100">%s</th>
                     <td width="50">%s</td>
                     <td>
                     <input type="button" value='%s'
             onClick="location.href='%s/admin2/bibcirculation/get_item_requests_details?ln=%s&recid=%s'"
             onmouseover="this.className='bibcircbuttonover'"
             onmouseout="this.className='bibcircbutton'"
                       class="bibcircbutton">
                     </td>
                 </tr>
 
                 <tr>
                     <th width="100">%s</th>
                     <td width="50">%s</td>
                     <td>
                     <input type="button" value='%s'
             onClick="location.href='%s/admin2/bibcirculation/get_item_loans_details?ln=%s&recid=%s'"
             onmouseover="this.className='bibcircbuttonover'"
             onmouseout="this.className='bibcircbutton'"
                       class="bibcircbutton">
                     </td>
                 </tr>
 
             </table>
             <br />
             <table class="bibcirctable">
                  <tr>
                      <td class="bibcirctableheader">%s</td>
                 </tr>
             </table>
             <table class="tablesortersmall" border="0" cellpadding="0" cellspacing="1">
                  <tr>
                       <th width="100">%s</th>
                       <td width="50">%s</td>
                       <td>
                       <input type="button" value='%s'
     onClick="location.href='%s/admin2/bibcirculation/get_item_req_historical_overview?ln=%s&recid=%s'"
     onmouseover="this.className='bibcircbuttonover'"
     onmouseout="this.className='bibcircbutton'"
                       class="bibcircbutton">
                       </td>
                  </tr>
 
                  <tr>
                       <th width="100">%s</th>
                       <td width="50">%s</td>
                       <td>
                       <input type="button" value='%s'
 onClick="location.href='%s/admin2/bibcirculation/get_item_loans_historical_overview?ln=%s&recid=%s'"
     onmouseover="this.className='bibcircbuttonover'"
     onmouseout="this.className='bibcircbutton'"
                       class="bibcircbutton">
                       </td>
                  </tr>
             </table>
             <br />
             """ % (CFG_SITE_URL, ln, recid, _("Add new copy"),
             CFG_SITE_URL, ln, recid, _("Order new copy"),
             CFG_SITE_URL, ln, recid, _("ILL request"),
     _("Hold requests and loans overview on %(date)s")
     % {'date': dateutils.convert_datestruct_to_datetext(dateutils.localtime())},
     _("Hold requests"), len(requests), _("More details"), CFG_SITE_URL, ln, recid,
      _("Loans"), len(loans), _("More details"), CFG_SITE_URL, ln, recid,
     _("Historical overview"), _("Hold requests"), len(req_hist_overview),
     _("More details"), CFG_SITE_URL, ln, recid, _("Loans"),
     len(loans_hist_overview), _("More details"), CFG_SITE_URL, ln, recid)
 
         out += """
            <br />
            <table class="bibcirctable">
              <tr>
                <td>
                  <input type=button value='%s'
                  onClick="history.go(-1)" class="formbutton">
                </td>
              </tr>
            </table>
            <br />
            <br />
            <br />
            </div>
            """ % (_("Back"))
 
         return out
 
     def tmpl_bor_requests_historical_overview(self, req_hist_overview,
                                               ln=CFG_SITE_LANG):
         """
         Return the historical requests overview of a borrower.
 
         req_hist_overview: list of old requests.
         """
 
         _ = gettext_set_language(ln)
 
         out = load_menu(ln)
 
         if len(req_hist_overview) == 0:
             out += """
             <div class="bibcircbottom">
             <br />
             <div class="bibcircinfoboxmsg">%s</div>
             <br />
           """ % (_("There are no requests."))
 
         else:
             out += """<div class="bibcircbottom">
                     <br /> <br />
                     <style type="text/css"> @import url("/img/tablesorter.css"); </style>
                     <script src="/js/jquery/jquery.js" type="text/javascript"></script>
                     <script src="/js/jquery/jquery.tablesorter.js" type="text/javascript"></script>
                     <script type="text/javascript">
                       $(document).ready(function() {
                         $('#table_requests').tablesorter({widthFixed: true, widgets: ['zebra']})
                       });
                     </script>
                     <table id="table_requests" class="tablesorter"
                            border="0" cellpadding="0" cellspacing="1">
                     <thead>
                      <tr>
                      <th>%s</th>
                      <th>%s</th>
                      <th>%s</th>
                      <th>%s</th>
                      <th>%s</th>
                      <th>%s</th>
                      <th>%s</th>
                      </tr>
                     <thead>
                     <tbody>
                     """ % (_("Item"), _("Barcode"), _("Library"),
                            _("Location"), _("From"),
                            _("To"), _("Request date"))
 
             for (recid, barcode, library_name,
                  location, req_from, req_to, req_date) in req_hist_overview:
 
                 title_link = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_item_details',
                                     {'recid': recid, 'ln': ln},
                                     (book_title_from_MARC(recid)))
 
                 out += """ <tr>
                             <td>%s</td>
                             <td>%s</td>
                             <td>%s</td>
                             <td>%s</td>
                             <td>%s</td>
                             <td>%s</td>
                             <td>%s</td>
                            </tr>
                  """ % (title_link, barcode, library_name, location, req_from,
                         req_to, req_date)
 
         out += """
            </tbody>
            </table>
            <br />
            """
         out += """
            <table class="bibcirctable">
                 <tr>
                      <td><input type=button value='%s'
                           onClick="history.go(-1)" class="formbutton"></td>
                 </tr>
            </table>
            <br />
            <br />
            <br />
            </div>
 
            """ % (_("Back"))
 
         return out
 
     def tmpl_bor_loans_historical_overview(self, loans_hist_overview,
                                            ln=CFG_SITE_LANG):
         """
         Return the historical loans overview of a borrower.
 
         loans_hist_overview: list of old loans.
         """
 
         _ = gettext_set_language(ln)
 
         out = load_menu(ln)
 
         if len(loans_hist_overview) == 0:
             out += """
             <div class="bibcircbottom">
             <br />
             <div class="bibcircinfoboxmsg">%s</div>
             <br />
             """ % (_("There are no loans."))
 
         else:
             out += """<div class="bibcircbottom">
                       <style type="text/css"> @import url("/img/tablesorter.css"); </style>
                       <script src="/js/jquery/jquery.js" type="text/javascript"></script>
                       <script src="/js/jquery/jquery.tablesorter.js" type="text/javascript"></script>
                       <script type="text/javascript">
                         $(document).ready(function() {
                           $('#table_loans').tablesorter({widthFixed: true, widgets: ['zebra']})
                         });
                       </script>
                     <br /> <br />
                     <table id="table_loans" class="tablesorter"
                            border="0" cellpadding="0" cellspacing="1">
                     <thead>
                      <tr>
                      <th>%s</th>
                      <th>%s</th>
                      <th>%s</th>
                      <th>%s</th>
                      <th>%s</th>
                      <th>%s</th>
                      <th>%s</th>
                      <th>%s</th>
                      <th>%s</th>
                      </tr>
                    </thead>
                    <tbody>
                      """ % (_("Item"),
                             _("Barcode"),
                             _("Library"),
                             _("Location"),
                             _("Loaned on"),
                             _("Due date"),
                             _("Returned on"),
                             _("Renewals"),
                             _("Overdue letters"))
 
             recid = '-'
             barcode = '-'
             library_name = '-'
             location = '-'
             loaned_on = '-'
             due_date = '-'
             returned_on = '-'
             nb_renew = '-'
             nb_overdueletters = '-'
 
             for (recid, barcode, library_name, location, loaned_on, due_date,
                  returned_on, nb_renew,
                  nb_overdueletters) in loans_hist_overview:
 
                 title_link = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_item_details',
                                     {'recid': recid, 'ln': ln},
                                     (book_title_from_MARC(recid)))
 
                 out += """ <tr>
                            <td>%s</td>
                            <td>%s</td>
                            <td>%s</td>
                            <td>%s</td>
                            <td>%s</td>
                            <td>%s</td>
                            <td>%s</td>
                            <td>%s</td>
                            <td>%s</td>
                            </tr>
                      """ % (title_link, barcode,
                             library_name, location,
                             loaned_on, due_date,
                             returned_on, nb_renew,
                             nb_overdueletters)
 
         out += """
             </table>
             <br />
             <table class="bibcirctable">
                 <tr>
                     <td>
                         <input type=button value='%s'
                                onClick="history.go(-1)" class="formbutton">
                     </td>
                 </tr>
            </table>
            <br />
            <br />
            <br />
            </div>
 
            """ % (_("Back"))
 
         return out
 
     def tmpl_get_item_req_historical_overview(self, req_hist_overview,
                                           ln=CFG_SITE_LANG):
         """
         Return the historical requests overview of a item.
 
         req_hist_overview: list of old borrowers.
         """
 
         _ = gettext_set_language(ln)
 
         out = load_menu(ln)
 
         if len(req_hist_overview) == 0:
             out += """
             <div class="bibcircbottom">
             <br />
             <div class="bibcircinfoboxmsg">%s</div>
             <br />
             """ % (_("There are no requests."))
 
         else:
             out += """
              <div class="bibcircbottom">
              <style type="text/css"> @import url("/img/tablesorter.css"); </style>
             <script src="/js/jquery/jquery.js" type="text/javascript"></script>
             <script src="/js/jquery/jquery.tablesorter.js" type="text/javascript"></script>
             <script type="text/javascript">
             $(document).ready(function() {
               $('#table_holdings').tablesorter({widthFixed: true, widgets: ['zebra']})
             });
             </script>
               <br />
               <br />
               <table id="table_holdings" class="tablesorter"
                      border="0" cellpadding="0" cellspacing="1">
               <thead>
               <tr>
                <th>%s</th>
                <th>%s</th>
                <th>%s</th>
                <th>%s</th>
                <th>%s</th>
                <th>%s</th>
                <th>%s</th>
               </tr>
               </thead>
               </tbody>
                      """ % (_("Borrower"),
                             _("Barcode"),
                             _("Library"),
                             _("Location"),
                             _("From"),
                             _("To"),
                             _("Request date"))
 
             for (name, borrower_id, barcode, library_name,
                  location, req_from, req_to, req_date) in req_hist_overview:
 
                 borrower_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_borrower_details',
                                 {'borrower_id': borrower_id, 'ln': ln}, (name))
 
                 out += """
                   <tr>
                    <td>%s</td>
                    <td>%s</td>
                    <td>%s</td>
                    <td>%s</td>
                    <td>%s</td>
                    <td>%s</td>
                    <td>%s</td>
                   </tr>
 
                  """ % (borrower_link, barcode, library_name,
                         location, req_from, req_to, req_date)
 
         out += """
            </tbody>
            </table>
            <br />
            <table class="bibcirctable">
                 <tr>
                     <td>
                         <input type=button value='%s'
                                onClick="history.go(-1)"
                                class="formbutton">
                     </td>
                 </tr>
            </table>
            <br />
            <br />
            <br />
            </div>
 
            """ % (_("Back"))
 
         return out
 
     def tmpl_get_item_loans_historical_overview(self, loans_hist_overview,
                                             ln=CFG_SITE_LANG):
         """
         Return the historical loans overview of a item.
 
         loans_hist_overview: list of old borrowers.
         """
 
         _ = gettext_set_language(ln)
 
         out = """
         """
         out += load_menu(ln)
 
         out += """<div class="bibcircbottom">
                   <style type="text/css"> @import url("/img/tablesorter.css"); </style>
                   <script src="/js/jquery/jquery.js" type="text/javascript"></script>
                   <script src="/js/jquery/jquery.tablesorter.js" type="text/javascript"></script>
                   <script type="text/javascript">
                   $(document).ready(function() {
                     $('#table_loans').tablesorter({widthFixed: true, widgets: ['zebra']})
                   });
                   </script>
                     <br />
                     <br />
                     <table id="table_loans" class="tablesorter"
                            border="0" cellpadding="0" cellspacing="1">
                     <thead>
                      <tr>
                      <th>%s</th>
                      <th>%s</th>
                      <th>%s</th>
                      <th>%s</th>
                      <th>%s</th>
                      <th>%s</th>
                      <th>%s</th>
                      <th>%s</th>
                      <th>%s</th>
                      </tr>
                      </thead>
                      <tbody>
                      """ % (_("Borrower"),
                             _("Barcode"),
                             _("Library"),
                             _("Location"),
                             _("Loaned on"),
                             _("Due date"),
                             _("Returned on"),
                             _("Renewals"),
                             _("Overdue letters"))
 
         for (name, borrower_id, barcode, library_name, location, loaned_on,
              due_date, returned_on, nb_renew,
              nb_overdueletters) in loans_hist_overview:
 
             borrower_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_borrower_details',
                                 {'borrower_id': borrower_id, 'ln': ln}, (name))
 
             out += """ <tr>
                        <td>%s</td>
                        <td>%s</td>
                        <td>%s</td>
                        <td>%s</td>
                        <td>%s</td>
                        <td>%s</td>
                        <td>%s</td>
                        <td>%s</td>
                        <td>%s</td>
                        </tr>
                  """ % (borrower_link, barcode, library_name,
                         location, loaned_on,
                         due_date, returned_on, nb_renew,
                         nb_overdueletters)
 
         out += """
            </tbody>
            </table>
            <br />
            <table class="bibcirctable">
                 <tr>
                      <td><input type=button value='%s'
                           onClick="history.go(-1)" class="formbutton"></td>
                 </tr>
            </table>
            <br />
            <br />
            <br />
            </div>
 
            """ % (_("Back"))
 
         return out
 
     def tmpl_library_details(self, library_details, library_items,
                              ln=CFG_SITE_LANG):
         """
         @param ln: language of the page
         """
         _ = gettext_set_language(ln)
 
         out = """
         """
         out += load_menu(ln)
 
         out += """
         <style type="text/css"> @import url("/img/tablesorter.css"); </style>
         <div class="bibcircbottom">
         <br />
         """
         (library_id, name, address, email, phone,
          lib_type, notes) = library_details
 
         no_notes_link = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_library_notes',
                                     {'library_id': library_id},
                                     (_("No notes")))
 
         see_notes_link = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_library_notes',
                                     {'library_id': library_id},
                                     (_("Notes about this library")))
 
         if notes == "":
             notes_link = no_notes_link
         else:
             notes_link = see_notes_link
 
         out += """
             <table class="bibcirctable">
                  <tr>
                       <td width="80" class="bibcirctableheader">%s</td>
                  </tr>
             </table>
             <table class="tablesorterborrower" border="0" cellpadding="0" cellspacing="1">
 
                  <tr>
                       <th width="100">%s</th>
                       <td>%s</td>
                  </tr>
                  <tr>
                       <th width="100">%s</th>
                       <td>%s</td>
                  </tr>
                  <tr>
                       <th width="100">%s</th>
                       <td>%s</td>
                  </tr>
                  <tr>
                       <th width="100">%s</th>
                       <td>%s</td>
                  </tr>
                  <tr>
                       <th width="100">%s</th>
                       <td>%s</td>
                  </tr>
                  <tr>
                       <th width="100">%s</th>
                       <td>%s</td>
                  </tr>
                   <tr>
                       <th width="100">%s</th>
                       <td>%s</td>
                  </tr>
              </table>
              <table>
                  <tr>
                    <td>
                      <input type=button
     onClick="location.href='%s/admin2/bibcirculation/update_library_info_step3?ln=%s&library_id=%s'"
                      onmouseover="this.className='bibcircbuttonover'"
                      onmouseout="this.className='bibcircbutton'"
                      value="%s"  class="bibcircbutton">
                     <a href="%s/admin2/bibcirculation/merge_libraries_step1?ln=%s&library_id=%s">%s</a>
                       </td>
                  </tr>
             </table>
             """ % (_("Library details"),
                    _("Name"), name,
                    _("Address"), address,
                    _("Email"), email,
                    _("Phone"), phone,
                    _("Type"), lib_type,
                    _("Notes"), notes_link,
                    _("No of items"), len(library_items),
                    CFG_SITE_URL, ln, library_id, _("Update"),
                    CFG_SITE_URL, ln, library_id, _("Duplicated library?"))
 
         out += """
            </table>
            <br />
            <br />
            <table class="bibcirctable">
                 <tr>
                      <td><input type=button value='%s'
                           onClick="history.go(-1)" class="formbutton"></td>
                 </tr>
            </table>
            <br />
            <br />
            <br />
            </div>
            """ % (_("Back"))
 
         return out
 
     def tmpl_merge_libraries_step1(self, library_details, library_items,
                                          result, p, ln=CFG_SITE_LANG):
 
         _ = gettext_set_language(ln)
 
         out = """
         """
         out += load_menu(ln)
 
         out += """
         <style type="text/css"> @import url("/img/tablesorter.css"); </style>
         <div class="bibcircbottom">
         <br />
         """
         (library_id, name, address, email, phone,
          lib_type, notes) = library_details
 
         no_notes_link = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_library_notes',
                                     {'library_id': library_id},
                                     (_("No notes")))
 
         see_notes_link = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_library_notes',
                                     {'library_id': library_id},
                                     (_("Notes about this library")))
 
         if notes == "":
             notes_link = no_notes_link
         else:
             notes_link = see_notes_link
 
         out += """
             <table class="bibcirctable">
                 <tbody>
                     <tr>
                         <td align="left" valign="top" width="300">
                             <table class="bibcirctable">
                                 <tr>
                                     <td width="200" class="bibcirctableheader">%s</td>
                                 </tr>
                             </table>
                             <table class="tablesorter" border="0"
                                    cellpadding="0" cellspacing="1">
                                 <tr>
                                     <th width="100">%s</th>
                                     <td>%s</td>
                                 </tr>
                                 <tr>
                                     <th width="100">%s</th>
                                     <td>%s</td>
                                 </tr>
                                 <tr>
                                     <th width="100">%s</th>
                                     <td>%s</td>
                                 </tr>
                                 <tr>
                                     <th width="100">%s</th>
                                     <td>%s</td>
                                 </tr>
                                 <tr>
                                     <th width="100">%s</th>
                                     <td>%s</td>
                                 </tr>
                                 <tr>
                                     <th width="100">%s</th>
                                     <td>%s</td>
                                 </tr>
                                 <tr>
                                     <th width="100">%s</th>
                                     <td>%s</td>
                                 </tr>
                             </table>
                         </td>
                             """ % (_("Library to be deleted"),
                                    _("Name"), name,
                                    _("Address"), address,
                                    _("Email"), email,
                                    _("Phone"), phone,
                                    _("Type"), lib_type,
                                    _("Notes"), notes_link,
                                    _("No of items"), len(library_items))
 
 
         out += """
                         <td width="200" align="center" valign="top">
                         <td valign="top" align='left'>
                             <form name="search_library_step1_form"
                                     action="%s/admin2/bibcirculation/merge_libraries_step1"
                                     method="get" >
                                 <input type=hidden name=library_id value="%s">
                                 <table class="bibcirctable">
                                     <tr align="center">
                                         <td class="bibcirctableheader">%s
                                             <input type="radio" name="f"
                                                    value="name" checked>%s
                                             <input type="radio" name="f"
                                                    value="email">%s
                                             <br \>
                                             <br \>
                                         </td>
                                     </tr>
                                     <tr align="center">
                                         <td>
                                             <input type="text" size="45" name="p"
                                                    style='border: 1px solid #cfcfcf'
                                                    value="%s">
                                         </td>
                                     </tr>
                                 </table>
                                 <br />
                                 <table class="bibcirctable">
                                     <tr align="center">
                                         <td>
                                             <input type="submit" value='%s' class="formbutton">
                                         </td>
                                     </tr>
                                 </table>
                             </form>
             """ % (CFG_SITE_URL, library_id, _("Search library"),
                    _("name"), _("email"), p or '', _("Search"))
 
         if result:
             out += """
                             <br />
                             <form name="form2"
                                     action="%s/admin2/bibcirculation/merge_libraries_step2"
                                     method="get">
                                 <table class="bibcirctable">
                                     <tr width="200">
                                         <td align="center">
                                             <select name="library_to" size="12"
                                                     style='border: 1px
                                                     solid #cfcfcf; width:77%%'>
                             """ % (CFG_SITE_URL)
 
             for (library_to, library_name) in result:
                 if library_to != library_id:
                     out += """
                                                 <option value ='%s'>%s
 
                        """ % (library_to, library_name)
 
             out += """
                                             </select>
                                         </td>
                                     </tr>
                                 </table>
                                 <table class="bibcirctable">
                                     <tr>
                                         <td ALIGN="center">
                                             <input type="submit" value='%s' class="formbutton">
                                         </td>
                                     </tr>
                                 </table>
                                 <input type=hidden name=library_from value="%s">
                             </form>
                     """ % (_("Select library"), library_id)
 
         out += """
                         </td>
                     <tr>
                 </tbody>
             </table>
             <br />
             <br />
             <table class="bibcirctable">
                 <tr>
                     <td>
                         <input type=button value='%s'
                           onClick="history.go(-1)" class="formbutton">
                     </td>
                 </tr>
             </table>
             <br />
             <br />
             <br />
         </div>
            """ % (_("Back"))
 
         return out
 
     def tmpl_merge_libraries_step2(self, library_from_details,
                                    library_from_items, library_to_details,
                                    library_to_items, ln=CFG_SITE_LANG):
 
         _ = gettext_set_language(ln)
 
         out = load_menu(ln)
 
         out += """
         <style type="text/css"> @import url("/img/tablesorter.css"); </style>
         <div class="bibcircbottom">
         <br />
         """
 
         try:
             (library_id_1, name_1, address_1, email_1,
              phone_1, type_1, notes_1) = library_from_details
             found_1 = True
         except:
             found_1 = False
 
         try:
             (library_id_2, name_2, address_2, email_2,
              phone_2, type_2, notes_2) = library_to_details
             found_2 = True
         except:
             found_2 = False
 
         if found_1:
             no_notes_link_1 = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_library_notes',
                                     {'library_id': library_id_1},
                                     (_("No notes")))
 
             see_notes_link_1 = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_library_notes',
                                     {'library_id': library_id_1},
                                     (_("Notes about this library")))
             if notes_1 == "":
                 notes_link_1 = no_notes_link_1
             else:
                 notes_link_1 = see_notes_link_1
 
         if found_2:
             no_notes_link_2 = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_library_notes',
                                     {'library_id': library_id_2},
                                     (_("No notes")))
 
             see_notes_link_2 = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_library_notes',
                                     {'library_id': library_id_2},
                                     (_("Notes about this library")))
 
             if notes_2 == "":
                 notes_link_2 = no_notes_link_2
             else:
                 notes_link_2 = see_notes_link_2
 
         if found_1 and found_2:
             out += """
             <br />
             <div class="infoboxmsg">
                 <strong>
                     %s
                 </strong>
             </div>
             <br />
           """ % (_("Please, note that this action is NOT reversible"))
 
         out += """
             <table class="bibcirctable">
                 <tbody>
                     <tr>
             """
 
         if found_1:
             out += """
                         <td align="left" valign="top" width="300">
                             <table class="bibcirctable">
                                 <tr>
                                     <td width="200" class="bibcirctableheader">%s</td>
                                 </tr>
                             </table>
                             <table class="tablesorter" border="0"
                                    cellpadding="0" cellspacing="1">
                                 <tr>
                                     <th width="100">%s</th>
                                     <td>%s</td>
                                 </tr>
                                 <tr>
                                     <th width="100">%s</th>
                                     <td>%s</td>
                                 </tr>
                                 <tr>
                                     <th width="100">%s</th>
                                     <td>%s</td>
                                 </tr>
                                 <tr>
                                     <th width="100">%s</th>
                                     <td>%s</td>
                                 </tr>
                                 <tr>
                                     <th width="100">%s</th>
                                     <td>%s</td>
                                 </tr>
                                 <tr>
                                     <th width="100">%s</th>
                                     <td>%s</td>
                                 </tr>
                                 <tr>
                                     <th width="100">%s</th>
                                     <td>%s</td>
                                 </tr>
                             </table>
                 """ % (_("Library to be deleted"),
                    _("Name"), name_1,
                    _("Address"), address_1,
                    _("Email"), email_1,
                    _("Phone"), phone_1,
                    _("Type"), type_1,
                    _("Notes"), notes_link_1,
                    _("No of items"), len(library_from_items))
         else:
             out += """
                         <td align="left" valign="center" width="300">
                             <div class="infoboxmsg">%s</div>
                         """ % (_("Library not found"))
 
         out += """
                         </td>
                         <td width="200" align="center" valign="center">
                             <strong>==></strong>
                         </td>
                 """
 
         if found_2:
             out += """
                         <td align="left" valign="top" width="300">
                             <table class="bibcirctable">
                                 <tr>
                                     <td width="200" class="bibcirctableheader">%s</td>
                                 </tr>
                             </table>
                             <table class="tablesorter" border="0"
                                    cellpadding="0" cellspacing="1">
                                 <tr>
                                     <th width="100">%s</th>
                                     <td>%s</td>
                                 </tr>
                                 <tr>
                                     <th width="100">%s</th>
                                     <td>%s</td>
                                 </tr>
                                 <tr>
                                     <th width="100">%s</th>
                                     <td>%s</td>
                                 </tr>
                                 <tr>
                                     <th width="100">%s</th>
                                     <td>%s</td>
                                 </tr>
                                 <tr>
                                     <th width="100">%s</th>
                                     <td>%s</td>
                                 </tr>
                                 <tr>
                                     <th width="100">%s</th>
                                     <td>%s</td>
                                 </tr>
                                 <tr>
                                     <th width="100">%s</th>
                                     <td>%s</td>
                                 </tr>
                             </table>
 
                 """ % (_("Merged library"),
                    _("Name"), name_2,
                    _("Address"), address_2,
                    _("Email"), email_2,
                    _("Phone"), phone_2,
                    _("Type"), type_2,
                    _("Notes"), notes_link_2,
                    _("No of items"), len(library_to_items))
         else:
             out += """
                         <td align="left" valign="center" width="300">
                             <div class="infoboxmsg">%s</div>
                         """ % (_("Library not found"))
 
         out += """
                         </td>
                     <tr>
                 </tbody>
             </table>
             <br />
             <br />
             <form name="form1" action="%s/admin2/bibcirculation/merge_libraries_step3"
                                method="get">
                 <table class="bibcirctable">
                     <tr>
                         <td>
                             <input type=button value='%s'
                               onClick="history.go(-1)" class="formbutton">
                 """ % (CFG_SITE_URL, _("Back"))
 
         if found_1 and found_2:
             out += """
                             <input type=hidden name=library_from value="%s">
                             <input type=hidden name=library_to value="%s">
                             <input type="submit" value='%s' class="formbutton">
                 """ % (library_id_1, library_id_2, _("Confirm"))
 
         out += """
                         </td>
                     </tr>
                 </table>
             </form>
             <br />
             <br />
             <br />
         </div>
            """
 
         return out
 
     def tmpl_borrower_details(self, borrower, requests, loans, notes,
                               ill, req_hist, loans_hist, ill_hist,
                               ln=CFG_SITE_LANG):
         """
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         out = load_menu(ln)
 
         (borrower_id, ccid, name, email, phone, address, mailbox) = borrower
 
         display_id = borrower_id
         id_string = _("ID")
         if CFG_CERN_SITE == 1:
             display_id = ccid
             id_string = _("CCID")
 
         no_notes_link = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_borrower_notes',
                                     {'borrower_id': borrower_id},
                                     (_("No notes")))
 
         see_notes_link = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_borrower_notes',
                                     {'borrower_id': borrower_id},
                                     (_("Notes about this borrower")))
 
         if notes == "" or str(notes) == '{}':
             check_notes = no_notes_link
         else:
             check_notes = see_notes_link
 
 
         out += """
             <style type="text/css"> @import url("/img/tablesorter.css"); </style>
             <div class="bibcircbottom">
 
             <br />
             <table class="bibcirctable">
                  <tr>
                       <td class="bibcirctableheader">%s</td>
                  </tr>
              </table>
             </form>
             <table class="tablesorterborrower" border="0" cellpadding="0" cellspacing="1">
               <tr>
                 <th width="100">%s</th>
                 <td>%s</td>
               </tr>
               <tr>
                 <th width="100">%s</th>
                 <td>%s</td>
               </tr>
               <tr>
                 <th width="100">%s</th>
                 <td>%s</td>
               </tr>
               <tr>
                 <th width="100">%s</th>
                 <td>%s</td>
               </tr>
               <tr>
                 <th width="100">%s</th>
                 <td>%s</td>
               </tr>
               <tr>
                 <th width="100">%s</th>
                 <td>%s</td>
                </tr>
                <tr>
                  <th width="100">%s</th>
                  <td>%s</td>
                </tr>
 
             """ % (_("Personal details"),
                    id_string, display_id,
                    _("Name"), name,
                    _("Address"), address,
                    _("Mailbox"), mailbox,
                    _("Email"), email,
                    _("Phone"), phone,
                    _("Notes"), check_notes)
 
         nb_requests = len(requests)
         nb_loans = len(loans)
         nb_ill = len(ill)
         nb_req_hist = len(req_hist)
         nb_loans_hist = len(loans_hist)
         nb_ill_hist = len(ill_hist)
 
         out += """
         </table>
         <br />
         <table class="bibcirctable">
           <tr>
             <td>
             <input type=button
                 onClick="location.href='%s/admin2/bibcirculation/loan_on_desk_step2?ln=%s&user_id=%s'"
                 value='%s' class='formbutton'>
 
             <input type=button
     onClick="location.href='%s/admin2/bibcirculation/create_new_request_step1?ln=%s&borrower_id=%s'"
                 value='%s' class='formbutton'>
 
             <input type=button
     onClick="location.href='%s/admin2/bibcirculation/register_ill_book_request?ln=%s&borrower_id=%s'"
                 value='%s' class='formbutton'>
 
             <input type=button
     onClick="location.href='%s/admin2/bibcirculation/borrower_notification?ln=%s&borrower_id=%s'"
                 value='%s' class='formbutton'>
         """ % (CFG_SITE_URL, ln, borrower_id, _("New loan"),
                CFG_SITE_URL, ln, borrower_id, _("New request"),
                CFG_SITE_URL, ln, borrower_id, _("New ILL request"),
                CFG_SITE_URL, ln, borrower_id, _("Notify this borrower"))
 
         if CFG_CERN_SITE:
             out += """
             <input type=button onClick=
 "location.href='%s/admin2/bibcirculation/get_borrower_details?ln=%s&borrower_id=%s&update=True'"
                 value="%s" class='formbutton'>
             """ % (CFG_SITE_URL, ln, borrower_id, _("Update"))
 
         else:
             out += """
             <input type=button
     onClick=
        "location.href='%s/admin2/bibcirculation/update_borrower_info_step1?ln=%s&borrower_id=%s'"
                 value="%s" class='formbutton'>
             """ % (CFG_SITE_URL, ln, borrower_id, _("Update"))
 
         out += """
             </td>
 
           </tr>
         </table>
         <br />
         <table class="bibcirctable">
           <tr>
             <td class="bibcirctableheader">%s %s</td>
           </tr>
         </table>
         <table class="tablesortersmall" border="0" cellpadding="0" cellspacing="1">
           <tr>
             <th width="100">%s</th>
             <td width="50">%s</td>
             <td>
               <input type="button"
               onClick="location.href='%s/admin2/bibcirculation/get_borrower_requests_details?ln=%s&borrower_id=%s'"
               onmouseover="this.className='bibcircbuttonover'" onmouseout="this.className='bibcircbutton'"
               value='%s' class="bibcircbutton">
             </td>
           </tr>
           <tr>
             <th width="100">%s</th>
             <td width="50">%s</td>
             <td>
               <input type="button"
               onClick="location.href='%s/admin2/bibcirculation/get_borrower_loans_details?ln=%s&borrower_id=%s'"
               onmouseover="this.className='bibcircbuttonover'" onmouseout="this.className='bibcircbutton'"
               value='%s' class="bibcircbutton">
             </td>
           </tr>
           <tr>
             <th width="100">%s</th>
             <td width="50">%s</td>
             <td>
               <input type="button"
               onClick="location.href='%s/admin2/bibcirculation/get_borrower_ill_details?ln=%s&borrower_id=%s'"
               onmouseover="this.className='bibcircbuttonover'" onmouseout="this.className='bibcircbutton'"
               value='%s' class="bibcircbutton">
             </td>
           </tr>
         </table>
         <br />
         <table class="bibcirctable">
           <tr>
             <td class="bibcirctableheader">%s</td>
           </tr>
         </table>
         <table class="tablesortersmall" border="0" cellpadding="0" cellspacing="1">
           <tr>
             <th width="100">%s</th>
             <td width="50">%s</td>
             <td>
               <input type="button"
               onClick="location.href='%s/admin2/bibcirculation/bor_requests_historical_overview?ln=%s&borrower_id=%s'"
               onmouseover="this.className='bibcircbuttonover'" onmouseout="this.className='bibcircbutton'"
               value='%s' class="bibcircbutton">
             </td>
           </tr>
           <tr>
             <th width="100">%s</th>
             <td width="50">%s</td>
             <td>
               <input type="button"
               onClick="location.href='%s/admin2/bibcirculation/bor_loans_historical_overview?ln=%s&borrower_id=%s'"
               onmouseover="this.className='bibcircbuttonover'" onmouseout="this.className='bibcircbutton'"
               value='%s' class="bibcircbutton">
             </td>
           </tr>
           <tr>
             <th width="100">%s</th>
             <td width="50">%s</td>
             <td>
               <input type="button"
 onClick="location.href='%s/admin2/bibcirculation/bor_ill_historical_overview?ln=%s&borrower_id=%s'"
               onmouseover="this.className='bibcircbuttonover'"
               onmouseout="this.className='bibcircbutton'"
               value='%s' class="bibcircbutton">
             </td>
           </tr>
         </table>
         <br />
         <table class="bibcirctable">
           <tr>
             <td><input type=button value='%s'
                  onClick="history.go(-1)" class="formbutton"></td>
           </tr>
         </table>
         <br />
         </div>
         """ % (_("Requests, Loans and ILL overview on"),
                dateutils.convert_datestruct_to_datetext(dateutils.localtime()),
                _("Requests"), nb_requests, CFG_SITE_URL, ln, borrower_id,
                _("More details"),
                _("Loans"), nb_loans, CFG_SITE_URL, ln, borrower_id,
                _("More details"),
                _("ILL"), nb_ill, CFG_SITE_URL, ln, borrower_id,
                _("More details"),
                _("Historical overview"),
                _("Requests"), nb_req_hist, CFG_SITE_URL, ln, borrower_id,
                _("More details"),
                _("Loans"), nb_loans_hist, CFG_SITE_URL, ln, borrower_id,
                _("More details"),
                _("ILL"), nb_ill_hist, CFG_SITE_URL, ln, borrower_id,
                _("More details"),
                _("Back"))
 
 
         return out
 
     def tmpl_borrower_request_details(self, result, borrower_id,
                                       ln=CFG_SITE_LANG):
         """
         @param ln: language of the page
         """
         _ = gettext_set_language(ln)
 
         out = """
         """
         out += load_menu(ln)
 
         if len(result) == 0:
             out += """
             <div class="bibcircbottom">
             <br />
             <div class="bibcircinfoboxmsg">%s</div>
             <br />
           """ % (_("There are no requests."))
 
         else:
             out += """
          <style type="text/css"> @import url("/img/tablesorter.css"); </style>
          <script src="/js/jquery/jquery.js" type="text/javascript"></script>
          <script src="/js/jquery/jquery.tablesorter.js" type="text/javascript"></script>
          <script type="text/javascript">
            $(document).ready(function() {
              $('#table_requests').tablesorter({widthFixed: true, widgets: ['zebra']})
            });
          </script>
         <form name="borrower_form" action="%s/admin2/bibcirculation/get_borrower_requests_details" method="get" >
         <div class="bibcircbottom">
         <br />
              <table id="table_requests" class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                <thead>
                     <tr>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                    </tr>
               </thead>
               <tbody>
         </form>
          """% (CFG_SITE_URL,
                _("Item"),
                _("Request status"),
                _("Library"),
                _("Location"),
                _("From"),
                _("To"),
                _("Request date"),
                _("Request option(s)"))
 
             for (recid, status, library, location, date_from,
                  date_to, request_date, request_id) in result:
 
                 title_link = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_item_details',
                                     {'recid': recid, 'ln': ln},
                                     (book_title_from_MARC(recid)))
 
                 out += """
             <tr>
                  <td>%s</td>
                  <td>%s</td>
                  <td>%s</td>
                  <td>%s</td>
                  <td>%s</td>
                  <td>%s</td>
                  <td>%s</td>
                  <td align="center">
                  <input type="button" value='%s' style="background: url(/img/jquery/dialog-cancel.png)
                  no-repeat; width: 75px; text-align: right;"
     onClick="location.href='%s/admin2/bibcirculation/get_pending_requests?ln=%s&request_id=%s'"
                  onmouseover="this.className='bibcircbuttonover'"
                  onmouseout="this.className='bibcircbutton'"
                  class="bibcircbutton">
                  </td>
             </tr>
 
             """ % (title_link, status, library, location, date_from,
                    date_to, request_date, _("Cancel"),
                    CFG_SITE_URL, ln, request_id)
 
 
         out += """
         </tbody>
         </table>
         <br />
         <table class="bibcirctable">
              <tr>
                   <td>
                     <input type=button onClick="location.href='%s/admin2/bibcirculation/get_borrower_details?ln=%s&borrower_id=%s'"
                     value='%s' class='formbutton'>
                   </td>
              </tr>
         </table>
         <br />
         </div>
         """ % (CFG_SITE_URL, ln,
                borrower_id,
                _("Back"))
 
         return out
 
     def tmpl_borrower_loans_details(self, borrower_loans, borrower_id, infos,
                                     ln=CFG_SITE_LANG):
         """
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         out = self.tmpl_infobox(infos, ln)
 
         out += load_menu(ln)
 
         if len(borrower_loans) == 0:
             out += """
             <div class="bibcircbottom">
             <br />
             <div class="bibcircinfoboxmsg">%s</div>
             <br />
           """ % (_("There are no loans."))
 
         else:
             out += """
         <form name="borrower_form" action="%s/admin2/bibcirculation/get_borrower_loans_details?submit_changes=true" method="get" >
         <input type=hidden name=borrower_id value="%s">
         <div class="bibcircbottom">
 
         <style type="text/css"> @import url("/img/tablesorter.css"); </style>
         <script src="/js/jquery/jquery.js" type="text/javascript"></script>
         <script src="/js/jquery/jquery.tablesorter.js" type="text/javascript"></script>
         <script type="text/javascript">
         $(document).ready(function() {
           $('#table_loans').tablesorter({widthFixed: true, widgets: ['zebra']})
         });
         </script>
 
         <br />
              <table id="table_loans" class="tablesorter" border="0" cellpadding="0" cellspacing="1">
              <thead>
                <tr>
                  <th>%s</th>
                  <th>%s</th>
                  <th>%s</th>
                  <th>%s</th>
                  <th>%s</th>
                  <th>%s</th>
                  <th>%s</th>
                  <th>%s</th>
                  <th>%s</th>
                  <th>%s</th>
                </tr>
              </thead>
              <tbody>
 
          """% (CFG_SITE_URL,
                borrower_id,
                _("Item"),
                _("Barcode"),
                _("Loan date"),
                _("Due date"),
                _("Renewals"),
                _("Overdue letters"),
                _("Type"),
                _("Loan notes"),
                _("Loans status"),
                _("Loan options"))
 
 
             for (recid, barcode, loaned_on, due_date, nb_renewall,
                  nb_overdue, date_overdue, loan_type, notes,
                  loan_id, status) in borrower_loans:
 
                 title_link = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_item_details',
                                     {'recid': recid, 'ln': ln},
                                     (book_title_from_MARC(recid)))
 
                 no_notes_link = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_loans_notes',
                                     {'loan_id': loan_id, 'ln': ln},
                                     (_("No notes")))
 
                 see_notes_link = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_loans_notes',
                                     {'loan_id': loan_id, 'ln': ln},
                                     (_("See notes")))
 
                 if notes == "":
                     check_notes = no_notes_link
                 else:
                     check_notes = see_notes_link
 
 
                 out += """
             <tr>
               <td>%s</td>
               <td>%s</td>
               <td>%s</td>
               <td>%s</td>
               <td>%s</td>
               <td>%s - %s</td>
               <td>%s</td>
               <td>%s</td>
               <td>%s</td>
               """ % (title_link, barcode, loaned_on, due_date, nb_renewall,
                      nb_overdue, date_overdue, loan_type, check_notes, status)
 
                 out += """
               <td align="center">
                 <SELECT style='border: 1px solid #cfcfcf'
                         ONCHANGE="location = this.options[this.selectedIndex].value;">
         <OPTION VALUE="">%s
         <OPTION
             VALUE="get_borrower_loans_details?borrower_id=%s&barcode=%s&loan_id=%s&recid=%s">%s
                   <OPTION VALUE="loan_return_confirm?barcode=%s">%s
                 """ % (_("Select an action"),
                        borrower_id, barcode, loan_id, recid, _("Renew"),
                        barcode, _("Return"))
 
                 if status == CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED:
                     out += """
         <OPTION VALUE="change_due_date_step1?barcode=%s&borrower_id=%s" DISABLED>%s
                   """ % (barcode, borrower_id, _("Change due date"))
                 else:
                     out += """
         <OPTION VALUE="change_due_date_step1?barcode=%s&borrower_id=%s">%s
                   """ % (barcode, borrower_id, _("Change due date"))
 
                 out += """
                 <OPTION VALUE="claim_book_return?borrower_id=%s&recid=%s&loan_id=%s&template=claim_return">%s
                 </SELECT>
               </td>
                 <input type=hidden name=barcode value="%s">
                 <input type=hidden name=loan_id value="%s">
             </tr>
             """ % (borrower_id, recid, loan_id, _("Send recall"),
                    barcode, loan_id)
 
             out += """
         </tbody>
         </table>
         <br />
         <table class="bibcirctable">
           <tr>
             <td class="bibcirccontent" align="right" width="100">
               <input type=button onClick="location.href='%s/admin2/bibcirculation/get_borrower_loans_details?ln=%s&borrower_id=%s&renewall=true'"
               value='%s' class='bibcircbutton'onmouseover="this.className='bibcircbuttonover'" onmouseout="this.className='bibcircbutton'"></td>
           </tr>
         </table>
         """ % (CFG_SITE_URL, ln,
                borrower_id,
                _("Renew all loans"))
 
         out += """
         <table class="bibcirctable">
           <tr>
             <td>
               <input type=button
     onClick="location.href='%s/admin2/bibcirculation/get_borrower_details?ln=%s&borrower_id=%s'"
               value='%s' class='formbutton'></td>
           </tr>
         </table>
         <br />
         </div>
         </form>
 
         """ % (CFG_SITE_URL, ln,
                borrower_id,
                _("Back"))
 
 
         return out
 
     def tmpl_all_loans(self, result, infos, ln=CFG_SITE_LANG):
         """
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         out = self.tmpl_infobox(infos, ln)
 
         out += load_menu(ln)
 
         out += """
             <style type="text/css"> @import url("/js/jquery/tablesorter/themes/blue/style.css"); </style>
             <style type="text/css"> @import url("/js/jquery/tablesorter/addons/pager/jquery.tablesorter.pager.css"); </style>
 
             <script src="/js/jquery/tablesorter/jquery.tablesorter.js" type="text/javascript"></script>
             <script src="/js/jquery/tablesorter/addons/pager/jquery.tablesorter.pager.js" type="text/javascript"></script>
             <script type="text/javascript">
             $(document).ready(function(){
                 $("#table_all_loans")
                     .tablesorter({sortList: [[3,1], [0,0]],widthFixed: true, widgets: ['zebra']})
                     .bind("sortStart",function(){$("#overlay").show();})
                     .bind("sortEnd",function(){$("#overlay").hide()})
                     .tablesorterPager({container: $("#pager"), positionFixed: false});
             });
             </script>
 
             <br />
 
             <div class="bibcircbottom">
             """
 
         if len(result) == 0:
             out += """
               <br />
               <table class="bibcirctable">
                 <tr>
                     <td class="bibcirccontent">%s</td>
                 </tr>
                 </table>
                 <br />
                 <table class="bibcirctable">
                 <tr>
                   <td>
                     <input type=button value='%s' onClick="history.go(-1)" class="formbutton">
                   </td>
                 </tr>
                 </table>
                 <br />
                 <br />
                 </div>
                 """ % (_("No result for your search."),
                        _("Back"))
 
         else:
             out += """
             <form name="borrower_form" action="%s/admin2/bibcirculation/all_loans" method="get" >
             <br />
             <table id="table_all_loans" class="tablesorter"
                    border="0" cellpadding="0" cellspacing="1">
                <thead>
                     <tr>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th></th>
                     </tr>
                </thead>
               <tbody>
                        """% (CFG_SITE_URL,
                           _("Borrower"),
                           _("Item"),
                           _("Barcode"),
                           _("Loaned on"),
                           _("Due date"),
                           _("Renewals"),
                           _("Overdue letters"),
                           _("Loan Notes"))
 
             for (borrower_id, borrower_name, recid, barcode,
                  loaned_on, due_date, nb_renewall, nb_overdue,
                  date_overdue, notes, loan_id) in result:
 
                 borrower_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_borrower_details',
                                 {'borrower_id': borrower_id, 'ln': ln},
                                 (borrower_name))
 
                 see_notes_link = create_html_link(CFG_SITE_URL +
                                '/admin2/bibcirculation/get_loans_notes',
                                {'loan_id': loan_id, 'ln': ln}, (_("see notes")))
 
                 no_notes_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_loans_notes',
                                 {'loan_id': loan_id, 'ln': ln}, (_("no notes")))
 
 
                 if notes == "":
                     check_notes = no_notes_link
                 elif str(notes) == '{}':
                     check_notes = no_notes_link
                 else:
                     check_notes = see_notes_link
 
                 title_link = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_item_details',
                                     {'recid': recid, 'ln': ln},
                                     (book_title_from_MARC(recid)))
 
                 out += """
                     <tr>
                         <td>%s</td>
                         <td>%s</td>
                         <td>%s</td>
                         <td>%s</td>
                         <td>%s</td>
                         <td>%s</td>
                         <td>%s - %s</td>
                         <td>%s</td>
                         <td align="center">
                         <input type=button onClick="location.href='%s/admin2/bibcirculation/claim_book_return?borrower_id=%s&recid=%s&loan_id=%s&template=claim_return'" onmouseover="this.className='bibcircbuttonover'" onmouseout="this.className='bibcircbutton'"
                              value='%s' class='bibcircbutton'></td>
                     </tr>
 
                     """ % (borrower_link, title_link, barcode,
                            loaned_on, due_date,
                            nb_renewall, nb_overdue, date_overdue,
                            check_notes, CFG_SITE_URL,
                            borrower_id, recid, loan_id, _("Send recall"))
 
             out += """
                     </tbody>
                     </table>
                     </form>
 
                     <div id="pager" class="pager">
                         <form>
                             <br />
                             <img src="/img/sb.gif" class="first" />
                             <img src="/img/sp.gif" class="prev" />
                             <input type="text" class="pagedisplay" />
                             <img src="/img/sn.gif" class="next" />
                             <img src="/img/se.gif" class="last" />
                             <select class="pagesize">
                                 <option value="10" selected="selected">10</option>
                                 <option value="20">20</option>
                                 <option value="30">30</option>
                                 <option value="40">40</option>
                             </select>
                         </form>
                     </div>
                     """
             out += """
                     <div class="back" style="position: relative; top: 5px;">
                         <br />
                         <table class="bibcirctable">
                             <tr>
                                 <td>
                                     <input type=button value='%s'
                                            onClick="history.go(-1)"
                                            class="formbutton">
                                 </td>
                             </tr>
                         </table>
                     <br />
                     <br />
                     </div>
                     </div>
                     """ % (_("Back"))
 
         return out
 
     def tmpl_all_expired_loans(self, result, infos, ln=CFG_SITE_LANG):
         """
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         out = self.tmpl_infobox(infos, ln)
 
         out += load_menu(ln)
 
         out += """
             <style type="text/css"> @import url("/js/jquery/tablesorter/themes/blue/style.css"); </style>
             <style type="text/css"> @import url("/js/jquery/tablesorter/addons/pager/jquery.tablesorter.pager.css"); </style>
 
             <script src="/js/jquery/tablesorter/jquery.tablesorter.js" type="text/javascript"></script>
             <script src="/js/jquery/tablesorter/addons/pager/jquery.tablesorter.pager.js" type="text/javascript"></script>
             <script type="text/javascript">
             $(document).ready(function(){
                 $("#table_all_loans")
                     .tablesorter({sortList: [[3,1], [0,0]],widthFixed: true, widgets: ['zebra']})
                     .bind("sortStart",function(){$("#overlay").show();})
                     .bind("sortEnd",function(){$("#overlay").hide()})
                     .tablesorterPager({container: $("#pager"), positionFixed: false});
             });
             </script>
 
             <br />
 
             <div class="bibcircbottom">
             """
 
         if len(result) == 0:
             out += """
               <br />
               <table class="bibcirctable">
                 <tr>
                     <td class="bibcirccontent">%s</td>
                 </tr>
                 </table>
                 <br />
                 <table class="bibcirctable">
                 <tr>
                   <td>
                     <input type=button value='%s'
                            onClick="history.go(-1)" class="formbutton">
                   </td>
                 </tr>
                 </table>
                 <br />
                 <br />
                 </div>
                 """ % (_("No result for your search."),
                        _("Back"))
 
         else:
             out += """
             <form name="borrower_form"
                   action="%s/admin2/bibcirculation/all_loans"
                   method="get" >
             <br />
             <table id="table_all_loans" class="tablesorter"
                     border="0" cellpadding="0" cellspacing="1">
                <thead>
                     <tr>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th></th>
                     </tr>
                </thead>
               <tbody>
                        """% (CFG_SITE_URL,
                           _("Borrower"),
                           _("Item"),
                           _("Barcode"),
                           _("Loaned on"),
                           _("Due date"),
                           _("Renewals"),
                           _("Overdue letters"),
                           _("Loan Notes"))
 
             for (borrower_id, borrower_name, recid, barcode,
                  loaned_on, due_date, nb_renewall, nb_overdue,
                  date_overdue, notes, loan_id) in result:
 
                 borrower_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_borrower_details',
                                 {'borrower_id': borrower_id, 'ln': ln},
                                 (borrower_name))
 
                 see_notes_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_loans_notes',
                                 {'loan_id': loan_id, 'ln': ln},
                                 (_("see notes")))
 
                 no_notes_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_loans_notes',
                                 {'loan_id': loan_id, 'ln': ln},
                                  (_("no notes")))
 
 
                 if notes == "":
                     check_notes = no_notes_link
                 elif str(notes) == '{}':
                     check_notes = no_notes_link
                 else:
                     check_notes = see_notes_link
 
                 title_link = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_item_details',
                                     {'recid': recid, 'ln': ln},
                                     (book_title_from_MARC(recid)))
 
                 out += """
                     <tr>
                         <td>%s</td>
                         <td>%s</td>
                         <td>%s</td>
                         <td>%s</td>
                         <td>%s</td>
                         <td>%s</td>
                         <td>%s - %s</td>
                         <td>%s</td>
                         <td align="center">
                         <input type=button onClick="location.href='%s/admin2/bibcirculation/claim_book_return?borrower_id=%s&recid=%s&loan_id=%s&template=claim_return'" onmouseover="this.className='bibcircbuttonover'" onmouseout="this.className='bibcircbutton'"
                              value='%s' class='bibcircbutton'></td>
                     </tr>
 
                     """ % (borrower_link, title_link, barcode,
                            loaned_on, due_date,
                            nb_renewall, nb_overdue, date_overdue,
                            check_notes, CFG_SITE_URL,
                            borrower_id, recid, loan_id, _("Send recall"))
 
 
             out += """
                     </tbody>
                     </table>
                     </form>
 
                     <div id="pager" class="pager">
                         <form>
                             <br />
                             <img src="/img/sb.gif" class="first" />
                             <img src="/img/sp.gif" class="prev" />
                             <input type="text" class="pagedisplay" />
                             <img src="/img/sn.gif" class="next" />
                             <img src="/img/se.gif" class="last" />
                             <select class="pagesize">
                                 <option value="10" selected="selected">10</option>
                                 <option value="20">20</option>
                                 <option value="30">30</option>
                                 <option value="40">40</option>
                             </select>
                         </form>
                     </div>
                     """
             out += """
                     <div class="back" style="position: relative; top: 5px;">
                         <br />
                         <table class="bibcirctable">
                             <tr>
                                 <td>
                                     <input type=button value='%s'
                                            onClick="history.go(-1)" class="formbutton">
                                 </td>
                             </tr>
                         </table>
                     <br />
                     <br />
                     </form>
                     </div>
                     </div>
                     """ % (_("Back"))
 
         return out
 
     def tmpl_borrower_notification(self, email, subject, email_body,
                                    borrower_id, ln=CFG_SITE_LANG):
         """
         @param result: template used for the notification
         @param ln: language of the page
         """
 
         if subject is None:
             subject = ""
 
         _ = gettext_set_language(ln)
 
         out = load_menu(ln)
 
         out += """
         <style type="text/css"> @import url("/img/tablesorter.css"); </style>
         <form name="borrower_notification"
               action="%s/admin2/bibcirculation/borrower_notification"
               method="get" >
             <div class="bibcircbottom">
             <input type=hidden name=borrower_id value="%s">
             <br />
             <table class="tablesortermedium" border="0" cellpadding="0" cellspacing="1">
                 <tr>
                     <th width="50">%s</th>
                     <td>%s</td>
                 </tr>
                 <tr>
                     <th width="50">%s</th>
         """ % (CFG_SITE_URL,
                borrower_id,
                _("From"),
                _("CERN Library"),
                _("To"))
 
         out += """
         <td>
         <input type="text" name="borrower_email"
                size="60" style='border: 1px solid #cfcfcf' value="%s">
         </td>
         </tr>
         """ % (email)
 
         out += """
             <tr>
                 <th width="50">%s</th>
                 <td>
                     <input type="text" name="subject" size="60"
                            value="%s" style='border: 1px solid #cfcfcf'>
                 </td>
             </tr>
         </table>
 
         <br />
 
         <table class="tablesortermedium" border="0" cellpadding="0" cellspacing="1">
             <tr>
                 <th width="500">%s</th>
                 <th>%s</th>
             </tr>
             <tr>
                 <td>
                     <textarea rows="10" cols="100" name="message"
                               style='border: 1px solid #cfcfcf'>%s</textarea>
                 </td>
         """ % (_("Subject"),
                subject,
                _("Message"),
                _("Choose a template"),
                email_body)
 
         out += """
                <td>
                     <select name="template" style='border: 1px solid #cfcfcf'>
                          <option value ="">%s</option>
                          <option value ="overdue_letter">%s</option>
                          <option value ="reminder">%s</option>
                          <option value ="notification">%s</option>
                          <option value ="claim_return">%s</option>
                     </select>
                     <br />
                     <br />
                     <input type="submit" name="load_template" value='%s' class="formbutton">
                </td>
                </tr>
         </table>
         """ % (_("Templates"),
                _("Overdue letter"),
                _("Reminder"),
                _("Notification"),
                _("Send recall"),
                _("Load"))
 
 
         out += """
         <br /> <br />
         <table class="bibcirctable">
                <tr>
                     <td>
                        <input type=button value="%s" onClick="history.go(-1)" class="formbutton">
                        <input type="reset" name="reset_button" value="%s" class="formbutton">
                        <input type="submit" name="send_message" value="%s" class="formbutton">
                     </td>
                </tr>
         </table>
         <br /> <br />
         </div>
         </form>
         """ % (_("Back"),
                _("Reset"),
                _("Send"))
 
 
         return out
 
     def tmpl_get_item_loans_details(self, result, recid, infos,
                                     ln=CFG_SITE_LANG):
         """
         @param ln: language of the page
         """
         _ = gettext_set_language(ln)
 
         out = self.tmpl_infobox(infos, ln)
 
         out += load_menu(ln)
 
         if len(result) == 0:
             out += """
             <div class="bibcircbottom">
             <br />
             <div class="bibcircinfoboxmsg">%s</div>
             <br />
             """ % (_("There are no loans."))
 
         else:
             out += """
             <div class="bibcircbottom">
             <style type="text/css"> @import url("/img/tablesorter.css"); </style>
             <script src="/js/jquery/jquery.js" type="text/javascript"></script>
             <script src="/js/jquery/jquery.tablesorter.js" type="text/javascript"></script>
             <script type="text/javascript">
             $(document).ready(function() {
               $('#table_loans').tablesorter({widthFixed: true, widgets: ['zebra']})
             });
             </script>
             <br />
             <form name="borrower_form"
                   action="%s/admin2/bibcirculation/get_item_loans_details" method="get" >
             <input type=hidden name=recid value="%s">
             """ % (CFG_SITE_URL,
                    recid)
 
             out += """
              <br />
              <table id="table_loans" class="tablesorter" border="0"
                                      cellpadding="0" cellspacing="1">
                <thead>
                     <tr>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                     </tr>
                 </thead>
                 <tbody>
                 """% (_("Borrower"),
                       _("Barcode"),
                       _("Loaned on"),
                       _("Due date"),
                       _("Renewals"),
                       _("Overdue letter"),
                       _("Loan status"),
                       _("Loan notes"),
                       _("Loan options"))
 
 
             for (borrower_id, borrower_name, barcode, loaned_on,
                  due_date, nb_renewall, nb_overdue, date_overdue,
                  status, notes, loan_id) in result:
 
                 borrower_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_borrower_details',
                                 {'borrower_id': borrower_id, 'ln': ln},
                                 (borrower_name))
 
                 no_notes_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_loans_notes',
                                 {'loan_id': loan_id, 'ln': ln}, (_("No notes")))
 
                 see_notes_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_loans_notes',
                                {'loan_id': loan_id, 'ln': ln}, (_("See notes")))
 
                 if notes == "":
                     check_notes = no_notes_link
                 else:
                     check_notes = see_notes_link
 
                 out += """
             <tr>
                  <td>%s</td>
                  <td>%s</td>
                  <td>%s</td>
                  <td>%s</td>
                  <td>%s</td>
                  <td>%s - %s</td>
                  <td>%s</td>
                  <td>%s</td>
                  """ % (borrower_link, barcode, loaned_on, due_date,
                         nb_renewall, nb_overdue, date_overdue,
                         status, check_notes)
 
                 out += """
                  <td align="center">
                    <SELECT style='border: 1px solid #cfcfcf'
                         ONCHANGE="location = this.options[this.selectedIndex].value;">
                       <OPTION VALUE="">%s
                       <OPTION VALUE="get_item_loans_details?barcode=%s&loan_id=%s&recid=%s">%s
                       <OPTION VALUE="loan_return_confirm?barcode=%s">%s
                 """ % (_("Select an action"),
                        barcode, loan_id, recid, _("Renew"),
                        barcode, _("Return"))
 
                 if status == CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED:
                     out += """
                       <OPTION VALUE="change_due_date_step1?barcode=%s" DISABLED>%s
                       """ % (barcode, _("Change due date"))
                 else:
                     out += """
                       <OPTION VALUE="change_due_date_step1?barcode=%s">%s
                       """ % (barcode, _("Change due date"))
 
                 out += """
     <OPTION VALUE="claim_book_return?borrower_id=%s&recid=%s&loan_id=%s&template=claim_return">%s
                     </SELECT>
                  </td>
              </tr>
              <input type=hidden name=loan_id value="%s">
              """ % (borrower_id, recid, loan_id, _("Send recall"),
                     loan_id)
 
         out += """
         <tbody>
         </table>
         <br />
         <table class="bibcirctable">
             <tr>
                 <td>
                     <input type=button
                onClick="location.href='%s/admin2/bibcirculation/get_item_details?ln=%s&recid=%s'"
                     value='%s'
                     class='formbutton'>
                 </td>
             </tr>
         </table>
         <br />
         <br />
         <br />
         </div>
         </form>
         """ % (CFG_SITE_URL, ln,
                recid,
                _("Back"))
 
         return out
 
     def tmpl_associate_barcode(self, request_id, recid, borrower,
                                infos, ln=CFG_SITE_LANG):
 
 
         _ = gettext_set_language(ln)
 
 
         (book_title, _book_year, _book_author,
          book_isbn, _book_editor) = book_information_from_MARC(recid)
 
         if book_isbn:
             book_cover = get_book_cover(book_isbn)
         else:
             book_cover = "%s/img/book_cover_placeholder.gif" % (CFG_SITE_URL)
 
 
         out = self.tmpl_infobox(infos, ln)
 
         out += load_menu(ln)
 
         (borrower_id, ccid, name, email, phone, address, mailbox) = borrower
 
         display_id = borrower_id
         id_string = _("ID")
         if CFG_CERN_SITE == 1:
             display_id = ccid
             id_string = _("CCID")
 
 
         out += """
             <style type="text/css"> @import url("/img/tablesorter.css"); </style>
             <form name="return_form" action="%s/admin2/bibcirculation/register_new_loan"
                   method="post" >
             <div class="bibcircbottom">
             <input type=hidden name=borrower_id value="%s">
             <input type=hidden name=request_id value="%s">
             <br />
             <table class="bibcirctable">
                 <tr>
                     <td class="bibcirctableheader">%s</td>
                 </tr>
             </table>
             </form>
             <table class="tablesorterborrower" border="0" cellpadding="0" cellspacing="1">
               <tr>
                 <th width="100">%s</th>
                 <td>%s</td>
               </tr>
               <tr>
                 <th width="100">%s</th>
                 <td>%s</td>
               </tr>
               <tr>
                 <th width="100">%s</th>
                 <td>%s</td>
               </tr>
               <tr>
                 <th width="100">%s</th>
                 <td>%s</td>
               </tr>
               <tr>
                 <th width="100">%s</th>
                 <td>%s</td>
               </tr>
               <tr>
                 <th width="100">%s</th>
                 <td>%s</td>
                </tr>
             </table>
             """% (CFG_SITE_URL,
                   borrower_id,
                   request_id,
                   _("Personal details"),
                   id_string, display_id,
                   _("Name"), name,
                   _("Address"), address,
                   _("Mailbox"), mailbox,
                   _("Email"), email,
                   _("Phone"), phone)
 
         out += """
         <br />
         <table class="tablesorterborrower" border="0" cellpadding="0" cellspacing="1">
             <tr>
                 <th>%s</th>
             </tr>
             <tr>
                 <td>%s</td>
             </tr>
             <tr algin='center'>
                 <td>
                     <img style='border: 1px solid #cfcfcf' src="%s" alt="Book Cover"/>
                 </td>
             </tr>
             <tr>
                 <th>%s</th>
             </tr>
             <tr>
                 <td>
                     <input type="text" size="66" name="barcode"
                            style='border: 1px solid #cfcfcf'>
                 </td>
             </tr>
         </table>
 
         """ % (_("Item"),
                book_title,
                str(book_cover),
                _("Barcode"))
 
         out += """
               <br />
               <table class="tablesorterborrower" border="0" cellpadding="0" cellspacing="1">
                 <tr>
                   <th>%s</th>
                 </tr>
                 <tr>
                   <td>
                     <textarea name='new_note' rows="4" cols="57"
                               style='border: 1px solid #cfcfcf'></textarea>
                   </td>
                 </tr>
               </table>
               <br />
               """ % (_("Write notes"))
 
         out += """
         <table class="bibcirctable">
           <tr>
             <td>
               <input type=button value="%s" onClick="history.go(-1)" class="bibcircbutton"
                 onmouseover="this.className='bibcircbuttonover'"
                 onmouseout="this.className='bibcircbutton'">
               <input type="submit" value="%s" class="bibcircbutton"
                 onmouseover="this.className='bibcircbuttonover'"
                 onmouseout="this.className='bibcircbutton'">
             </td>
           </tr>
         </table>
         <br />
         <br />
         <br />
         </div>
         </form>
         """ % (_("Back"),
                _("Confirm"))
 
         return out
 
     def tmpl_borrower_notes(self, borrower_notes, borrower_id,
                             ln=CFG_SITE_LANG):
 
         _ = gettext_set_language(ln)
 
         if not borrower_notes:
             borrower_notes = {}
         else:
             borrower_notes = eval(borrower_notes)
 
         out = """ """
 
         out += load_menu(ln)
 
         out += """
             <div class="bibcircbottom">
             <form name="borrower_notes"
                   action="%s/admin2/bibcirculation/get_borrower_notes"
                   method="post" >
             <input type=hidden name=borrower_id value='%s'>
             <br />
             <br />
             <table class="bibcirctable">
               <tr>
                 <td class="bibcirctableheader">%s</td>
               </tr>
             </table>
             <table class="bibcirctable">
               <tr>
                 <td>
                   <table class="bibcircnotes">
 
             """ % (CFG_SITE_URL, borrower_id,
                    _("Notes about borrower"))
 
         key_array = borrower_notes.keys()
         key_array.sort()
 
         for key in key_array:
             delete_note = create_html_link(CFG_SITE_URL +
                             '/admin2/bibcirculation/get_borrower_notes',
                             {'delete_key': key, 'borrower_id': borrower_id,
                              'ln': ln}, (_("[delete]")))
 
             out += """<tr class="bibcirccontent">
                         <td class="bibcircnotes" width="160"
                             valign="top" align="center"><b>%s</b></td>
                         <td width="400"><i>%s</i></td>
                         <td width="65" align="center">%s</td>
                       </tr>
 
                       """ % (key, borrower_notes[key], delete_note)
 
         out += """
                   </table>
                 </td>
               </tr>
             </table>
             <br />
             <table class="bibcirctable">
               <tr>
                 <td class="bibcirctableheader">%s</td>
               </tr>
             </table>
             <table class="bibcirctable">
               <tr>
                 <td class="bibcirccontent">
                   <textarea name="library_notes" rows="5" cols="90"
                             style='border: 1px solid #cfcfcf'></textarea>
                 </td>
               </tr>
             </table>
             <br />
             <table class="bibcirctable">
               <tr>
                 <td>
                   <input type=button
     onClick="location.href='%s/admin2/bibcirculation/get_borrower_details?ln=%s&borrower_id=%s'"
                   value="%s" class='formbutton'>
                   <input type="submit" value='%s' class="formbutton">
                 </td>
               </tr>
              </table>
              <br />
              <br />
              <br />
              </form>
              </div>
         """ % (_("Write new note"),
                CFG_SITE_URL, ln,
                borrower_id,
                _("Back"),
                _("Confirm"))
 
         return out
 
     def tmpl_get_loans_notes(self, loans_notes, loan_id,
                              referer, back="", ln=CFG_SITE_LANG):
 
         _ = gettext_set_language(ln)
 
         if back == "":
             back = referer
 
         if not loans_notes:
             loans_notes = {}
         else:
             loans_notes = eval(loans_notes)
 
         out = """ """
 
         out += load_menu(ln)
 
         out += """
             <div class="bibcircbottom">
             <form name="loans_notes"
                   action="%s/admin2/bibcirculation/get_loans_notes"
                   method="get" >
             <input type="hidden" name="loan_id" value="%s">
             <br />
             <br />
             <table class="bibcirctable">
               <tr>
                 <td class="bibcirctableheader">%s</td>
               </tr>
             </table>
             <table class="bibcirctable">
               <tr>
                 <td>
                   <table class="bibcircnotes">
             """ % (CFG_SITE_URL, loan_id,
                    _("Notes about loan"))
 
         key_array = loans_notes.keys()
         key_array.sort()
 
         for key in key_array:
             delete_note = create_html_link(CFG_SITE_URL +
                             '/admin2/bibcirculation/get_loans_notes',
                             {'delete_key': key, 'loan_id': loan_id, 'ln': ln,
                             'back': cgi.escape(back, True)}, (_("[delete]")))
 
             out += """<tr class="bibcirccontent">
                         <td class="bibcircnotes" width="160" valign="top"
                             align="center"><b>%s</b></td>
                         <td width="400"><i>%s</i></td>
                         <td width="65" align="center">%s</td>
                       </tr>
                       """ % (key, loans_notes[key], delete_note)
 
         out += """
                   </table>
                 </td>
               </tr>
             </table>
             <br />
             <table class="bibcirctable">
               <tr>
                 <td class="bibcirctableheader">%s</td>
               </tr>
             </table>
             <table class="bibcirctable">
               <tr>
                 <td class="bibcirccontent">
                   <textarea name="library_notes" rows="5" cols="90"
                             style='border: 1px solid #cfcfcf'></textarea>
                 </td>
               </tr>
             </table>
             <br />
             <table class="bibcirctable">
               <tr>
                   <td>
                     <input type=button
                            value="%s"
                            onClick="window.location='%s'"
                            class="formbutton">
                     <input type="submit" value="%s" class="formbutton">
                     <input type="hidden" name="back" value="%s">
                   </td>
              </tr>
              </table>
              <br />
              <br />
              <br />
              </form>
              </div>
         """ % (_("Write new note"),
                _("Back"),
                cgi.escape(back, True),
                _("Confirm"),
                cgi.escape(back, True))
 
         return out
 
     def tmpl_new_item(self, book_info=None, errors=None, ln=CFG_SITE_LANG):
         """
         No more in use.
         """
 
         _ = gettext_set_language(ln)
 
         out = """ """
 
         out += load_menu(ln)
 
         if book_info:
             out += """
               <div class="bibcircbottom">
                 <br />
                 <table class="bibcirctable">
                 <tr>
                 <td class="bibcirctableheader" width="10">%s</td>
                 </tr>
                 </table>
                 <table class="bibcirctable">
                     <tr>
                     <td width="110" valign="top">%s</td>
                     <td class="bibcirccontent">
                         <textarea style='border: 1px solid #cfcfcf'
                                   rows="3" cols="43" name="title">%s</textarea>
                     </td>
                     </tr>
                     <tr>
                     <td width="110"></td>
                     <td class="bibcirccontent"></td>
                     </tr>
                     <tr>
                     <td width="110"></td>
                     <td class="bibcirccontent">
                         <img style='border: 1px solid #cfcfcf' src="%s" alt="Book Cover"/>
                     </td>
                     </tr>
                     <tr>
                     <td width="110"></td>
                     <td class="bibcirccontent"></td>
                     </tr>
                     <tr>
                     <td width="110">%s</td>
                     <td class="bibcirccontent">
                        <input type="text" style='border: 1px solid #cfcfcf'
                               size=45 value="%s" name="author">
                     </td>
                     </tr>
                     <tr>
                     <td width="110">%s</td>
                     <td class="bibcirccontent">
                        <input type="text" style='border: 1px solid #cfcfcf'
                               size=45 value="%s" name="ean">
                     </td>
                     </tr>
                     <tr>
                     <td width="110">%s</td>
                     <td class="bibcirccontent">
                        <input type="text" style='border: 1px solid #cfcfcf'
                               size=45 value="%s" name="isbn">
                     </td>
                     </tr>
                     <tr>
                     <td width="110">%s</td>
                     <td class="bibcirccontent">
                        <input type="text" size=45 style='border: 1px solid #cfcfcf'
                               value="%s" name="publisher">
                     </td>
                     </tr>
                     <tr>
                     <td width="110">%s</td>
                     <td class="bibcirccontent">
                        <input type="text" size=45 style='border: 1px solid #cfcfcf'
                               value="%s" name="pub_date">
                     </td>
                     </tr>
                     <tr>
                     <td width="110">%s</td>
                     <td class="bibcirccontent">
                        <input type="text" style='border: 1px solid #cfcfcf'
                               size=45 value="" name="pub_place">
                     </td>
                     </tr>
                     <tr>
                     <td width="110">%s</td>
                     <td class="bibcirccontent">
                        <input type="text" style='border: 1px solid #cfcfcf'
                               size=45 value="%s" name="edition">
                     </td>
                     </tr>
                     <tr>
                     <td width="110">%s</td>
                     <td class="bibcirccontent">
                        <input type="text" style='border: 1px solid #cfcfcf'
                               size=45 value="%s" name="nb_pages">
                     </td>
                     </tr>
                     <tr>
                     <td width="110">%s</td>
                     <td class="bibcirccontent">
                        <input type="text" style='border: 1px solid #cfcfcf'
                               size=45 value="%s" name="sub_library">
                     </td>
                     </tr>
                     <tr>
                     <td width="110">%s</td>
                     <td class="bibcirccontent">
                        <input type="text" style='border: 1px solid #cfcfcf'
                               size=45 value="" name="location">
                     </td>
                     </tr>
                      """ % (_("Book Information"),
                             _("Title"), book_info[6],
                             book_info[8],
                             _("Author"), book_info[0],
                             _("EAN"), book_info[1],
                             _("ISBN"), book_info[2],
                             _("Publisher"), book_info[3],
                             _("Publication date"), book_info[5],
                             _("Publication place"),
                             _("Edition"), book_info[7],
                             _("Number of pages"), book_info[4],
                             _("Sub-library"),
                             _("CERN Central Library"),
                             _("Location"))
 
             out += """
                     <tr>
                         <td width="110">%s</td>
                         <td class="bibcirccontent">
                             <select name="loan_period"  style='border: 1px solid #cfcfcf'>
                 """ % (_("Loan period"))
 
             for loan_period in CFG_BIBCIRCULATION_ITEM_LOAN_PERIOD:
                 out += """
                                 <option value="%s">%s</option>
                            """ % (loan_period, loan_period)
 
             out += """
                             </select>
                         </td>
                     </tr>
                 """
 
             out += """
                     <tr>
                         <td width="110">%s</td>
                         <td class="bibcirccontent">
                             <input type="text" style='border: 1px solid #cfcfcf'
                               size=45 value="" name="barcode">
                         </td>
                     </tr>
                     <tr>
                         <td width="110">%s</td>
                         <td class="bibcirccontent">
                             <input type="text" style='border: 1px solid #cfcfcf'
                               size=45 value="" name="collection">
                         </td>
                     </tr>
                     <tr>
                         <td width="110">%s</td>
                         <td class="bibcirccontent">
                             <input type="text" style='border: 1px solid #cfcfcf'
                               size=45 value="" name="description">
                         </td>
                     </tr>
                 </table>
            <br />
            <br />
            """ % (_("Barcode"),
                   _("Collection"),
                   _("Description"))
 
 
         elif errors:
             out += """
             <div class="bibcircbottom">
                 <form name="list_form" action="%s/admin2/bibcirculation/new_item" method="get">
                     <br />
                     <br />
                     <br />
                     <table class="bibcirctable_contents">
                         <tr align="center">
                             <td>ERROR: %s. %s</td>
                         </tr>
                     </table>
                     <br />
                     <br />
                     <br />
                     <br />
                 </form>
             </div>
             """ % (CFG_SITE_URL, errors[0], errors[1])
                 # The errors are not translated because they come from Amazon
                 # and they will allways be in English
         else:
             out += """
             <div class="bibcircbottom">
             <form name="list_form" action="%s/admin2/bibcirculation/new_item" method="get" >
             <br />
             <br />
             <br />
             <table class="bibcirctable_contents">
             <tr align="center">
             <td class="bibcirctableheader">'%s'
               <input type="text" style='border: 1px solid #cfcfcf' size=25  name="isbn">
             </td>
             </tr>
             </table>
             <br />
             <table class="bibcirctable_contents">
             <tr align="center">
             <td><input type="submit" value="%s" class="formbutton"></td>
             </tr>
             </table>
             <br />
             <br />
             <br />
             </form>
             </div>
             """ % (CFG_SITE_URL, _("ISBN"), _("Retrieve book information"))
 
         return out
 
     def tmpl_add_new_borrower_step1(self, tup_infos=None, infos=None, ln=CFG_SITE_LANG):
 
         _ = gettext_set_language(ln)
 
         if tup_infos:
             (name, email, phone, address, mailbox, notes) = tup_infos
         else:
             (name, email, phone, address, mailbox, notes) = ('', '', '', '', '', '')
 
         out = ''
 
         if infos:
             out += self.tmpl_infobox(infos, ln)
 
         out += load_menu(ln)
 
         out += """
             <div class="bibcircbottom">
             <form name="add_new_borrower_step1_form"
                   action="%s/admin2/bibcirculation/add_new_borrower_step2"
                   method="get">
               <br />
               <br />
               <table class="bibcirctable">
                 <tr>
                     <td width="70">%s</td>
                     <td class="bibcirccontent">
                       <input type="text" style='border: 1px solid #cfcfcf'
                              size=45 name="name" value="%s">
                     </td>
                 </tr>
                 <tr>
                     <td width="70">%s</td>
                     <td class="bibcirccontent">
                       <input type="text" style='border: 1px solid #cfcfcf'
                              size=45 name="email" value="%s">
                     </td>
                 </tr>
                 <tr>
                     <td width="70">%s</td>
                     <td class="bibcirccontent">
                       <input type="text" style='border: 1px solid #cfcfcf'
                              size=45 name="phone" value="%s">
                     </td>
                 </tr>
                 <tr>
                     <td width="70">%s</td>
                     <td class="bibcirccontent">
                       <input type="text" style='border: 1px solid #cfcfcf'
                              size=45 name="address" value="%s">
                     </td>
                  </tr>
                   <tr>
                     <td width="70">%s</td>
                     <td class="bibcirccontent">
                       <input type="text" style='border: 1px solid #cfcfcf'
                              size=45 name="mailbox" value="%s">
                     </td>
                  </tr>
                  <tr>
                     <td width="70" valign="top">%s</td>
                     <td class="bibcirccontent">
                         <textarea name="notes" rows="5" cols="39"
                                 style='border: 1px solid #cfcfcf'>%s</textarea>
                     </td>
                  </tr>
                 </table>
                 <br />
                 <table class="bibcirctable">
                 <tr>
                   <td>
                        <input type=button value="%s" class="formbutton"
                               onClick="history.go(-1)">
                        <input type="submit" value="%s" class="formbutton">
                   </td>
                  </tr>
                 </table>
                 <br />
                 <br />
                 </form>
                 </div>
                 """ % (CFG_SITE_URL,
                        _("Name"), name,
                        _("Email"), email,
                        _("Phone"), phone,
                        _("Address"), address,
                        _("Mailbox"), mailbox,
                        _("Notes"), notes,
                        _("Back"), _("Continue"))
 
         return out
 
     def tmpl_add_new_borrower_step2(self, tup_infos, infos, ln=CFG_SITE_LANG):
 
         _ = gettext_set_language(ln)
 
         (name, email, phone, address, mailbox, notes) = tup_infos
 
         out = self.tmpl_infobox(infos, ln)
 
         out += load_menu(ln)
 
         out += """
             <div class="bibcircbottom">
             <form name="add_new_borrower_step2_form"
                   action="%s/admin2/bibcirculation/add_new_borrower_step3"
                   method="post" >
               <br />
               <br />
               <table class="bibcirctable">
                 <tr>
                     <td width="70">%s</td> <td class="bibcirccontent">%s</td>
                 </tr>
                 <tr>
                     <td width="70">%s</td> <td class="bibcirccontent">%s</td>
                 </tr>
                 <tr>
                     <td width="70">%s</td> <td class="bibcirccontent">%s</td>
                 </tr>
                 <tr>
                     <td width="70">%s</td> <td class="bibcirccontent">%s</td>
                  </tr>
                  <tr>
                     <td width="70">%s</td> <td class="bibcirccontent">%s</td>
                  </tr>
                  <tr>
                     <td width="70">%s</td> <td class="bibcirccontent">%s</td>
                  </tr>
                 </table>
 
                 """ % (CFG_SITE_URL,
                        _("Name"), name,
                        _("Email"), email,
                        _("Phone"), phone,
                        _("Address"), address,
                        _("Mailbox"), mailbox,
                        _("Notes"), notes)
 
 
         if infos:
             out += """
                     <br />
                     <table class="bibcirctable">
                       <tr>
                         <td>
                          <input type=button value="%s"
                                 onClick="history.go(-1)"
                                 class="formbutton">
                        </td>
                      </tr>
                     </table>
                     <br />
                     <br />
                     </form>
                     </div>
                 """ % (_("Back"))
 
         else:
             out += """
                     <br />
                     <table class="bibcirctable">
                       <tr>
                         <td>
                          <input type=button value="%s"
                                 onClick="history.go(-1)"
                                 class="formbutton">
                          <input type="submit" value="%s" class="formbutton">
                          <input type=hidden name=tup_infos value="%s">
                        </td>
                      </tr>
                    </table>
                    <br />
                    <br />
                    </form>
                    </div>
                    """ % (_("Back"), _("Continue"), tup_infos)
 
         return out
 
     def tmpl_add_new_borrower_step3(self, ln=CFG_SITE_LANG):
 
         _ = gettext_set_language(ln)
 
         out = """ """
 
         out += load_menu(ln)
 
         out += """
             <div class="bibcircbottom">
               <br />
               <br />
               <table class="bibcirctable">
                 <tr>
                     <td class="bibcirccontent">%s</td>
                 </tr>
                 </table>
                 <br />
                 <table class="bibcirctable">
                 <tr>
                   <td>
                        <input type=button value="%s"
                     onClick="location.href='%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s'"
                             class="formbutton">
                   </td>
                  </tr>
                 </table>
                 <br />
                 <br />
                 </div>
                 """ % (_("A new borrower has been registered."),
                        _("Back to home"),
                        CFG_SITE_URL, ln)
 
         return out
 
     #def tmpl_update_borrower_info_step1(self, ln=CFG_SITE_LANG):
     #    """
     #    Template for the admin interface. Search borrower.
     #
     #    @param ln: language
     #    """
     #    _ = gettext_set_language(ln)
     #
     #    out = load_menu(ln)
     #
     #    if CFG_CERN_SITE == 1:
     #        id_string = 'ccid'
     #    else:
     #        id_string = _('id')
     #
     #    out += """
     #    <div class="bibcircbottom">
     #    <br />
     #    <br />
     #    <br />
     #    <form name="update_borrower_info_step1_form"
     #          action="%s/admin2/bibcirculation/update_borrower_info_step2"
     #          method="get" >
     #        <table class="bibcirctable">
     #            <tr align="center">
     #                <td class="bibcirctableheader">%s
     #                    <input type="radio" name="column" value="id">%s
     #                    <input type="radio" name="column" value="name" checked>%s
     #                    <input type="radio" name="column" value="email">%s
     #                    <br>
     #                    <br>
     #                </td>
     #            </tr>
     #        """ % (CFG_SITE_URL, _("Search borrower by"), id_string,
     #               _("name"), _("email"))
     #
     #    out += """
     #            <tr align="center">
     #                <td>
     #                    <input type="text" size="45" name="string"
     #                           style='border: 1px solid #cfcfcf'>
     #                </td>
     #            </tr>
     #        </table>
     #    <br />
     #    <table class="bibcirctable">
     #        <tr align="center">
     #            <td>
     #                <input type=button value="%s" onClick="history.go(-1)"
     #                       class="formbutton">
     #                <input type="submit" value="%s" class="formbutton">
     #            </td>
     #        </tr>
     #    </table>
     #    <form>
     #    <br />
     #    <br />
     #    <br />
     #    <br />
     #    </div>
     #
     #    """ % (_("Back"), _("Search"))
     #
     #    return out
     #
     #def tmpl_update_borrower_info_step2(self, result, ln=CFG_SITE_LANG):
     #    """
     #    @param result: search result
     #    @param ln: language
     #    """
     #
     #    _ = gettext_set_language(ln)
     #
     #    out = """ """
     #
     #    out += load_menu(ln)
     #
     #    out += """
     #    <div class="bibcircbottom">
     #    <br />
     #    <table class="bibcirctable">
     #        <tr align="center">
     #            <td class="bibcirccontent">%s</td>
     #        </tr>
     #    </table>
     #    <br />
     #    <table class="bibcirctable">
     #    """ % (_("%i borrowers found") % len(result))
     #
     #    for (borrower_id, name) in result:
     #        borrower_link = create_html_link(CFG_SITE_URL +
     #                        '/admin2/bibcirculation/update_borrower_info_step1',
     #                        {'borrower_id': borrower_id, 'ln': ln}, (name))
     #
     #        out += """
     #        <tr align="center">
     #             <td class="bibcirccontent" width="70">%s
     #             <input type=hidden name=uid value="%s"></td>
     #        </tr>
     #        """ % (borrower_link, borrower_id)
     #
     #
     #    out += """
     #         </table>
     #         <br />
     #         """
     #
     #    out += """
     #    <table class="bibcirctable">
     #        <tr align="center">
     #            <td>
     #                <input type=button
     #                       value='%s'
     #                       onClick="history.go(-1)"
     #                       class="formbutton">
     #            </td>
     #        </tr>
     #    </table>
     #    <br />
     #    <br />
     #    <br />
     #    </form>
     #    </div>
     #    """ % (_("Back"))
     #
     #    return out
 
     def tmpl_update_borrower_info_step1(self, tup_infos, infos=None,
                                         ln=CFG_SITE_LANG):
 
         _ = gettext_set_language(ln)
 
         (borrower_id, name, email, phone, address, mailbox) = tup_infos
 
         display_id = borrower_id
         id_string = _("ID")
 
         out = ''
 
         if infos:
             out += self.tmpl_infobox(infos, ln)
 
         out += load_menu(ln)
 
         out += """
             <div class="bibcircbottom">
             <form name="update_borrower_info_step1_form"
                   action="%s/admin2/bibcirculation/update_borrower_info_step2"
                   method="get" >
               <br />
               <br />
               <table class="bibcirctable">
                 <tr>
                     <td class="bibcirctableheader">%s</td>
                 </tr>
               </table>
               <table class="bibcirctable">
                 <tr>
                     <td width="70">%s</td>
                     <td class="bibcirccontent">%s</td>
                 </tr>
                 <tr>
                     <td width="70">%s</td>
                     <td class="bibcirccontent">
                         <input type="text" style='border: 1px solid #cfcfcf'
                                 size=45 name="name" value="%s">
                     </td>
                 </tr>
                 <tr>
                     <td width="70">%s</td>
                     <td class="bibcirccontent">
                         <input type="text" style='border: 1px solid #cfcfcf'
                                 size=45 name="address" value="%s">
                     </td>
                  </tr>
                  <tr>
                     <td width="70">%s</td>
                     <td class="bibcirccontent">
                         <input type="text" style='border: 1px solid #cfcfcf'
                                 size=45 name="mailbox" value="%s">
                     </td>
                  </tr>
                 <tr>
                     <td width="70">%s</td>
                     <td class="bibcirccontent">
                         <input type="text" style='border: 1px solid #cfcfcf'
                                 size=45 name="email" value="%s">
                     </td>
                 </tr>
                 <tr>
                     <td width="70">%s</td>
                     <td class="bibcirccontent">
                         <input type="text" style='border: 1px solid #cfcfcf'
                                 size=45 name="phone" value="%s">
                         <input type=hidden name=borrower_id value="%s">
                     </td>
                 </tr>
 
                 </table>
                 <br />
                 <table class="bibcirctable">
                 <tr>
                     <td>
                         <input type=button value="%s" onClick="history.go(-1)"
                                class="formbutton">
                         <input type="submit" value='%s' class="formbutton">
                     </td>
                 </tr>
                 </table>
                 <br />
                 <br />
                 </form>
                 </div>
                 """ % (CFG_SITE_URL, _("Borrower information"),
                        id_string, display_id,
                        _("Name"), name,
                        _("Address"), address,
                        _("Mailbox"), mailbox,
                        _("Email"), email,
                        _("Phone"), phone,
                        borrower_id,
                        _("Back"), _("Continue"))
 
 
         return out
 
     def tmpl_add_new_library_step1(self, ln=CFG_SITE_LANG):
 
         _ = gettext_set_language(ln)
 
         out = load_menu(ln)
 
         out += """
             <style type="text/css"> @import url("/img/tablesorter.css"); </style>
             <div class="bibcircbottom" align="center">
             <form name="add_new_library_step1_form"
                   action="%s/admin2/bibcirculation/add_new_library_step2" method="get" >
               <br />
               <br />
                <table class="bibcirctable">
                 <tr align="center">
                      <td class="bibcirctableheader">%s</td>
                 </tr>
               </table>
               <table class="tablesorterborrower" border="0" cellpadding="0" cellspacing="1">
                 <tr>
                     <th width="70">%s</th>
                     <td>
                       <input type="text" style='border: 1px solid #cfcfcf'
                              size=50 name="name" id='name'>
                       <script language="javascript" type="text/javascript">
                             document.getElementById("name").focus();
                       </script>
                     </td>
                 </tr>
                 <tr>
                     <th width="70">%s</th>
                     <td>
                       <input type="text" style='border: 1px solid #cfcfcf' size=50 name="email">
                     </td>
                 </tr>
                 <tr>
                     <th width="70">%s</th>
                     <td>
                       <input type="text" style='border: 1px solid #cfcfcf' size=50 name="phone">
                     </td>
                 </tr>
                 <tr>
                     <th width="70">%s</th>
                     <td>
                       <input type="text" style='border: 1px solid #cfcfcf' size=50
                              name="address">
                     </td>
                  </tr>
                  <tr>
                     <th width="70">%s</th>
                     <td>
                     <select name="type"  style='border: 1px solid #cfcfcf'>
             """ % (CFG_SITE_URL, _("New library information"), _("Name"),
                      _("Email"), _("Phone"), _("Address"), _("Type"))
 
         for lib in CFG_BIBCIRCULATION_LIBRARY_TYPE:
             out += """
                         <option value="%s">%s</option>
                    """ % (lib, lib)
 
         out += """
                       </select>
                     </td>
                  </tr>
                  <tr>
                     <th width="70" valign="top">%s</th>
                     <td>
                       <textarea name="notes" rows="5" cols="39"
                                 style='border: 1px solid #cfcfcf'></textarea>
                     </td>
                  </tr>
                 </table>
                 <br />
                 <table class="bibcirctable">
                 <tr align="center">
                   <td>
                        <input type=button value="%s" onClick="history.go(-1)" class="formbutton">
                        <input type="submit"   value="%s" class="formbutton">
                   </td>
                  </tr>
                 </table>
                 <br />
                 <br />
                 </form>
                 </div>
                 """ % (_("Notes"), _("Back"), _("Continue"))
 
         return out
 
     def tmpl_add_new_library_step2(self, tup_infos, ln=CFG_SITE_LANG):
 
         _ = gettext_set_language(ln)
 
         (name, email, phone, address, lib_type, notes) = tup_infos
 
         out = """ """
 
         out += load_menu(ln)
 
         out += """
             <div class="bibcircbottom">
             <form name="add_new_library_step2_form"
                   action="%s/admin2/bibcirculation/add_new_library_step3" method="get" >
               <br />
               <br />
                <table class="bibcirctable">
                 <tr>
                      <td class="bibcirctableheader">%s</td>
                 </tr>
               </table>
               <table class="bibcirctable">
                 <tr>
                     <td width="70">%s</td> <td class="bibcirccontent">%s</td>
                 </tr>
                 <tr>
                     <td width="70">%s</td> <td class="bibcirccontent">%s</td>
                 </tr>
                 <tr>
                     <td width="70">%s</td> <td class="bibcirccontent">%s</td>
                 </tr>
                 <tr>
                     <td width="70">%s</td> <td class="bibcirccontent">%s</td>
                 </tr>
                 <tr>
                     <td width="70">%s</td> <td class="bibcirccontent">%s</td>
                 </tr>
                 <tr>
                     <td width="70">%s</td> <td class="bibcirccontent">%s</td>
                 </tr>
                 </table>
                 <br />
                 <table class="bibcirctable">
                 <tr>
                     <td>
                         <input type=button
                                value="%s"
                                onClick="history.go(-1)"
                                class="formbutton">
                         <input type="submit"
                                value="%s"
                                class="formbutton">
                         <input type=hidden name=name     value="%s">
                         <input type=hidden name=email    value="%s">
                         <input type=hidden name=phone    value="%s">
                         <input type=hidden name=address  value="%s">
                         <input type=hidden name=lib_type value="%s">
                         <input type=hidden name=notes    value="%s">
                     </td>
                 </tr>
                 </table>
                 <br />
                 <br />
                 </form>
                 </div>
                 """ % (CFG_SITE_URL, _("New library information"),
                        _("Name"), name,
                        _("Email"), email,
                        _("Phone"), phone,
                        _("Address"), address,
                        _("Type"), lib_type,
                        _("Notes"), notes,
                        _("Back"), _("Confirm"),
                       name, email, phone, address, lib_type, notes)
                        #tup_infos)
 
         return out
 
     def tmpl_add_new_library_step3(self, ln=CFG_SITE_LANG):
 
         _ = gettext_set_language(ln)
 
         out = load_menu(ln)
 
         out += """
             <div class="bibcircbottom">
               <br />
               <br />
               <table class="bibcirctable">
                 <tr>
                     <td class="bibcirccontent">%s</td>
                 </tr>
                 </table>
                 <br />
                 <table class="bibcirctable">
                 <tr>
                   <td>
                        <input type=button value='%s'
                     onClick="location.href='%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s'"
                             class="formbutton">
                   </td>
                  </tr>
                 </table>
                 <br />
                 <br />
                 </div>
                 """ % (_("A new library has been registered."),
                        _("Back to home"),
                        CFG_SITE_URL, ln)
 
         return out
 
     def tmpl_update_library_info_step1(self, infos, ln=CFG_SITE_LANG):
         """
         Template for the admin interface. Search borrower.
 
         @param ln: language
         """
         _ = gettext_set_language(ln)
 
         out = self.tmpl_infobox(infos, ln)
 
         out += load_menu(ln)
 
         out += """
         <div class="bibcircbottom">
         <br />
         <br />
         <br />
         <form name="update_library_info_step1_form"
               action="%s/admin2/bibcirculation/update_library_info_step2"
               method="get" >
             <table class="bibcirctable">
                 <tr align="center">
                     <td class="bibcirctableheader">%s
                         <input type="radio" name="column" value="name" checked>%s
                         <input type="radio" name="column" value="email">%s
                         <br>
                         <br>
                     </td>
                 </tr>
         """ % (CFG_SITE_URL,
                _("Search library by"),
                _("name"),
                _("email"))
 
         out += """
                 <tr align="center">
                     <td>
                         <input type="text" size="45" name="string" id='string'
                                style='border: 1px solid #cfcfcf'>
                         <script language="javascript" type="text/javascript">
                             document.getElementById("string").focus();
                         </script>
                     </td>
                 </tr>
             </table>
         <br />
         <table class="bibcirctable">
              <tr align="center">
                   <td>
                         <input type=button value='%s'
                          onClick="history.go(-1)" class="formbutton">
                         <input type="submit" value="%s" class="formbutton">
 
                   </td>
              </tr>
         </table>
         <form>
         <br /><br />
         <br />
         <br />
         </div>
         """ % (_("Back"), _("Search"))
 
         return out
 
     def tmpl_update_library_info_step2(self, result, ln=CFG_SITE_LANG):
         """
         @param result: search result
         @param ln: language
         """
 
         _ = gettext_set_language(ln)
 
         out = load_menu(ln)
 
         out += """
         <style type="text/css"> @import url("/img/tablesorter.css"); </style>
         <div class="bibcircbottom" align="center">
         <br />
         <table class="bibcirctable">
           <tr align="center">
             <td class="bibcirccontent">
                <strong>%s libraries found</strong>
             </td>
           </tr>
         </table>
         <br />
         <table class="tablesortersmall" border="0"
                cellpadding="0" cellspacing="1">
          <th align="center">%s</th>
 
         """ % (len(result), _("Libraries"))
 
         for (library_id, name) in result:
             library_link = create_html_link(CFG_SITE_URL +
                             '/admin2/bibcirculation/update_library_info_step3',
                             {'library_id': library_id, 'ln': ln}, (name))
 
             out += """
             <tr align="center">
                  <td class="bibcirccontent" width="70">%s
                  <input type=hidden name=library_id value="%s"></td>
             </tr>
             """ % (library_link, library_id)
 
 
         out += """
              </table>
              <br />
 
         <table class="bibcirctable">
              <tr align="center">
                   <td><input type=button value="%s"
                        onClick="history.go(-1)" class="formbutton"></td>
              </tr>
         </table>
         <br />
         <br />
         <br />
         </form>
         </div>
         """ % (_("Back"))
 
         return out
 
     def tmpl_update_library_info_step3(self, library_info, ln=CFG_SITE_LANG):
 
         _ = gettext_set_language(ln)
 
         (library_id, name, address, email, phone,
          lib_type, _notes) = library_info
 
         out = """ """
 
         out += load_menu(ln)
 
         out += """
             <style type="text/css"> @import url("/img/tablesorter.css"); </style>
             <div class="bibcircbottom" align="center">
             <form name="update_library_info_step3_form"
                   action="%s/admin2/bibcirculation/update_library_info_step4" method="get" >
                 <input type=hidden name=library_id value="%s">
                 <br />
                 <br />
                 <table class="bibcirctable">
                     <tr align="center">
                          <td class="bibcirctableheader">%s</td>
                     </tr>
                 </table>
                 <table class="tablesorterborrower" border="0" cellpadding="0" cellspacing="1">
                     <tr>
                         <th width="70">%s</th>
                         <td>
                           <input type="text" style='border: 1px solid #cfcfcf' size=50
                                  name="name" value="%s">
                         </td>
                     </tr>
                     <tr>
                         <th width="70">%s</th>
                         <td>
                           <input type="text" style='border: 1px solid #cfcfcf' size=50
                                  name="email" value="%s">
                         </td>
                     </tr>
                     <tr>
                         <th width="70">%s</th>
                         <td>
                           <input type="text" style='border: 1px solid #cfcfcf' size=50
                                  name="phone" value="%s">
                         </td>
                     </tr>
                     <tr>
                         <th width="70">%s</th>
                         <td>
                           <input type="text" style='border: 1px solid #cfcfcf' size=50
                                  name="address" value="%s">
                         </td>
                     </tr>
                     <tr>
                         <th width="70">%s</th>
                         <td>
                             <select name="lib_type"  style='border: 1px solid #cfcfcf'>
                 """ % (CFG_SITE_URL, library_id, _("Library information"),
                        _("Name"), name,
                        _("Email"), email,
                        _("Phone"), phone,
                        _("Address"), address,
                        _("Type"))
 
         for lib in CFG_BIBCIRCULATION_LIBRARY_TYPE:
             if lib == lib_type:
                 out += """
                                 <option value="%s" selected="selected">%s</option>
                        """ % (lib, lib)
             else:
                 out += """
                                 <option value="%s">%s</option>
                        """ % (lib, lib)
 
         out += """
                             </select>
                         </td>
                     </tr>
                 </table>
                 <br />
                 <table class="bibcirctable">
                 <tr align="center">
                   <td>
                        <input type=button value="%s" onClick="history.go(-1)" class="formbutton">
                        <input type="submit" value="%s" class="formbutton">
                   </td>
                 </tr>
                 </table>
                 <br />
                 <br />
                 </form>
                 </div>
                 """ % (_("Back"), _("Continue"))
 
 
         return out
 
     def tmpl_update_library_info_step4(self, tup_infos, ln=CFG_SITE_LANG):
 
         (library_id, name, email, phone, address, lib_type) = tup_infos
 
         _ = gettext_set_language(ln)
 
         out = load_menu(ln)
 
         out += """
             <style type="text/css"> @import url("/img/tablesorter.css"); </style>
             <div class="bibcircbottom" align="center">
             <form name="update_library_info_step4_form" action="%s/admin2/bibcirculation/update_library_info_step5" method="get" >
               <br />
               <br />
               <table class="bibcirctable">
                 <tr align="center">
                      <td class="bibcirctableheader">%s</td>
                 </tr>
               </table>
               <table class="tablesorterborrower" border="0" cellpadding="0" cellspacing="1">
                 <tr>
                     <th width="70">%s</th> <td>%s</td>
                 </tr>
                 <tr>
                     <th width="70">%s</th> <td>%s</td>
                 </tr>
                 <tr>
                     <th width="70">%s</th> <td>%s</td>
                 </tr>
                 <tr>
                     <th width="70">%s</th> <td>%s</td>
                 </tr>
                 <tr>
                     <th width="70">%s</th> <td>%s</td>
                 </tr>
                 </table>
                 <br />
                 <table class="bibcirctable">
                 <tr align="center">
                   <td>
                        <input type=button value="%s"
                         onClick="history.go(-1)" class="formbutton">
 
                        <input type="submit"
                        value="%s" class="formbutton">
 
                        <input type=hidden name=library_id value="%s">
                        <input type=hidden name=name value="%s">
                        <input type=hidden name=email value="%s">
                        <input type=hidden name=phone value="%s">
                        <input type=hidden name=address value="%s">
                        <input type=hidden name=lib_type value="%s">
                   </td>
                  </tr>
                 </table>
                 <br />
                 <br />
                 </form>
                 </div>
                 """ % (CFG_SITE_URL, _("Library information"),
                        _("Name"), name,
                        _("Email"), email,
                        _("Phone"), phone,
                        _("Address"), address,
                        _("Type"), lib_type,
                        _("Back"), _("Continue"),
                        library_id, name, email, phone, address, lib_type)
                        #tup_infos)
 
         return out
 
     def tmpl_update_library_info_step5(self, ln=CFG_SITE_LANG):
         """
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         out = """ """
 
         out += load_menu(ln)
 
         out += """
             <div class="bibcircbottom">
               <br />
               <br />
               <table class="bibcirctable">
                 <tr>
                     <td class="bibcirccontent">%s</td>
                 </tr>
                 </table>
                 <br />
                 <table class="bibcirctable">
                 <tr>
                   <td>
                        <input type=button value="%s"
                     onClick="location.href='%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s'"
                         class="formbutton">
                   </td>
                  </tr>
                 </table>
                 <br />
                 <br />
                 </div>
                 """ % (_("The information has been updated."),
                        _("Back to home"),
                        CFG_SITE_URL, ln)
 
         return out
 
     def tmpl_new_book_step1(self, ln=CFG_SITE_LANG):
 
         _ = gettext_set_language(ln)
 
         out = load_menu(ln)
 
         out += """
         <br />
         <br />
           <div class="bibcircbottom" align="center">
           <br />
           <br />
           <style type="text/css"> @import url("/img/tablesorter.css"); </style>
            <form name="display_ill_form" action="%s/admin2/bibcirculation/new_book_step2" method="get">
              <table class="bibcirctable">
                   <tr align="center">
                     <td class="bibcirctableheader">%s</td>
                   </tr>
                 </table>
                 <table class="tablesorterborrower" border="0" cellpadding="0" cellspacing="1">
                     <tr>
                         <th width="100">%s</th>
                         <td>
                           <input type="text" size="45" name="title" id='title'
                                  style='border: 1px solid #cfcfcf'>
                             <script language="javascript" type="text/javascript">
                                 document.getElementById("title").focus();
                             </script>
                         </td>
                     </tr>
                     <tr>
                         <th width="100">%s</th>
                         <td>
                           <input type="text" size="45" name="authors" style='border: 1px solid #cfcfcf'>
                         </td>
                     </tr>
                     <tr>
                         <th width="100">%s</th>
                         <td>
                           <input type="text" size="30" name="place" style='border: 1px solid #cfcfcf'>
                         </td>
                     </tr>
                     <tr>
                         <th width="100">%s</th>
                         <td>
                           <input type="text" size="30" name="publisher" style='border: 1px solid #cfcfcf'>
                         </td>
                     </tr>
                     <tr>
                         <th width="100">%s</th>
                         <td>
                           <input type="text" size="30" name="year" style='border: 1px solid #cfcfcf'>
                         </td>
                     </tr>
                     <tr>
                         <th width="100">%s</th>
                         <td>
                           <input type="text" size="30" name="edition" style='border: 1px solid #cfcfcf'>
                         </td>
                     </tr>
                     <tr>
                         <th width="100">%s</th>
                         <td>
                           <input type="text" size="30" name="isbn" style='border: 1px solid #cfcfcf'>
                         </td>
                     </tr>
                 </table>
 
 
            <br />
 
            """ % (CFG_SITE_URL,
                    _("Item details"),
                    _("Book title"),
                    _("Author(s)"),
                    _("Place"),
                    _("Publisher"),
                    _("Year"),
                    _("Edition"),
                    _("ISBN"))
 
 
 
         #conditions_link = """<a href="http://library.web.cern.ch/library/Library/ill_faq.html" target="_blank">conditions</a>"""
 
         out += """
              <table class="bibcirctable">
                 <tr align="center">
                   <td>
                        <input type=button value="%s"
                         onClick="history.go(-1)" class="formbutton">
 
                        <input type="submit"
                        value="%s" class="formbutton">
 
                   </td>
                  </tr>
              </table>
              </form>
              <br />
              <br />
              </div>
              """ % (_("Back"), _("Continue"))
 
         return out
 
     def tmpl_new_book_step2(self, ln=CFG_SITE_LANG):
         ### FIXME ###
 
         _ = gettext_set_language(ln)
 
         return _("Coming soon...")
 
     def tmpl_add_new_copy_step1(self, ln=CFG_SITE_LANG):
         """
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         out = load_menu(ln)
 
         out += """
         <div class="bibcircbottom">
         <form name="add_new_copy_step1_form"
               action="%s/admin2/bibcirculation/add_new_copy_step2"
               method="get" >
         <br />
         <br />
         <br />
         <input type=hidden name=start value="0">
         <input type=hidden name=end value="10">
         <table class="bibcirctable">
            <tr align="center">
            """ % (CFG_SITE_URL)
         out += """
              <td class="bibcirctableheader">%s
              <input type="radio" name="f" value="" checked>%s
              <input type="radio" name="f" value="name">%s
              <input type="radio" name="f" value="author">%s
              <input type="radio" name="f" value="title">%s
              """ % (_("Search item by"), _("any field"), _("year"),
                     _("author"), _("title"))
 
         out += """
              <br />
              <br />
             </td>
            <tr align="center">
              <td>
                <input type="text" size="50" name="p" style='border: 1px solid #cfcfcf'>
              </td>
            </tr>
         </table>
         <br />
         <table class="bibcirctable">
             <tr align="center">
                 <td>
                     <input type=button
                             value="%s"
                             onClick="history.go(-1)"
                             class="formbutton">
                     <input type="submit"
                             value="%s"
                             class="formbutton">
                 </td>
             </tr>
         </table>
         <br />
         <br />
         <br />
         <br />
         </div>
         <form>
         """ % (_("Back"), _("Search"))
 
         return out
 
     def tmpl_add_new_copy_step2(self, result, ln=CFG_SITE_LANG):
         """
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         out = load_menu(ln)
 
         out += """
         <div class="bibcircbottom">
         <br />
         <br />
         <table class="bibcirctable">
           <tr align="center">
             <td class="bibcirccontent">
               <strong>%s items found</strong>
             </td>
           </tr>
         </table>
         <table class="bibcirctable">
         </tr>
         """ % (len(result))
 
         for recid in result:
 
             title_link = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/add_new_copy_step3',
                                     {'recid': recid, 'ln': ln},
                                     (book_title_from_MARC(recid)))
 
             out += """
                 <tr align="center">
                 <td class="contents">%s</td>
                 </tr>
                 """ % (title_link)
 
         out += """
         </table>
         <br />
         """
 
         out += """
         <table class="bibcirctable">
         <tr align="center">
         <td>
         <input type=button value="%s" onClick="history.go(-1)" class="formbutton">
         </td>
         </tr>
         </table>
         <br />
         <br />
         <br />
         </div>
         """ % (_("Back"))
         return out
 
     def tmpl_add_new_copy_step3(self, recid, result, libraries,
                                 original_copy_barcode, tmp_barcode,
                                 infos, ln=CFG_SITE_LANG):
         """
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         record_is_periodical = is_periodical(recid)
 
         out = self.tmpl_infobox(infos, ln)
 
         out += load_menu(ln)
 
         (book_title, book_year, book_author,
                      book_isbn, book_editor) = book_information_from_MARC(recid)
 
         if book_isbn:
             book_cover = get_book_cover(book_isbn)
         else:
             book_cover = "%s/img/book_cover_placeholder.gif" % (CFG_SITE_URL)
 
         out += """
             <style type="text/css">
                 @import url("/img/jquery/tablesorter.css");
             </style>
             <script src="/js/jquery/jquery.min.js" type="text/javascript"></script>
             <script src="/js/jquery/tablesorter/jquery.tablesorter.js" type="text/javascript"></script>
 
             <style type="text/css">
                 @import url("/js/jquery/tablesorter/themes/blue/style.css");
             </style>
             <style type="text/css">
                 @import url("/js/jquery/tablesorter/addons/pager/jquery.tablesorter.pager.css");
             </style>
 
             <script src="/js/jquery/jquery.min.js" type="text/javascript"></script>
             <script src="/js/jquery/tablesorter/jquery.tablesorter.js" type="text/javascript"></script>
             <script src="/js/jquery/tablesorter/addons/pager/jquery.tablesorter.pager.js"
                     type="text/javascript"></script>
             """
 
         if record_is_periodical:
             out += """
             <script type="text/javascript">
                 $(document).ready(function(){
                     $("#table_copies")
                       .tablesorter({sortList: [[6,1]],widthFixed: true, widgets: ['zebra']})
                       .bind("sortStart",function(){$("#overlay").show();})
                       .bind("sortEnd",function(){$("#overlay").hide()})
                       .tablesorterPager({container: $("#pager"), positionFixed: false});
                 });
             </script>
             """
         else:
             out += """
             <script type="text/javascript">
                 $(document).ready(function() {
                     $('#table_copies').tablesorter({widthFixed: true, widgets: ['zebra']})
                 });
             </script>
             """
 
         out += """
            <form name="add_new_copy_step3_form"
                  action="%s/admin2/bibcirculation/add_new_copy_step4" method="get" >
            <div class="bibcircbottom">
                 <br />
                 <table class="bibcirctable">
                     <tr>
                         <td class="bibcirctableheader" width="10">%s</td>
                     </tr>
                 </table>
                 <table class="bibcirctable">
                  <tr valign='top'>
                     <td width="400">
                     <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      </table>
                      </td>
                      <td class="bibcirccontent">
                         <img style='border: 1px solid #cfcfcf' src="%s" alt="Book Cover"/>
                      </td>
                      </tr>
               </table>
 
            <br />
            <table class="bibcirctable">
                 <tr>
                      <td class="bibcirctableheader">%s</td>
                 </tr>
            </table>
 
            """ % (CFG_SITE_URL,
                    _("Item details"),
                    _("Name"),
                    book_title,
                    _("Author(s)"),
                    book_author,
                    _("Year"),
                    book_year,
                    _("Publisher"),
                    book_editor,
                    _("ISBN"),
                    book_isbn,
                    str(book_cover),
                    _("Copies of %s" % book_title))
 
 
         out += """
                   <table class="tablesorter" id="table_copies" border="0"
                          cellpadding="0" cellspacing="1">
                   <thead>
                     <tr>
                       <th>%s</th>
                       <th>%s</th>
                       <th>%s</th>
                       <th>%s</th>
                 """ % (_("Barcode"),
                        _("Status"),
                        _("Due date"),
                        _("Library"))
 
         if not record_is_periodical:
             out += """
                       <th>%s</th>
                    """ % (_("Location"))
 
         out += """
                       <th>%s</th>
                       <th>%s</th>
                 """ % (_("Loan period"),
                        _("No of loans"))
 
         if not record_is_periodical:
             out += """
                       <th>%s</th>
                    """ % (_("Collection"))
 
         out += """
                       <th>%s</th>
                     </tr>
                   </thead>
                   <tboby>
                     """ % (_("Description"))
 
         for (barcode, loan_period, lib_name, libid, location, nb_requests,
              status, collection, description, due_date) in result:
 
             library_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_library_details',
                                 {'library_id': libid, 'ln': ln}, (lib_name))
 
             out += """
                  <tr>
                      <td>%s</td>
                      <td>%s</td>
                      <td>%s</td>
                      <td>%s</td>
                      """ % (barcode, status, due_date or '-', library_link)
 
             if not record_is_periodical:
                 out += """
                      <td>%s</td>
                      """ % (location)
 
             out += """
                      <td>%s</td>
                      <td>%s</td>
                      """ % (loan_period, nb_requests)
 
             if not record_is_periodical:
                 out += """
                      <td>%s</td>
                      """ % (collection or '-')
 
             out += """
                      <td>%s</td>
                      """ % (description or '-')
 
         out += """
            </tbody>
            </table>
            """
 
         if record_is_periodical:
             out += """
             <div id="pager" class="pager">
                         <form>
                             <img src="/img/sb.gif" class="first" />
                             <img src="/img/sp.gif" class="prev" />
                             <input type="text" class="pagedisplay" />
                             <img src="/img/sn.gif" class="next" />
                             <img src="/img/se.gif" class="last" />
                             <select class="pagesize">
                                 <option value="10" selected="selected">10</option>
                                 <option value="20">20</option>
                                 <option value="30">30</option>
                                 <option value="40">40</option>
                             </select>
                         </form>
             </div>
             </br>
             """
 
         if record_is_periodical:
             colspan = 'colspan="5"'
         else:
             colspan = ''
 
         if original_copy_barcode is not None:
             default_details = db.get_item_info(original_copy_barcode)
             if default_details is not None:
                 default_library_id = default_details[1]
                 default_collection = default_details[3]
                 default_location = default_details[4]
                 default_description = default_details[5]
                 default_loan_period = default_details[6]
 
         out += """
           <table class="bibcirctable">
                 <tr>
                      <td class="bibcirctableheader">%s</td>
                 </tr>
            </table>
            <table class="tablesorterborrower" border="0" cellpadding="0" cellspacing="1">
                 <tr>
                     <th>%s</th>
                     <td %s>
                       <input type="text" style='border: 1px solid #cfcfcf' size=35
                              name="barcode" value='%s'>
                     </td>
                 </tr>
                 <tr>
                     <th>%s</th>
                     <td %s>
                       <select name="library"  style='border: 1px solid #cfcfcf'>
 
                 """ % (_("New copy details"), _("Barcode"),
                        colspan, tmp_barcode, _("Library"), colspan)
 
         main_library = db.get_main_libraries()
         if main_library is not None:
             main_library = main_library[0][0] #id of the first main library
 
         for(library_id, name) in libraries:
             if original_copy_barcode is not None and \
                default_details is not None and \
                library_id == default_library_id:
                 out += """<option value="%s" selected="selected">%s</option>
                       """ % (library_id, name)
             elif library_id == main_library:
                 out += """<option value="%s" selected="selected">%s</option>
                       """ % (library_id, name)
             else:
                 out += """<option value="%s">%s</option>""" % (library_id, name)
 
         if original_copy_barcode is not None \
             and default_location is not None:
             loc = default_location
         else:
             loc = ''
 
         out += """
                     </select>
                     </td>
                 </tr>
             """
 
         if record_is_periodical:
             out += """ <input type=hidden name=collection value="%s">
                     """ % ("Periodical")
         else:
             out += """
                 <tr>
                     <th width="100">%s</th>
                     <td>
                       <input type="text" style='border: 1px solid #cfcfcf' size=35
                              name="location" value="%s">
                     </td>
                 </tr>
                 """ % (_("Location"), loc)
 
             out += """
                 <tr>
                     <th width="100">%s</th>
                     <td>
                       <select name="collection" style='border: 1px solid #cfcfcf'>
                    """ % (_("Collection"))
 
             for collection in CFG_BIBCIRCULATION_COLLECTION:
                 if original_copy_barcode is not None and \
                    default_collection is not None and \
                    collection == default_collection:
                     out += """
                         <option value="%s" selected="selected">%s</option>
                            """ % (collection, collection)
                 else:
                     out += """
                         <option value="%s">%s</option>
                            """ % (collection, collection)
 
             out += """
                       </select>
                     </td>
                 </tr>
                 """
 
         if original_copy_barcode is not None \
            and default_description is not None:
             desc = default_description
         else:
             desc = ''
 
         out += """
                 <tr>
                     <th width="100">%s</th>
                     <td>
                       <input type="text" style='border: 1px solid #cfcfcf' size=35
                              name="description" value="%s">
                     </td>
                 </tr>
                 """ % (_("Description"), desc)
 
         out += """
                 <tr>
                     <th width="100">%s</th>
                     <td %s>
                       <select name="loan_period"  style='border: 1px solid #cfcfcf'>
                 """ % (_("Loan period"), colspan)
 
         for loan_period in CFG_BIBCIRCULATION_ITEM_LOAN_PERIOD:
             if original_copy_barcode is not None and \
                  default_loan_period is not None and \
                  loan_period == default_loan_period:
                 out += """
                           <option value="%s" selected="selected">%s</option>
                        """ % (loan_period, loan_period)
             else:
                 out += """
                           <option value="%s">%s</option>
                        """ % (loan_period, loan_period)
 
         out += """
                       </select>
                     </td>
                 </tr>
             """
 
         out += """
                 <tr>
                     <th width="100">%s</th>
                     <td %s>
                     <select name="status"  style='border: 1px solid #cfcfcf'>
                 """ % (_("Status"), colspan)
 
         for st in CFG_BIBCIRCULATION_ITEM_STATUS:
             if st == CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF:
                 out += """
                           <option value ="%s" selected="selected">%s</option>
                     """ % (st, st)
             else:
                 out += """
                           <option value ="%s">%s</option>
                     """ % (st, st)
 
         out += """
                     </select>
                     </td>
                  </tr>
                  <tr>
                   <th width="100">%s</th>
                   <td %s>
                     <input type="text" style='border: 1px solid #cfcfcf' size=35
                            name="expected_arrival_date" value="">
                   </td>
                  </tr>
                 </table>
            <br />
            <table class="bibcirctable">
                 <tr>
                      <td>
                        <input type=button value="%s"
                         onClick="history.go(-1)" class="formbutton">
                        <input type="submit" value="%s" class="formbutton">
                        <input type=hidden name=recid value="%s">
                      </td>
                 </tr>
            </table>
            <br />
            <br />
            </div>
            </form>
            """ % (_("Expected arrival date"), colspan, _("Back"),
                   _("Continue"), recid)
 
         return out
 
     def tmpl_add_new_copy_step4(self, tup_infos, ln=CFG_SITE_LANG):
         """
         @param tup_info: item's informations
         @type tup_info: tuple
 
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         (barcode, library, _library_name, location, collection, description,
          loan_period, status, expected_arrival_date, recid) = tup_infos
 
         out = """ """
 
         out += load_menu(ln)
 
         out += """
             <style type="text/css"> @import url("/img/tablesorter.css"); </style>
             <div class="bibcircbottom">
             <form name="add_new_copy_step4_form"
                   action="%s/admin2/bibcirculation/add_new_copy_step5"
                   method="get" >
               <br />
               <br />
               <table class="tablesorterborrower">
                 <tr>
                     <th width="90">%s</th> <td class="bibcirccontent">%s</td>
                 </tr>
                 <tr>
                     <th width="90">%s</th> <td class="bibcirccontent">%s</td>
                 </tr>
                 <tr>
                     <th width="90">%s</th> <td class="bibcirccontent">%s</td>
                 </tr>
                 <tr>
                     <th width="90">%s</th> <td class="bibcirccontent">%s</td>
                 </tr>
                 <tr>
                     <th width="90">%s</th> <td class="bibcirccontent">%s</td>
                  </tr>
                  <tr>
                     <th width="90">%s</th> <td class="bibcirccontent">%s</td>
                  </tr>
                  <tr>
                     <th width="90">%s</th> <td class="bibcirccontent">%s</td>
                  </tr>
                  <tr>
                     <th width="90">%s</th> <td class="bibcirccontent">%s</td>
                  </tr>
                 </table>
                 <br />
                 <table class="bibcirctable">
                 <tr>
                   <td>
                        <input type=button value="%s"
                         onClick="history.go(-1)" class="formbutton">
 
                        <input type="submit"
                        value="%s" class="formbutton">
 
                        <input type=hidden name=barcode value="%s">
                        <input type=hidden name=library value="%s">
                        <input type=hidden name=location value="%s">
                        <input type=hidden name=collection value="%s">
                        <input type=hidden name=description value="%s">
                        <input type=hidden name=loan_period value="%s">
                        <input type=hidden name=status value="%s">
                        <input type=hidden name=expected_arrival_date value="%s">
                        <input type=hidden name=recid value="%s">
 
                   </td>
                  </tr>
                 </table>
                 <br />
                 <br />
                 </form>
                 </div>
                 """ % (CFG_SITE_URL,
                        _("Barcode"), tup_infos[0],
                        _("Library"), tup_infos[2],
                        _("Location"), tup_infos[3],
                        _("Collection"), tup_infos[4],
                        _("Description"), tup_infos[5],
                        _("Loan period"), tup_infos[6],
                        _("Status"), tup_infos[7],
                        _("Expected arrival date"), expected_arrival_date,
                        _("Back"), _("Continue"),
                        barcode, library, location, collection, description,
                        loan_period, status, expected_arrival_date, recid)
                        #tup_infos)
 
         return out
 
     def tmpl_add_new_copy_step5(self, infos, recid, ln=CFG_SITE_LANG):
         """
         @param recid: identify the record. Primary key of bibrec.
         @type recid: int
         """
 
         _ = gettext_set_language(ln)
 
         out = """ """
 
         out += load_menu(ln)
 
         if infos == []:
             out += """
             <div class="bibcircbottom">
               <br />
               <br />
               <table class="bibcirctable">
                 <tr>
                     <td class="bibcirccontent">%s</td>
                 </tr>
                 </table>
                 <br />
                 <table class="bibcirctable">
                     <tr>
                         <td>
                             <input type=button value='%s'
                     onClick="location.href='%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s'"
                             class="formbutton">
                         </td>
                     </tr>
                 </table>
                 <br />
                 <br />
                 </div>
         """ % (_("A %(x_url_open)snew copy%(x_url_close)s has been added.") % {'x_url_open': '<a href="' + CFG_SITE_URL + '/admin2/bibcirculation/get_item_details?ln=%s&amp;recid=%s' %(ln, recid) + '">', 'x_url_close': '</a>'},
                _("Back to home"),
                CFG_SITE_URL, ln)
 
         else:
             out += """<br /> """
             out += self.tmpl_infobox(infos, ln)
             out += """
             <div class="bibcircbottom">
                 <br />
                 <br />
 
                 <table class="bibcirctable">
                     <tr>
                         <td>
                             <input type=button value='%s'
             onClick="location.href='%s/admin2/bibcirculation/get_item_details?ln=%s&recid=%s'"
                             class="formbutton">
                         </td>
                     </tr>
                 </table>
                 <br />
                 <br />
                 </div>
                 """ % (_("Back to the record"),
                        CFG_SITE_URL, ln, recid)
 
         return out
 
     def tmpl_update_item_info_step1(self, ln=CFG_SITE_LANG):
         """
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         out = load_menu(ln)
 
         out += """
         <div class="bibcircbottom">
         <form name="update_item_info_step1_form"
               action="%s/admin2/bibcirculation/update_item_info_step2" method="get" >
               """ % (CFG_SITE_URL)
         out += """
         <br />
         <br />
         <br />
         <input type=hidden name=start value="0">
         <input type=hidden name=end value="10">
         <table class="bibcirctable">
                 <tr align="center">
                   <td class="bibcirctableheader">%s
                     <input type="radio" name="f" value="" checked>%s
                     <input type="radio" name="f" value="name">%s
                     <input type="radio" name="f" value="email">%s
                     <input type="radio" name="f" value="email">%s
                     <br /><br />
                   </td>
             """ % (_("Search item by"), _("any field"), _("year"),
                    _("author"), _("title"))
 
         out += """
                 <tr align="center">
                   <td>
                     <input type="text" size="50" name="p" style='border: 1px solid #cfcfcf'>
                   </td>
                 </tr>
         </table>
         <br />
         <table class="bibcirctable">
             <tr align="center">
                 <td>
                     <input type=button
                            value="%s"
                            onClick="history.go(-1)"
                            class="formbutton">
 
                     <input type="submit"
                            value="%s"
                            class="formbutton">
                 </td>
             </tr>
         </table>
         <br />
         <br />
         <br />
         <br />
         </div>
         <form>
         """ % (_("Back"), _("Search"))
 
         return out
 
     def tmpl_update_item_info_step2(self, result, ln=CFG_SITE_LANG):
         """
         @param result: list with recids
         @type result: list
 
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         out = load_menu(ln)
 
         out += """
         <div class="bibcircbottom">
         <br />
         <br />
         <table class="bibcirctable">
           <tr align="center">
             <td class="bibcirccontent"><strong>%s</strong></td>
           </tr>
         </table>
         <table class="bibcirctable">
         </tr>
         """ % (_("%(nb_items_found)i items found")
                     % {'nb_items_found': len(result)})
 
         for recid in result:
 
             title_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/update_item_info_step3',
                                 {'recid': recid, 'ln': ln},
                                 (book_title_from_MARC(recid)))
 
             out += """
                 <tr align="center">
                 <td class="contents">%s</td>
                 </tr>
                 """ % (title_link)
 
         out += """
         </table>
         <br />
         <table class="bibcirctable">
         <tr align="center">
         <td>
         <input type=button value="%s" onClick="history.go(-1)" class="formbutton">
         </td>
         </tr>
         </table>
         <br />
         <br />
         <br />
         </div>
         """ % (_("Back"))
         return out
 
     def tmpl_update_item_info_step3(self, recid, result, ln=CFG_SITE_LANG):
         """
         @param recid: identify the record. Primary key of bibrec.
         @type recid: int
 
         @param result: book's information
         @type result: tuple
 
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         out = """
         """
         out += load_menu(ln)
 
         (book_title, book_year, book_author,
                      book_isbn, book_editor) = book_information_from_MARC(recid)
 
         if book_isbn:
             book_cover = get_book_cover(book_isbn)
         else:
             book_cover = "%s/img/book_cover_placeholder.gif" % (CFG_SITE_URL)
 
         out += """
            <form name="update_item_info_step3_form"
                  action="%s/admin2/bibcirculation/update_item_info_step4" method="get" >
            <div class="bibcircbottom">
                 <br />
                      <table class="bibcirctable">
                           <tr>
                                <td class="bibcirctableheader" width="10">%s</td>
                           </tr>
                 </table>
                 <table class="bibcirctable">
                  <tr valign='top'>
                     <td width="400">
                     <table>
                      <tr>
                         <td width="100">%s</td>
                         <td class="bibcirccontent">%s</td>
                      </tr>
                      <tr>
                         <td width="100">%s</td>
                         <td class="bibcirccontent">%s</td>
                      </tr>
                      <tr>
                         <td width="100">%s</td>
                         <td class="bibcirccontent">%s</td>
                          </tr>
                      <tr>
                         <td width="100">%s</td>
                         <td class="bibcirccontent">%s</td>
                      </tr>
                      <tr>
                         <td width="100">%s</td>
                         <td class="bibcirccontent">%s</td>
                      </tr>
                      </table>
                      </td>
                      <td class="bibcirccontent">
                         <img style='border: 1px solid #cfcfcf' src="%s" alt="Book Cover"/>
                      </td>
                  </tr>
                 </table>
 
            <br />
 
            """ % (CFG_SITE_URL,
                    _("Item details"),
                    _("Name"),
                    book_title,
                    _("Author(s)"),
                    book_author,
                    _("Year"),
                    book_year,
                    _("Publisher"),
                    book_editor,
                    _("ISBN"),
                    book_isbn,
                    str(book_cover))
 
 
         out += """<table class="bibcirctable">
                     <tr>
                       <td>%s</td>
                       <td align="center">%s</td>
                       <td align="center">%s</td>
                       <td align="center">%s</td>
                       <td align="center">%s</td>
                       <td align="center">%s</td>
                       <td align="center">%s</td>
                       <td align="center">%s</td>
                       <td align="center"></td>
                       <td width="350"></td>
                     </tr>""" % (_("Barcode"),
                                 _("Status"),
                                 _("Library"),
                                 _("Location"),
                                 _("Loan period"),
                                 _("No of loans"),
                                 _("Collection"),
                                 _("Description"))
 
 
         for (barcode, loan_period, lib_name, libid, location, nb_requests,
              status, collection, description) in result:
 
             library_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_library_details',
                                 {'library_id': libid, 'ln': ln}, (lib_name))
 
             out += """
                  <tr>
                      <td class="bibcirccontent">%s</td>
                      <td class="bibcirccontent" align="center">%s</td>
                      <td class="bibcirccontent" align="center">%s</td>
                      <td class="bibcirccontent" align="center">%s</td>
                      <td class="bibcirccontent" align="center">%s</td>
                      <td class="bibcirccontent" align="center">%s</td>
                      <td class="bibcirccontent" align="center">%s</td>
                      <td class="bibcirccontent" align="center">%s</td>
                      <td class="bibcirccontent" align="center">
                      <input type=button
       onClick="location.href='%s/admin2/bibcirculation/update_item_info_step4?ln=%s&barcode=%s'"
                      value="%s" class="formbutton">
                      </td>
                      <td class="bibcirccontent" width="350"></td>
                  </tr>
                  """ % (barcode, status, library_link, location, loan_period,
                         nb_requests, collection, description, CFG_SITE_URL, ln,
                         barcode, _("Update"))
 
         out += """
            </table>
            <br />
            <table class="bibcirctable">
                 <tr>
                      <td>
                         <input type=button value="%s"
                          onClick="history.go(-1)" class="formbutton">
                         <input type=hidden name=recid value="%s"></td>
                 </tr>
            </table>
            <br />
            <br />
            </div>
            """ % (_("Back"), recid)
 
         return out
 
     def tmpl_update_item_info_step4(self, recid, result, libraries,
                                     ln=CFG_SITE_LANG):
         """
         @param recid: identify the record. Primary key of bibrec
         @type recid: int
 
         @param result: book's information
         @type result: tuple
 
         @param libraries: list of libraries
         @type libraries: list
 
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         out = load_menu(ln)
 
         (title, year, author, isbn, editor) = book_information_from_MARC(recid)
 
         barcode = result[0]
         expected_arrival_date = db.get_expected_arrival_date(barcode)
 
         if isbn:
             book_cover = get_book_cover(isbn)
         else:
             book_cover = "%s/img/book_cover_placeholder.gif" % (CFG_SITE_URL)
 
         out += """
            <style type="text/css"> @import url("/img/tablesorter.css"); </style>
            <form name="update_item_info_step4_form"
                  action="%s/admin2/bibcirculation/update_item_info_step5" method="get" >
            <div class="bibcircbottom">
                 <br />
                 <table class="bibcirctable">
                     <tr>
                         <td class="bibcirctableheader" width="10">%s</td>
                     </tr>
                 </table>
                 <table class="bibcirctable">
                  <tr valign='top'>
                     <td width="400">
                     <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                      <tr>
                        <th width="100">%s</th>
                        <td>%s</td>
                      </tr>
                      <tr>
                        <th width="100">%s</th>
                        <td>%s</td>
                      </tr>
                      <tr>
                        <th width="100">%s</th>
                        <td>%s</td>
                      </tr>
                      <tr>
                        <th width="100">%s</th>
                        <td>%s</td>
                      </tr>
                      <tr>
                        <th width="100">%s</th>
                        <td>%s</td>
                      </tr>
                    </table>
                  </td>
                  <td class="bibcirccontent">
                     <img style='border: 1px solid #cfcfcf' src="%s" alt="Book Cover"/>
                  </td>
                </tr>
               </table>
 
            <br />
 
            """ % (CFG_SITE_URL,
                    _("Item details"),
                    _("Name"),
                    title,
                    _("Author(s)"),
                    author,
                    _("Year"),
                    year,
                    _("Publisher"),
                    editor,
                    _("ISBN"),
                    isbn,
                    str(book_cover))
 
         out += """
              <table class="bibcirctable">
                 <tr>
                      <td class="bibcirctableheader">%s</td>
                 </tr>
              </table>
              <table class="tablesorterborrower" border="0" cellpadding="0" cellspacing="1">
                <tr>
                  <th width="100">%s</th>
                  <td>
                     <input type="text" style='border: 1px solid #cfcfcf'
                            size=35 name="barcode" value="%s">
                     <input type=hidden name=old_barcode value="%s">
                  </td>
                </tr>
                <tr>
                  <th width="100">%s</th>
                  <td>
                    <select name="library_id"  style='border: 1px solid #cfcfcf'>
 
                 """ % (_("Update copy information"),
                        _("Barcode"), result[0], result[0],
                        _("Library"))
 
         for(library_id, name) in libraries:
 
             if library_id == result[1]:
                 out += """<option value ="%s" selected>%s</option>
                         """ % (library_id, name)
 
             else:
                 out += """<option value ="%s">%s</option>
                         """ % (library_id, name)
 
         out += """
                     </select>
                     </td>
                 </tr>
                 <tr>
                   <th width="100">%s</th>
                   <td>
                     <input type="text" style='border: 1px solid #cfcfcf' size=35
                            name="location" value="%s">
                   </td>
                 </tr>
                 <tr>
                   <th width="100">%s</th>
                   <td>
                     <select name="collection" style='border: 1px solid #cfcfcf'>
                     """ % (_("Location"), result[4],
                            _("Collection"))
 
         for collection in CFG_BIBCIRCULATION_COLLECTION:
             if collection == result[3]:
                 out += """
                     <option value="%s" selected="selected">%s</option>
                        """ % (collection, collection)
             else:
                 out += """
                     <option value="%s">%s</option>
                        """ % (collection, collection)
 
         out += """
                    </select>
                   </td>
                 </tr>
                 <tr>
                   <th width="100">%s</th>
                   <td>
                     <input type="text" style='border: 1px solid #cfcfcf' size=35
                            name="description" value="%s">
                   </td>
                 </tr>
                     """ % (_("Description"), result[5] or '-')
 
         out += """
                 <tr>
                     <th width="100">%s</th>
                     <td>
                       <select name="loan_period"  style='border: 1px solid #cfcfcf'>
                 """ % (_("Loan period"))
 
         for loan_period in CFG_BIBCIRCULATION_ITEM_LOAN_PERIOD:
             if loan_period == result[6]:
                 out += """
                           <option value="%s" selected="selected">%s</option>
                        """ % (loan_period, loan_period)
             else:
                 out += """
                           <option value="%s">%s</option>
                        """ % (loan_period, loan_period)
 
         out += """
                       </select>
                     </td>
                 </tr>
             """
 
         out += """
                  <tr>
                     <th width="100">%s</th>
                     <td>
                       <select name="status"  style='border: 1px solid #cfcfcf'>
 
                       """ % (_("Status"))
 
 
         for st in CFG_BIBCIRCULATION_ITEM_STATUS:
             if st == CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN and result[7] != CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN:
                 pass # to avoid creting a fake loan,
                      # 'on loan' is only shown if the item was already on loan
             elif st == result[7]:
                 out += """
                           <option value="%s" selected>%s</option>
                     """ % (st, st)
             else:
                 out += """
                           <option value="%s">%s</option>
                     """ % (st, st)
 
         out += """  </select>
                     </td>
                  </tr>
                  <tr>
                   <th width="100">%s</th>
                   <td>
                     <input type="text" style='border: 1px solid #cfcfcf' size=35
                            name="expected_arrival_date" value="%s">
                   </td>
                 </tr>
                 </table>
            <br />
            <table class="bibcirctable">
                 <tr>
                      <td>
                        <input type=button onClick="history.go(-1)"
                        value='%s' class='formbutton'>
                        <input type="submit" value='%s' class="formbutton">
                        <input type=hidden name=recid value="%s">
                      </td>
                 </tr>
            </table>
            <br />
            <br />
            </div>
            </form>
            """ % (_("Expected arrival date"), expected_arrival_date,
                   _("Back"), _("Continue"), recid)
 
         return out
 
     def tmpl_update_item_info_step5(self, tup_infos, ln=CFG_SITE_LANG):
         """
         @param tup_info: item's informations
         @type tup_info: tuple
 
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         out = """ """
 
         out += load_menu(ln)
 
         out += """
             <style type="text/css"> @import url("/img/tablesorter.css"); </style>
             <div class="bibcircbottom">
             <form name="update_item_info_step5_form"
                   action="%s/admin2/bibcirculation/update_item_info_step6" method="get" >
               <br />
               <br />
               <table class="bibcirctable">
                 <tr>
                     <td class="bibcirctableheader">%s</td>
                 </tr>
               </table>
               <table class="tablesortersmall" border="0" cellpadding="0" cellspacing="1">
                 <tr>
                     <th width="100">%s</th> <td>%s</td>
                 </tr>
                 <tr>
                     <th width="100">%s</th> <td>%s</td>
                 </tr>
                 <tr>
                     <th width="100">%s</th> <td>%s</td>
                 </tr>
                 <tr>
                     <th width="100">%s</th> <td>%s</td>
                 </tr>
                 <tr>
                     <th width="100">%s</th> <td>%s</td>
                 </tr>
                 <tr>
                     <th width="100">%s</th> <td>%s</td>
                 </tr>
                 <tr>
                     <th width="100">%s</th> <td>%s</td>
                 </tr>
                 <tr>
                     <th width="100">%s</th> <td>%s</td>
                 </tr>
               </table>
               <br />
               <table class="bibcirctable">
                 <tr>
                   <td>
                      <input type=button value="%s"
                        onClick="history.go(-1)" class="formbutton">
                      <input type="submit"
                       value="%s" class="formbutton">
                      <input type=hidden name=barcode value="%s">
                      <input type=hidden name=old_barcode value="%s">
                      <input type=hidden name=library_id value="%s">
                      <input type=hidden name=location value="%s">
                      <input type=hidden name=collection value="%s">
                      <input type=hidden name=description value="%s">
                      <input type=hidden name=loan_period value="%s">
                      <input type=hidden name=status value="%s">
                      <input type=hidden name=expected_arrival_date value="%s">
                      <input type=hidden name=recid value="%s">
                   </td>
                 </tr>
               </table>
               <br />
               <br />
             </form>
             </div>
                 """ % (CFG_SITE_URL, _("New copy information"),
                     _("Barcode"), cgi.escape(tup_infos[0], True),
                     _("Library"), cgi.escape(tup_infos[3], True),
                     _("Location"), cgi.escape(tup_infos[4], True),
                     _("Collection"), cgi.escape(tup_infos[5], True),
                     _("Description"), cgi.escape(tup_infos[6], True),
                     _("Loan period"), cgi.escape(tup_infos[7], True),
                     _("Status"), cgi.escape(tup_infos[8], True),
                     _("Expected arrival date"), cgi.escape(tup_infos[9], True),
                     _("Back"), _("Confirm"),
                     cgi.escape(tup_infos[0], True),
                     cgi.escape(tup_infos[1], True),
                     tup_infos[2], cgi.escape(tup_infos[4], True),
                     cgi.escape(tup_infos[5], True),
                     cgi.escape(tup_infos[6], True),
                     cgi.escape(tup_infos[7], True),
                     cgi.escape(tup_infos[8], True),
                     cgi.escape(tup_infos[9], True), tup_infos[10])
 
         return out
 
     def tmpl_update_item_info_step6(self, ln=CFG_SITE_LANG):
         """
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         out = """ """
 
         out += load_menu(ln)
 
         out += """
             <div class="bibcircbottom">
               <br />
               <br />
               <table class="bibcirctable">
                 <tr>
                     <td class="bibcirccontent">%s</td>
                 </tr>
                 </table>
                 <br />
                 <table class="bibcirctable">
                 <tr>
                   <td>
                        <input type=button value='%s'
                     onClick="location.href='%s/admin2/bibcirculation/loan_on_desk_step1ln=%s'"
                         class="formbutton">
                   </td>
                  </tr>
                 </table>
                 <br />
                 <br />
                 </div>
                 """ % (_("This item has been updated."),
                        _("Back to home"),
                        CFG_SITE_URL, ln)
 
         return out
 
     def tmpl_search_library_step1(self, infos, ln=CFG_SITE_LANG):
         """
         Template for the admin interface. Search borrower.
 
         @param infos: informations
         @type infos: list
 
         @param ln: language
         """
         _ = gettext_set_language(ln)
 
         out = self.tmpl_infobox(infos, ln)
 
         out += load_menu(ln)
 
         out += """
         <div class="bibcircbottom">
         <br />
         <br />
         <br />
         <form name="search_library_step1_form"
               action="%s/admin2/bibcirculation/search_library_step2"
               method="get" >
           <table class="bibcirctable">
            <tr align="center">
              <td class="bibcirctableheader">%s
                <input type="radio" name="column" value="name" checked>%s
                <input type="radio" name="column" value="email">%s
                <br>
                <br>
              </td>
            </tr>
         """ % (CFG_SITE_URL,
                _("Search library by"),
                _("name"), _("email"))
         out += """
            <tr align="center">
              <td>
                 <input type="text" size="45" name="string" id="string"
                        style='border: 1px solid #cfcfcf'>
                 <script language="javascript" type="text/javascript">
                     document.getElementById("string").focus();
                 </script>
              </td>
            </tr>
           </table>
           <br />
           <table class="bibcirctable">
              <tr align="center">
                   <td>
                         <input type=button value='%s'
                           onClick="history.go(-1)" class="formbutton">
                         <input type="submit" value='%s' class="formbutton">
                   </td>
              </tr>
         </table>
         <form>
         <br />
         <br />
         <br />
         <br />
         </div>
 
         """ % (_("Back"),
                _("Search"))
 
 
         return out
 
     def tmpl_search_library_step2(self, result, ln=CFG_SITE_LANG):
         """
         @param result: search result about libraries
         @type result: list
 
         @param ln: language
         """
 
         _ = gettext_set_language(ln)
 
         out = """ """
 
         out += load_menu(ln)
 
         if len(result) == 0:
             out += """
             <div class="bibcircbottom">
             <br />
             <div class="bibcircinfoboxmsg">%s</div>
             <br />
             """ % (_("0 libraries found."))
 
         else:
             out += """
         <style type="text/css"> @import url("/img/tablesorter.css"); </style>
         <div class="bibcircbottom" align="center">
         <br />
         <table class="bibcirctable">
             <tr align="center">
                 <td class="bibcirccontent">
                     <strong>%s libraries found</strong>
                 </td>
             </tr>
         </table>
         <br />
         <table class="tablesortersmall" border="0" cellpadding="0" cellspacing="1">
           <th align="center">%s</th>
 
         """ % (len(result), _("Libraries"))
 
             for (library_id, name) in result:
 
                 library_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_library_details',
                                 {'library_id': library_id, 'ln': ln}, (name))
 
                 out += """
             <tr align="center">
                 <td width="70">%s
                     <input type=hidden name=library_id value="%s">
                 </td>
             </tr>
             """ % (library_link, library_id)
 
         out += """
         </table>
         <br />
         <table class="bibcirctable">
             <tr align="center">
                 <td>
                     <input type=button value="%s" onClick="history.go(-1)" class="formbutton">
                 </td>
             </tr>
         </table>
         <br />
         <br />
         <br />
         </form>
         </div>
 
         """ % (_("Back"))
 
         return out
 
     def tmpl_library_notes(self, library_notes, library_id,
                            ln=CFG_SITE_LANG):
 
         """
         @param library_notes: notes about a library
         @type library_notes: dictionnary
 
         @param library_id: identify the library. Primary key of crcLIBRARY
         @type library_id: int
 
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         if not library_notes:
             library_notes = {}
         else:
             library_notes = eval(library_notes)
 
         out = """ """
 
         out += load_menu(ln)
 
         out += """
             <div class="bibcircbottom">
             <form name="library_notes" action="%s/admin2/bibcirculation/get_library_notes" method="get" >
             <input type=hidden name=library_id value='%s'>
             <br />
             <br />
             <table class="bibcirctable">
               <tr>
                 <td class="bibcirctableheader">%s</td>
               </tr>
             </table>
             <table class="bibcirctable">
               <tr>
                 <td>
                   <table class="bibcircnotes">
 
             """ % (CFG_SITE_URL, library_id,
                    _("Notes about library"))
 
         key_array = library_notes.keys()
         key_array.sort()
 
         for key in key_array:
             delete_note = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_library_notes',
                                 {'delete_key': key, 'library_id': library_id,
                                  'ln': ln}, (_("[delete]")))
 
             out += """<tr class="bibcirccontent">
                         <td class="bibcircnotes" width="160" valign="top" align="center"><b>%s</b></td>
                         <td width="400"><i>%s</i></td>
                         <td width="65" align="center">%s</td>
                       </tr>
 
                       """ % (key, library_notes[key], delete_note)
 
         out += """
                   </table>
                 </td>
               </tr>
             </table>
             <br />
             <table class="bibcirctable">
               <tr>
                 <td class="bibcirctableheader">%s</td>
               </tr>
             </table>
             <table class="bibcirctable">
               <tr>
                 <td class="bibcirccontent">
                   <textarea name="library_notes" rows="5" cols="90" style='border: 1px solid #cfcfcf'></textarea>
                 </td>
               </tr>
             </table>
             <br />
             <table class="bibcirctable">
               <tr>
                   <td>
                       <input type=button
     onClick="location.href='%s/admin2/bibcirculation/get_library_details?ln=%s&library_id=%s'"
                        value="%s" class='formbutton'>
                        <input type="submit" value='%s' class="formbutton">
                   </td>
              </tr>
              </table>
              <br />
              <br />
              <br />
              </form>
              </div>
         """ % (_("Write new note"),
                CFG_SITE_URL, ln,
                library_id,
                _("Back"),
                _("Confirm"))
 
         return out
 
     def tmpl_change_due_date_step1(self, loan_details, loan_id, borrower_id,
                                    ln=CFG_SITE_LANG):
         """
         Return the form where the due date can be changed.
 
         @param loan_details: the information related with the loan.
         @type loan_details: tuple
 
         @param loan_id: identify the loan. Primary key of crcLOAN.
         @type loan_id: int
 
         @param borrower_id: identify the borrower. Primary key of crcBORROWER.
         @type borrower_id: int
 
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         out = """ """
 
         out += load_menu(ln)
 
         (recid, barcode, loaned_on, due_date, loan_status,
                                     loan_period, _item_status) = loan_details
         number_of_requests = db.get_number_requests_per_copy(barcode)
         if number_of_requests > 0:
             request_status = 'Yes'
         else:
             request_status = 'No'
 
         out += """
             <div class="bibcircbottom">
             <form name="borrower_notes" action="%s/admin2/bibcirculation/change_due_date_step2" method="get" >
             <br />
             <br />
             <table class="bibcirctable">
              <tr>
                <td class="bibcirctableheader" width="100">%s</td>
              </tr>
            </table>
            <table class="bibcirctable">
             <tr>
              <td width="80">%s</td> <td class="bibcirccontent">%s</td>
             </tr>
             <tr>
             <td width="80">%s</td> <td class="bibcirccontent">%s</td>
             </tr>
             <tr>
             <td width="80">%s</td> <td class="bibcirccontent">%s</td>
             </tr>
             <tr>
             <td width="80">%s</td> <td class="bibcirccontent">%s</td>
             </tr>
             <tr>
             <td width="80">%s</td> <td class="bibcirccontent">%s</td>
             </tr>
             <tr>
             <td width="80">%s</td> <td class="bibcirccontent">%s</td>
             </tr>
             <tr>
             <td width="80">%s</td> <td class="bibcirccontent">%s</td>
             </tr>
             </table>
             <br />
              """ % (CFG_SITE_URL, _("Loan information"),
                     _("Title"), book_title_from_MARC(recid),
                     _("Barcode"), barcode,
                     _("Loan date"), loaned_on,
                     _("Due date"), due_date,
                     _("Loan status"), loan_status,
                     _("Loan period"), loan_period,
                     _("Requested ?"), request_status)
 
         out += """
 
             <script type="text/javascript" language='JavaScript' src="%s/js/jquery/jquery.ui.datepicker.min.js"></script>
 
             <table class="bibcirctable">
               <tr align="left">
                 <td width="230" class="bibcirctableheader">%s
                     <script type="text/javascript">
                         $(function(){
                             $("#date_picker1").datepicker({dateFormat: 'yy-mm-dd', showOn: 'button', buttonImage: "%s/img/jquery/calendar.gif", buttonImageOnly: true});
                         });
                     </script>
                     <input type="text" size="12" id="date_picker1" name="new_due_date" value="%s" style='border: 1px solid #cfcfcf'>
                 </td>
               </tr>
             </table>
             <br />
             """ % (CFG_SITE_URL,
                     _("New due date: "), CFG_SITE_URL, due_date)
 
 
         out += """
         <table class="bibcirctable">
              <tr>
                   <td>
                        <input type=hidden name=loan_id value="%s">
                        <input type=hidden name=borrower_id value="%s">
 
                        <input type=button value="%s"
                         onClick="history.go(-1)" class="formbutton">
 
                        <input type="submit"
                         value="%s" class="formbutton">
 
 
                   </td>
              </tr>
         </table>
         <br />
         <br />
         </form>
         </div>
         """ % (loan_id, borrower_id,
                _("Back"), _("Submit new due date"))
 
         return out
 
     def tmpl_change_due_date_step2(self, new_due_date, borrower_id,
                                    ln=CFG_SITE_LANG):
         """
         Return a page with the new due date.
 
         @param due_date: new due date
         @type due_date: string
 
         @param borrower_id: identify the borrower. Primary key of crcBORROWER.
         @type borrower_id: int
 
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         out = """ """
 
         out += load_menu(ln)
 
         out += """
             <div class="bibcircbottom">
               <br />
               <br />
               <table class="bibcirctable">
                 <tr>
                     <td class="bibcirccontent">%s</td>
                 </tr>
                 </table>
                 <br />
                 <table class="bibcirctable">
                 <tr>
                   <td>
                     <input type=button
     onClick="location.href='%s/admin2/bibcirculation/get_borrower_loans_details?ln=%s&borrower_id=%s'"
                     value='%s' class='formbutton'>
                   </td>
                  </tr>
                 </table>
                 <br />
                 <br />
                 </div>
 """ % (_("The due date has been updated. New due date: %s" % (new_due_date)),
     CFG_SITE_URL, ln, borrower_id, cgi.escape(_("Back to borrower's loans"), True))
 
 
         return out
 
     def tmpl_create_new_loan_step1(self, borrower, infos, ln=CFG_SITE_LANG):
         """
         Display the borrower's information and a form where it is
         possible to search for an item.
 
         @param borrower: borrower's information.
         @type borrower: tuple
 
         @param infos: informations
         @type infos: list
 
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         out = self.tmpl_infobox(infos, ln)
 
         out += load_menu(ln)
 
         (borrower_id, ccid, name, email, phone, address, mailbox) = borrower
 
         display_id = borrower_id
         id_string = _("ID")
         if CFG_CERN_SITE == 1:
             display_id = ccid
             id_string = _("CCID")
 
         out += """
             <form name="create_new_loan_form1"
                   action="%s/admin2/bibcirculation/create_new_loan_step2"
                   method="post" >
             <div class="bibcircbottom">
             <input type=hidden name=borrower_id value="%s">
             <br />
             <table class="bibcirctable">
                  <tr>
                       <td class="bibcirctableheader">%s</td>
                  </tr>
              </table>
             </form>
             <table class="bibcirctable">
                  <tr>
                       <td width="100">%s</td>
                       <td class="bibcirccontent">%s</td>
                  </tr>
                      <tr>
                       <td width="100">%s</td>
                       <td class="bibcirccontent">%s</td>
 
                  </tr>
                  <tr>
                       <td width="100">%s</td>
                       <td class="bibcirccontent">%s</td>
                  </tr>
                  <tr>
                       <td width="100">%s</td>
                       <td class="bibcirccontent">%s</td>
                  </tr>
                  <tr>
                       <td width="100">%s</td>
                       <td class="bibcirccontent">%s</td>
                  </tr>
                  <tr>
                       <td width="100">%s</td>
                       <td class="bibcirccontent">%s</td>
                  </tr>
             </table>
             """% (CFG_SITE_URL,
                   borrower_id,
                   _("Personal details"),
                   id_string, display_id,
                   _("Name"), name,
                   _("Address"), address,
                   _("Mailbox"), mailbox,
                   _("Email"), email,
                   _("Phone"), phone)
 
 
         out += """
         <br />
         <table class="bibcirctable">
                   <tr>
                      <td class="bibcirctableheader">%s</td>
                   </tr>
                   <tr>
                      <td><input type="text" size="50" name="barcode" style='border: 1px solid #cfcfcf'></td>
                   </tr>
              </table>
              """ % (_("Barcode"))
 
         out += """
               <br />
               <table class="bibcirctable">
                 <tr>
                   <td class="bibcirctableheader">%s</td>
                 </tr>
                 <tr>
                   <td><textarea name='new_note' rows="4" cols="43" style='border: 1px solid #cfcfcf'></textarea></td>
                 </tr>
               </table>
               <br />
               """ % (_("Write notes"))
 
         out += """
         <table class="bibcirctable">
              <tr>
                   <td>
                        <input type=button value="%s" onClick="history.go(-1)" class="formbutton">
                        <input type="submit"   value="%s" class="formbutton">
                   </td>
              </tr>
         </table>
         <br />
         <br />
         <br />
         </div>
         </form>
         """ % (_("Back"),
                _("Confirm"))
 
         return out
 
     def tmpl_create_new_request_step1(self, borrower, infos, result, p, f,
                                       ln=CFG_SITE_LANG):
         """
         Display the borrower's information and the form where it is
         possible to search for an item.
 
         @param borrower: borrower's information.
         @type borrower: tuple
 
         @param infos: informations
         @type infos: list
 
         @param result: result of searching for an item, using p and f.
         @type result: list
 
         @param p: pattern who will be used in the search process.
         @type p: string
 
         @param f: field who will be used in the search process.
         @type f: string
 
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         out = self.tmpl_infobox(infos, ln)
 
         out += load_menu(ln)
 
         (borrower_id, ccid, name, email, phone, address, mailbox) = borrower
 
         display_id = borrower_id
         id_string = _("ID")
         if CFG_CERN_SITE == 1:
             display_id = ccid
             id_string = _("CCID")
 
         out += """
             <style type="text/css"> @import url("/img/tablesorter.css"); </style>
 
             <div class="bibcircbottom">
 
             <br />
 
             <table class="bibcirctable">
             <tbody>
                 <tr>
                     <td width="500" valign="top">
                         <form name="create_new_loan_form1"
                           action="%s/admin2/bibcirculation/create_new_request_step1"
                           method="get" >
                             <input type=hidden name=borrower_id value="%s">
                             <table class="bibcirctable">
                                 <tr align="center">
                                     <td class="bibcirctableheader">%s
             """ % (CFG_SITE_URL, borrower_id, _("Search item by"))
 
         if f == 'barcode':
             out += """
                                 <input type="radio" name="f" value="">%s
                                 <input type="radio" name="f" value="barcode" checked>%s
                                 <input type="radio" name="f" value="author">%s
                                 <input type="radio" name="f" value="title">%s
               """ % (_("any field"), _("barcode"), _("author"), _("title"))
 
         elif f == 'author':
             out += """
                                 <input type="radio" name="f" value="">%s
                                 <input type="radio" name="f" value="barcode">%s
                                 <input type="radio" name="f" value="author" checked>%s
                                 <input type="radio" name="f" value="title">%s
               """ % (_("any field"), _("barcode"), _("author"), _("title"))
 
         elif f == 'title':
             out += """
                                 <input type="radio" name="f" value="">%s
                                 <input type="radio" name="f" value="barcode">%s
                                 <input type="radio" name="f" value="author">%s
                                 <input type="radio" name="f" value="title" checked>%s
               """ % (_("any field"), _("barcode"), _("author"), _("title"))
 
         else:
             out += """
                                 <input type="radio" name="f" value="" checked>%s
                                 <input type="radio" name="f" value="barcode">%s
                                 <input type="radio" name="f" value="author">%s
                                 <input type="radio" name="f" value="title">%s
               """ % (_("any field"), _("barcode"), _("author"), _("title"))
 
         out += """
                                         <br />
                                         <br />
                                     </td>
                                 </tr>
                                 <tr align="center">
                                     <td>
                                         <input type="text" size="50" name="p" value='%s'
                                             style='border: 1px solid #cfcfcf'>
                                     </td>
                                 </tr>
                             </table>
                             <br />
                             <table class="bibcirctable">
                                 <tr align="center">
                                     <td>
                                         <input type=button value='%s' onClick="history.go(-1)"
                                             class="formbutton">
                                         <input type="submit" value='%s' name='search'
                                             class="formbutton">
                                     </td>
                                 </tr>
                             </table>
                         </form>
         """ % (p or '', _("Back"), _("Search"))
 
         if result:
             out += """
             <br />
                         <form name="form2"
                             action="%s/admin2/bibcirculation/create_new_request_step2"
                             method="get" >
                             <table class="bibcirctable">
                                 <tr width="200">
                                     <td align="center">
                                         <select name="recid" size="12" style='border: 1px
                                             solid #cfcfcf; width:77%%'>
 
               """ % (CFG_SITE_URL)
             for recid in result:
                 out += """
                        <option value ='%s'>%s
 
                        """ % (recid, book_title_from_MARC(recid))
 
             out += """
                                         </select>
                                     </td>
                                 </tr>
                             </table>
                             <table class="bibcirctable">
                                 <tr>
                                     <td ALIGN="center">
                                         <input type="submit" value='%s' class="formbutton">
                                     </td>
                                 </tr>
                             </table>
                             <input type=hidden name=borrower_id value="%s">
                         </form>
                     """ % (_("Select item"), borrower_id)
 
         out += """
                     </td>
                     <td width="200" align="center" valign="top">
                     <td align="center" valign="top">
                         <table class="bibcirctable">
                             <tr>
                                 <td class="bibcirctableheader">%s</td>
                             </tr>
                         </table>
                         </form>
                            <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                              <tr>
                                <th width="100">%s</th>
                                <td>%s</td>
                              </tr>
                              <tr>
                                <th width="100">%s</th>
                                <td>%s</td>
                              </tr>
                              <tr>
                                <th width="100">%s</th>
                                <td>%s</td>
                              </tr>
                              <tr>
                                <th width="100">%s</th>
                                <td>%s</td>
                              </tr>
                              <tr>
                                <th width="100">%s</th>
                                <td>%s</td>
                              </tr>
                              <tr>
                                <th width="100">%s</th>
                                <td>%s</td>
                              </tr>
                         </table>
                     </td>
                 </tr>
 
             <br />
 
             """% (_("Borrower details"),
                   id_string, display_id,
                   _("Name"), name,
                   _("Address"), address,
                   _("Mailbox"), mailbox,
                   _("Email"), email,
                   _("Phone"), phone)
 
 
         out += """
             </table>
             <br />
             <br />
             <br />
             <br />
             <br />
 
               </div>
 
 
               """
 
         return out
 
     def tmpl_create_new_request_step2(self, user_info, holdings_information,
                                       recid, ln=CFG_SITE_LANG):
         """
         @param borrower_id: identify the borrower. Primary key of crcBORROWER.
         @type borrower_id: int
 
         @param holdings_information: information about holdings
         @type holdings_information: list
 
         @param recid: identify the record. Primary key of bibrec.
         @type recid: int
         """
 
         _ = gettext_set_language(ln)
 
         if not holdings_information:
             return _("This item has no holdings.")
 
         out = load_menu(ln)
 
         out += """
                  <div class="bibcircbottom">
                  <br />
                  <br />
                  <br />
                    <table class="bibcirctable">
                    <tr>
                    <td class="bibcirctableheader">%s</td>
                    <td class="bibcirctableheader">%s</td>
                    <td class="bibcirctableheader" align="center">%s</td>
                    <td class="bibcirctableheader" align="center">%s</td>
                    <td class="bibcirctableheader" align="center">%s</td>
                    <td class="bibcirctableheader" align="center">%s</td>
                    <td class="bibcirctableheader "align="center">%s</td>
                    <td class="bibcirctableheader "align="center">%s</td>
                    <td class="bibcirctableheader"></td>
                    </tr>
                    """ % (_("Barcode"), _("Library"), _("Collection"),
                           _("Location"), _("Description"), _("Loan period"),
                           _("Status"), _("Due date"))
 
         for (barcode, library, collection, location, description, loan_period,
              status, due_date) in holdings_information:
             out += """
                      <tr onMouseOver="this.className='highlight'" onmouseout="this.className='normal'">
                           <td class="bibcirccontent">%s</td>
                           <td class="bibcirccontent">%s</td>
                           <td class="bibcirccontent" align="center">%s</td>
                           <td class="bibcirccontent" align="center">%s</td>
                           <td class="bibcirccontent" align="center">%s</td>
                           <td class="bibcirccontent" align="center">%s</td>
                           <td class="bibcirccontent" align="center">%s</td>
                           <td class="bibcirccontent" align="center">%s</td>
                           <td class="bibcirccontent" align="right">
                           <input type=button onClick="location.href='%s/admin2/bibcirculation/place_new_request_step2?ln=%s&barcode=%s&recid=%s&user_info=%s,%s,%s,%s,%s,%s,%s'"
                           value='%s' class="formbutton"></td>
                      </tr>
 
                 """ % (barcode, library, collection, location,
                        description, loan_period, status, due_date,
                        CFG_SITE_URL, ln, barcode, recid, user_info[0],
                        user_info[1], user_info[2], user_info[3],
                        user_info[4], user_info[5], user_info[6],
                        _("Request"))
 
         out += """
            </table>
            <br />
            <br />
            <br />
            </div>
            """
 
         return out
 
     def tmpl_create_new_request_step3(self, borrower_id, barcode, recid,
                                       ln=CFG_SITE_LANG):
         """
         @param borrower_id: identify the borrower. Primary key of crcBORROWER.
         @type borrower_id: int
 
         @param barcode: identify the item. Primary key of crcITEM.
         @type barcode: string
 
         @param recid: identify the record. Primary key of bibrec.
         @type recid: int
 
         @param ln: language
         """
 
         _ = gettext_set_language(ln)
 
         out = """ """
 
         out += load_menu(ln)
 
         out += """
 
         <script type="text/javascript" language='JavaScript' src="%s/js/jquery/jquery.ui.datepicker.min.js"></script>
 
         <form name="request_form" action="%s/admin2/bibcirculation/create_new_request_step4"
               method="post" >
         <div class="bibcircbottom">
         <br />
         <br />
         <br />
         <table class="bibcirctable_contents">
           <tr class="bibcirctableheader" align='center'>
             <td>%s</td>
           </tr>
         </table>
         <br />
         <table class="bibcirctable_contents">
           <tr>
             <td width="90" class="bibcirctableheader" align='right'>%s</td>
             <td align='left'>
 
                 <script type="text/javascript">
                     $(function(){
                         $("#date_picker1").datepicker({dateFormat: 'yy-mm-dd', showOn: 'button', buttonImage: "%s/img/jquery/calendar.gif", buttonImageOnly: true});
                     });
                 </script>
                 <input type="text" size="12" id="date_picker1" name="period_from" value="%s" style='border: 1px solid #cfcfcf'>
 
             </td>
           </tr>
         </table>
 
         <table class="bibcirctable_contents">
           <tr>
             <td width="90" class="bibcirctableheader" align='right'>%s</td>
             <td align='left'>
 
                 <script type="text/javascript">
                     $(function(){
                         $("#date_picker2").datepicker({dateFormat: 'yy-mm-dd', showOn: 'button', buttonImage: "%s/img/jquery/calendar.gif", buttonImageOnly: true});
                     });
                 </script>
                 <input type="text" size="12" id="date_picker2" name="period_to" value="%s" style='border: 1px solid #cfcfcf'>
 
             </td>
           </tr>
         </table>
         <br />
         <br />
        """ % (CFG_SITE_URL, CFG_SITE_URL,
               _("Enter the period of interest"),
             _("From:  "), CFG_SITE_URL,
             datetime.date.today().strftime('%Y-%m-%d'),
             _("To:  "), CFG_SITE_URL,
     (datetime.date.today() + datetime.timedelta(days=365)).strftime('%Y-%m-%d'))
 
         out += """
         <table class="bibcirctable_contents">
           <tr>
             <td align="center">
               <input type=hidden name=barcode value='%s'>
               <input type=hidden name=borrower_id value='%s'>
               <input type=hidden name=recid value='%s'>
               <input type=button value="%s" onClick="history.go(-1)" class="formbutton">
               <input type="submit" name="submit_button" value="%s" class="formbutton">
             </td>
           </tr>
         </table>
         <br />
         <br />
         </form>
         </div>
 
         """ % (barcode, borrower_id, recid, _("Back"), _('Confirm'))
 
         return out
 
     def tmpl_create_new_request_step4(self, ln=CFG_SITE_LANG):
         """
         Last step of the request procedure.
 
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         out = """ """
 
         out += load_menu(ln)
 
 
         out += """
         <div class="bibcircbottom">
         <br />
         <br />
         <table class="bibcirctable">
         <tr>
         <td class="bibcirccontent" width="30">%s</td>
         </tr>
         </table>
         <br />
         <br />
         <table class="bibcirctable">
         <td>
             <input type=button
                 onClick="location.href='%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s'"
                 value='%s' class='formbutton'>
         </td>
         </table>
         <br />
         <br />
         </div>
 
         """ % (_("A new request has been registered with success."),
                CFG_SITE_URL, ln, _("Back to home"))
 
         return out
 
     def tmpl_place_new_request_step1(self, result, key, string, barcode,
                                      recid, infos, ln=CFG_SITE_LANG):
         """
         @param result: borrower's information
         @type result: list
 
         @param key: field (name, email, etc...)
         @param key: string
 
         @param string: pattern
         @type string: string
 
         @param barcode: identify the item. Primary key of crcITEM.
         @type barcode: string
 
         @param recid: identify the record. Primary key of bibrec
         @type recid: int
 
         @param infos: informations
         @type infos: list
 
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         (book_title, book_year, book_author,
          book_isbn, book_editor) = book_information_from_MARC(recid)
 
         if book_isbn:
             book_cover = get_book_cover(book_isbn)
         else:
             book_cover = "%s/img/book_cover_placeholder.gif" % (CFG_SITE_URL)
 
         out = self.tmpl_infobox(infos, ln)
 
         out += load_menu(ln)
 
         out += """
         <style type="text/css"> @import url("/img/tablesorter.css"); </style>
         <div class="bibcircbottom">
         <br />
         <br />
                 <table class="bibcirctable">
                   <tr>
                     <td width="500" valign='top'>
                         <table class="bibcirctable">
                             <tr>
                                 <td class="bibcirctableheader" width="10">%s</td>
                             </tr>
                         </table>
 
                       <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                       </table>
                      </td>
                      <td width="200" align='center' valign='top'>
                        <table>
                          <tr>
                            <td>
                              <img style='border: 1px solid #cfcfcf' src="%s" alt="Book Cover"/>
                            </td>
                          </tr>
                        </table>
                      </td>
                      """ % (_("Item details"),
                             _("Name"), book_title,
                             _("Author(s)"), book_author,
                             _("Year"), book_year,
                             _("Publisher"), book_editor,
                             _("ISBN"), book_isbn,
                             _("Barcode"), barcode,
                             str(book_cover))
 
         out += """
         <td valign='top' align='center'>
         <form name="step1_form1"
               action="%s/admin2/bibcirculation/place_new_request_step1"
               method="get" >
         <input type=hidden name=barcode value='%s'>
         <input type=hidden name=recid value='%s'>
         <table>
 
             """ % (CFG_SITE_URL, barcode, recid)
 
         if CFG_CERN_SITE == 1:
 
             out += """
                  <tr>
                    <td class="bibcirctableheader" align="center">%s
                    """ % (_("Search user by"))
 
             if key == 'email':
                 out += """
                    <input type="radio" name="key" value="ccid">%s
                    <input type="radio" name="key" value="name">%s
                    <input type="radio" name="key" value="email" checked>%s
                    """ % (_("ccid"), _("name"), _("email"))
 
             elif key == 'name':
                 out += """
                    <input type="radio" name="key" value="ccid">%s
                    <input type="radio" name="key" value="name" checked>%s
                    <input type="radio" name="key" value="email">%s
                    """ % (_("ccid"), _("name"), _("email"))
 
             else:
                 out += """
                    <input type="radio" name="key" value="ccid" checked>%s
                    <input type="radio" name="key" value="name">%s
                    <input type="radio" name="key" value="email">%s
                    """ % (_("ccid"), _("name"), _("email"))
 
         else:
             out += """
                  <tr>
                    <td class="bibcirctableheader" align="center">%s
                    """ % (_("Search borrower by"))
 
             if key == 'email':
                 out += """
                    <input type="radio" name="key" value="id">%s
                    <input type="radio" name="key" value="name">%s
                    <input type="radio" name="key" value="email" checked>%s
                    """ % (_("ccid"), _("name"), _("email"))
 
             elif key == 'id':
                 out += """
                    <input type="radio" name="key" value="id" checked>%s
                    <input type="radio" name="key" value="name">%s
                    <input type="radio" name="key" value="email">%s
                    """ % (_("ccid"), _("name"), _("email"))
 
             else:
                 out += """
                    <input type="radio" name="key" value="id">%s
                    <input type="radio" name="key" value="name" checked>%s
                    <input type="radio" name="key" value="email">%s
                    """ % (_("ccid"), _("name"), _("email"))
 
         out += """
                     <br><br>
                     </td>
                     </tr>
                     <tr>
                     <td align="center">
                     <input type="text" size="40" id="string" name="string"
                            value='%s'  style='border: 1px solid #cfcfcf'>
                     </td>
                     </tr>
                     <tr>
                     <td align="center">
                     <br>
                     <input type="submit" value="%s" class="formbutton">
                     </td>
                     </tr>
                 </table>
           </form>
         """ % (string or '', _("Search"))
 
         if result:
             out += """
             <br />
             <form name="step1_form2"
                   action="%s/admin2/bibcirculation/place_new_request_step2"
                   method="get" >
             <input type=hidden name=barcode value='%s'>
             <input type=hidden name=recid value='%s'>
             <table class="bibcirctable">
                 <tr width="200">
                     <td align="center">
                         <select name="user_info"
                                 size="8"
                                 style='border: 1px solid #cfcfcf; width:40%%'>
             """ % (CFG_SITE_URL, barcode, recid)
 
             for (borrower_id, ccid, name, email,
                  phone, address, mailbox) in result:
                 out += """
                        <option value ='%s,%s,%s,%s,%s,%s,%s'>%s
                        """ % (borrower_id, ccid, name, email, phone,
                               address, mailbox, name)
 
             out += """
                     </select>
                     </td>
                     </tr>
                     </table>
                     <table class="bibcirctable">
                     <tr>
                         <td ALIGN="center">
                         <input type="submit" value='%s' class="formbutton">
                         </td>
                     </tr>
                     </table>
                     </form>
                     """ % (_("Select user"))
 
         out += """
                   </td>
                 </tr>
               </table>
               <br />
               <br />
               <br />
               <br />
               </div>
               """
 
         return out
 
     def tmpl_place_new_request_step2(self, barcode, recid, user_info, infos,
                                      ln=CFG_SITE_LANG):
         """
         @param barcode: identify the item. Primary key of crcITEM.
         @type barcode: string
 
         @param recid: identify the record. Primary key of bibrec
         @type recid: int
 
         @param user_info: user's informations
         @type user_info: tuple
 
         @param infos: informations
         @type infos: list
 
         @param ln: language of the page
         """
 
         (book_title, book_year, book_author,
          book_isbn, book_editor) = book_information_from_MARC(recid)
 
         if book_isbn:
             book_cover = get_book_cover(book_isbn)
         else:
             book_cover = "%s/img/book_cover_placeholder.gif" % (CFG_SITE_URL)
 
         (borrower_id, ccid, name, email, phone, address, mailbox) = user_info
 
         _ = gettext_set_language(ln)
 
         out = self.tmpl_infobox(infos, ln)
 
         out += load_menu(ln)
 
         out += """
             <style type="text/css"> @import url("/img/tablesorter.css"); </style>
             <div class="bibcircbottom">
             <form name="step2_form" action="%s/admin2/bibcirculation/place_new_request_step3"
                   method="post" >
             <input type=hidden name=barcode value='%s'>
             <input type=hidden name=recid value='%s'>
             <input type=hidden name=user_info value="%s,%s,%s,%s,%s,%s,%s">
             <br />
 
                 <table class="bibcirctable">
                     <tr>
                         <td width="500" valign="top">
                             <table class="bibcirctable">
                                 <tr class="bibcirctableheader">
                                     <td>%s</td>
                                 </tr>
                             </table>
                             <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                                 <tr>
                                    <th width="100">%s</th>
                                    <td>%s</td>
                                 </tr>
                                 <tr>
                                    <th width="100">%s</th>
                                    <td>%s</td>
                                 </tr>
                                 <tr>
                                    <th width="100">%s</th>
                                    <td>%s</td>
                                 </tr>
                                 <tr>
                                    <th width="100">%s</th>
                                    <td>%s</td>
                                 </tr>
                                 <tr>
                                    <th width="100">%s</th>
                                    <td>%s</td>
                                 </tr>
                                 <tr>
                                    <th width="100">%s</th>
                                    <td>%s</td>
                                 </tr>
                             </table>
                         </td>
                         <td width="200" align='center' valign='top'>
                             <table>
                                 <tr>
                                     <td>
                                         <img style='border: 1px solid #cfcfcf' src="%s" alt="Book Cover"/>
                                     </td>
                                 </tr>
                             </table>
                         </td>
 
 
               <br />
               """ % (CFG_SITE_URL, barcode, recid,
                      borrower_id, ccid, name, email, phone, address, mailbox,
                      _("Item details"),
                      _("Name"), book_title,
                      _("Author(s)"), book_author,
                      _("Year"), book_year,
                      _("Publisher"), book_editor,
                      _("ISBN"), book_isbn,
                      _("Barcode"), barcode,
                      str(book_cover))
 
         out += """
               <td align='center' valign="top">
               <table class="bibcirctable">
                 <tr class="bibcirctableheader">
                     <td>%s</td>
                 </tr>
               </table>
               <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                 <tr>
                     <th width="100">%s</th>
                     <td>%s</td>
                 </tr>
                 <tr>
                     <th width="100">%s</th>
                     <td>%s</td>
                 </tr>
                 <tr>
                     <th width="100">%s</th>
                     <td>%s</td>
                 </tr>
                 <tr>
                     <th width="100">%s</th>
                     <td>%s</td>
                  </tr>
                   <tr>
                     <th width="100">%s</th>
                     <td>%s</td>
                  </tr>
                   <tr>
                     <th width="100">%s</th>
                     <td>%s</td>
                  </tr>
                 </table>
                 </td>
                 </table>
                 """ % (_("Borrower details"),
                        _("ID"), ccid,
                        _("Name"), name,
                        _("Address"), address,
                        _("Mailbox"), mailbox,
                        _("Email"), email,
                        _("Phone"), phone)
 
         out += """
 
                 <script type="text/javascript" language='JavaScript' src="%s/js/jquery/jquery.ui.datepicker.min.js"></script>
 
 
                 <table class="bibcirctable">
                   <tr class="bibcirctableheader">
                     <td>%s</td>
                   </tr>
                 </table>
                 <table class="tablesorterborrower" border="0" cellpadding="0" cellspacing="1">
                   <tr>
                     <th width="100">%s</th>
                     <td>
 
                     <script type="text/javascript">
                     $(function(){
                         $("#date_picker1").datepicker({dateFormat: 'yy-mm-dd', showOn: 'button', buttonImage: "%s/img/jquery/calendar.gif", buttonImageOnly: true});
                     });
                     </script>
                     <input type="text" size="12" id="date_picker1" name="period_from" value="%s" style='border: 1px solid #cfcfcf'>
 
                     </td>
                   </tr>
                   <tr>
                     <th width="100">%s</th>
                     <td>
 
                     <script type="text/javascript">
                     $(function(){
                         $("#date_picker2").datepicker({dateFormat: 'yy-mm-dd', showOn: 'button', buttonImage: "%s/img/jquery/calendar.gif", buttonImageOnly: true});
                     });
                     </script>
                     <input type="text" size="12" id="date_picker2" name="period_to" value="%s" style='border: 1px solid #cfcfcf'>
 
                     </td>
                   </tr>
                 </table>
                 <br />
                 <br />
                 <table class="bibcirctable">
                 <tr>
                   <td>
                        <input type=button value="%s"
                         onClick="history.go(-1)" class="formbutton">
 
                        <input type="submit"
                        value="%s" class="formbutton">
 
                   </td>
                  </tr>
                 </table>
                 </form>
                 <br />
                 <br />
                 </div>
                 """ % (CFG_SITE_URL,
         _("Enter the period of interest"),
         _("From:  "), CFG_SITE_URL, datetime.date.today().strftime('%Y-%m-%d'),
         _("To:  "), CFG_SITE_URL,
     (datetime.date.today() + datetime.timedelta(days=365)).strftime('%Y-%m-%d'),
         _("Back"), _("Continue"))
 
         return out
 
     def tmpl_place_new_request_step3(self, ln=CFG_SITE_LANG):
         """
         Last step of the request procedure.
         """
 
         _ = gettext_set_language(ln)
 
         out = load_menu(ln)
 
         out += """
         <div class="bibcircbottom">
         <br />
         <br />
         <div class="bibcircinfoboxsuccess">%s</div>
         <br />
         <br />
         <table class="bibcirctable">
         <td>
             <input type=button
                    onClick="location.href='%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s'"
                    value='%s'
                    class='formbutton'>
         </td>
         </table>
         <br />
         <br />
         </div>
 
         """ % (_("A new request has been registered with success."),
                CFG_SITE_URL, ln, _("Back to home"))
 
         return out
 
     def tmpl_place_new_loan_step1(self, result, key, string, barcode,
                                   recid, infos, ln=CFG_SITE_LANG):
         """
         @param result: borrower's information
         @type result: list
 
         @param key: field (name, email, etc...)
         @param key: string
 
         @param string: pattern
         @type string: string
 
         @param barcode: identify the item. Primary key of crcITEM.
         @type barcode: string
 
         @param recid: identify the record. Primary key of bibrec
         @type recid: int
 
         @param infos: informations
         @type infos: list
 
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         (book_title, book_year, book_author,
          book_isbn, book_editor) = book_information_from_MARC(recid)
 
         if book_isbn:
             book_cover = get_book_cover(book_isbn)
         else:
             book_cover = "%s/img/book_cover_placeholder.gif" % (CFG_SITE_URL)
 
         out = self.tmpl_infobox(infos, ln)
 
         out += load_menu(ln)
 
         out += """
         <style type="text/css"> @import url("/img/tablesorter.css"); </style>
         <div class="bibcircbottom">
         <br />
           <table class="bibcirctable">
                   <tr>
                      <td class="bibcirctableheader" width="10">%s</td>
                   </tr>
                 </table>
                 <table class="bibcirctable">
                   <tr>
                     <td width="500" valign='top'>
                       <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                       </table>
                      </td>
                      <td width="200" align='center' valign='top'>
                        <table>
                          <tr>
                            <td>
                              <img style='border: 1px solid #cfcfcf' src="%s" alt="Book Cover"/>
                            </td>
                          </tr>
                        </table>
                      </td>
                      """ % (_("Item details"),
                             _("Name"), book_title,
                             _("Author(s)"), book_author,
                             _("Year"), book_year,
                             _("Publisher"), book_editor,
                             _("ISBN"), book_isbn,
                             _("Barcode"), barcode,
                             str(book_cover))
 
         out += """
         <td valign='top' align='center'>
         <form name="step1_form1"
               action="%s/admin2/bibcirculation/place_new_loan_step1"
               method="get" >
         <input type=hidden name=barcode value='%s'>
         <input type=hidden name=recid value='%s'>
         <table>
 
             """ % (CFG_SITE_URL, barcode, recid)
 
         if CFG_CERN_SITE == 1:
 
             out += """
                  <tr>
                    <td class="bibcirctableheader" align="center">%s
                    """ % (_("Search user by"))
 
             if key == 'email':
                 out += """
                    <input type="radio" name="key" value="ccid">%s
                    <input type="radio" name="key" value="name">%s
                    <input type="radio" name="key" value="email" checked>%s
                    """ % (_("ccid"), _("name"), _("email"))
 
             elif key == 'name':
                 out += """
                    <input type="radio" name="key" value="ccid">%s
                    <input type="radio" name="key" value="name" checked>%s
                    <input type="radio" name="key" value="email">%s
                    """ % (_("ccid"), _("name"), _("email"))
 
             else:
                 out += """
                    <input type="radio" name="key" value="ccid" checked>%s
                    <input type="radio" name="key" value="name">%s
                    <input type="radio" name="key" value="email">%s
                    """ % (_("ccid"), _("name"), _("email"))
 
         else:
             out += """
                  <tr>
                    <td class="bibcirctableheader" align="center">%s
                    """ % (_("Search user by"))
 
             if key == 'email':
                 out += """
                    <input type="radio" name="key" value="id">%s
                    <input type="radio" name="key" value="name">%s
                    <input type="radio" name="key" value="email" checked>%s
                    """ % (_("id"), _("name"), _("email"))
 
             elif key == 'id':
                 out += """
                    <input type="radio" name="key" value="id" checked>%s
                    <input type="radio" name="key" value="name">%s
                    <input type="radio" name="key" value="email">%s
                    """ % (_("id"), _("name"), _("email"))
 
             else:
                 out += """
                    <input type="radio" name="key" value="id">%s
                    <input type="radio" name="key" value="name" checked>%s
                    <input type="radio" name="key" value="email">%s
                    """ % (_("id"), _("name"), _("email"))
 
         out += """
                     <br><br>
                     </td>
                     </tr>
                     <tr>
                     <td align="center">
                     <input type="text" size="40" id="string" name="string"
                            value='%s'  style='border: 1px solid #cfcfcf'>
                     </td>
                     </tr>
                     <tr>
                     <td align="center">
                     <br>
                     <input type="submit" value="%s" class="formbutton">
                     </td>
                     </tr>
                 </table>
           </form>
         """ % (string or '', _("Search"))
 
 #<input type=hidden name=recid value='%s'>
         if result:
             out += """
                 <script type="text/javascript">
                     function checkform(form){
                       if (form.user_id.value == ""){
                         alert("%s");
                         return false;
                       }
                       else{
                         return true;
                       }
                     }
                 </script>
                 """ % (_("Please select one borrower to continue."))
 
             out += """
             <br />
             <form name="step1_form2" action="%s/admin2/bibcirculation/loan_on_desk_step3"
                   method="get" onsubmit="return checkform(this);">
             <input type=hidden name=barcode value='%s'>
 
             <table class="bibcirctable">
               <tr width="200">
                 <td align="center">
                   <select name="user_id" size="8" style='border: 1px solid #cfcfcf;'>
             """ % (CFG_SITE_URL, barcode)
 
             for brw in result:
                 borrower_id = brw[0]
                 name = brw[2]
                 out += """
                        <option value ="%s">%s
                        """ % (borrower_id, name)
 
             out += """
                     </select>
                     </td>
                     </tr>
                     </table>
                     <table class="bibcirctable">
                     <tr>
                         <td ALIGN="center">
                         <input type="submit" value='%s' class="formbutton">
                         </td>
                     </tr>
                     </table>
                     </form>
                     """ % (_("Select user"))
 
         out += """
                   </td>
                 </tr>
               </table>
               <br />
               <br />
               <br />
               <br />
               </div>
               """
 
         return out
 
     def tmpl_place_new_loan_step2(self, barcode, recid, user_info,
                                   ln=CFG_SITE_LANG):
         """
         @param barcode: identify the item. Primary key of crcITEM.
         @type barcode: string
 
         @param recid: identify the record. Primary key of bibrec.
         @type recid: int
 
         @param user_info: user's informations
         @type user_info: tuple
 
         @param ln: language of the page
         """
 
         (book_title, book_year, book_author, book_isbn,
          book_editor) = book_information_from_MARC(recid)
 
         if book_isbn:
             book_cover = get_book_cover(book_isbn)
         else:
             book_cover = "%s/img/book_cover_placeholder.gif" % (CFG_SITE_URL)
 
         (_borrower_id, ccid, name, email, phone,
          address, mailbox) = user_info.split(',')
 
         _ = gettext_set_language(ln)
 
         out = """
         """
         out += load_menu(ln)
 
         out += """
             <style type="text/css"> @import url("/img/tablesorter.css"); </style>
             <div class="bibcircbottom">
             <form name="step2_form" action="%s/admin2/bibcirculation/place_new_loan_step3"
                   method="post" >
             <input type=hidden name=barcode value='%s'>
             <input type=hidden name=recid value='%s'>
             <input type=hidden name=email value='%s'>
               <br />
               <table class="bibcirctable">
                   <tr>
                      <td class="bibcirctableheader" width="10">%s</td>
                   </tr>
                 </table>
 
                 <table class="bibcirctable">
                  <tr valign='top'>
                   <td width="400">
                     <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                      <tr>
                        <th width="100">%s</th>
                        <td>%s</td>
                      </tr>
                      <tr>
                        <th width="100">%s</th>
                        <td>%s</td>
                      </tr>
                      <tr>
                        <th width="100">%s</th>
                        <td>%s</td>
                      </tr>
                      <tr>
                        <th width="100">%s</th>
                        <td>%s</td>
                      </tr>
                      <tr>
                        <th width="100">%s</th>
                        <td>%s</td>
                      </tr>
                      <tr>
                        <th width="100">%s</th>
                        <td>%s</td>
                      </tr>
                    </table>
                  </td>
                  <td>
                    <img style='border: 1px solid #cfcfcf' src="%s" alt="Book Cover"/>
                  </td>
                </tr>
               </table>
               <br />
               """ % (CFG_SITE_URL, barcode,
                      recid, email,
                      _("Item details"),
                      _("Name"), book_title,
                      _("Author(s)"), book_author,
                      _("Year"), book_year,
                      _("Publisher"), book_editor,
                      _("ISBN"), book_isbn,
                      _("Barcode"), barcode,
                      str(book_cover))
 
         out += """
               <br />
               <table class="bibcirctable">
                 <tr>
                   <td class="bibcirctableheader" width="10">%s</td>
                 </tr>
               </table>
               <table class="tablesorterborrower" border="0" cellpadding="0" cellspacing="1">
                 <tr>
                     <th width="70">%s</th>
                     <td>%s</td>
                 </tr>
                 <tr>
                     <th width="70">%s</th>
                     <td>%s</td>
                 </tr>
                 <tr>
                     <th width="70">%s</th>
                     <td>%s</td>
                 </tr>
                 <tr>
                     <th width="70">%s</th>
                     <td>%s</td>
                  </tr>
                  <tr>
                     <th width="70">%s</th>
                     <td>%s</td>
                  </tr>
                  <tr>
                     <th width="70">%s</th>
                     <td>%s</td>
                  </tr>
                 </table>
                 <br />
                 """ % (_("Borrower details"),
                        _("ID"), ccid,
                        _("Name"), name,
                        _("Address"), address,
                        _("Mailbox"), mailbox,
                        _("Email"), email,
                        _("Phone"), phone)
 
         out += """
 
                 <script type="text/javascript" language='JavaScript' src="%s/js/jquery/jquery.ui.datepicker.min.js"></script>
 
                 <table class="bibcirctable">
                   <tr class="bibcirctableheader">
                     <td>%s</td>
                   </tr>
                 </table>
                 <table class="tablesorterborrower" border="0" cellpadding="0" cellspacing="1">
                   <tr>
                     <th width="70">%s</th>
                     <td>%s</td>
                   </tr>
                   <tr>
                     <th width="70">%s</th>
                     <td align='left'>
                     <script type="text/javascript">
                     $(function(){
                         $("#date_picker1").datepicker({dateFormat: 'yy-mm-dd', showOn: 'button', buttonImage: "%s/img/jquery/calendar.gif", buttonImageOnly: true});
                     });
                 </script>
                 <input type="text" size="12" id="date_picker1"
                        name="due_date" value="%s" style='border: 1px solid #cfcfcf'>
                     </td>
                   </tr>
                 </table>
                 <br />
                 <br />
                 <table class="tablesorterborrower" border="0" cellpadding="0" cellspacing="1">
                   <tr>
                     <th>%s</th>
                   </tr>
                   <tr>
                     <td>
                         <textarea name='notes' rows="5" cols="57"
                                   style='border: 1px solid #cfcfcf'></textarea>
                     </td>
                   </tr>
                   <tr>
                     <td>%s</td>
                   </tr>
                 </table>
                 <br />
                 <br />
                 <table class="bibcirctable">
                 <tr>
                   <td>
                        <input type=button value="%s"
                               onClick="history.go(-1)"
                               class="formbutton">
                        <input type="submit"
                               value="%s"
                               class="formbutton">
                   </td>
                  </tr>
                 </table>
                 </form>
                 <br />
                 <br />
                 </div>
     """ % (CFG_SITE_URL,
         _("Loan information"),
         _("Loan date"), datetime.date.today().strftime('%Y-%m-%d'),
         _("Due date"), CFG_SITE_URL, renew_loan_for_X_days(barcode),
         _("Write notes"),
         _("This note will be associate to this new loan, not to the borrower."),
         _("Back"), _("Continue"))
 
         return out
 
     def tmpl_order_new_copy_step1(self, recid, list_of_vendors,
                                   libraries, ln=CFG_SITE_LANG):
         """
         @param recid: identify the record. Primary key of bibrec.
         @type recid: int
 
         @param list_of_vendors: list with all the vendores
         @type list_of_vendors: list
 
         @param libraries: all libraries
         @type libraries: list
 
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         out = """
         """
         out += load_menu(ln)
 
         (book_title, book_year, book_author,
          book_isbn, book_editor) = book_information_from_MARC(recid)
 
         if book_isbn:
             book_cover = get_book_cover(book_isbn)
         else:
             book_cover = "%s/img/book_cover_placeholder.gif" % (CFG_SITE_URL)
 
         out += """
            <style type="text/css"> @import url("/img/tablesorter.css"); </style>
            <script type="text/javascript" src="/js/jquery/jquery.validate.js"></script>
            <script>
              $(document).ready(function(){
                $('#order_new_copy_step1_form').validate();
              });
            </script>
            <style type="text/css">
            label { width: 10em; float: left; }
            label.error { float: none; color: red; padding-left: .5em; vertical-align: top; }
            p { clear: both; }
            .submit { margin-left: 12em; }
            em { font-weight: bold; padding-right: 1em; vertical-align: top; }
            </style>
            <form name="order_new_copy_step1_form" action="%s/admin2/bibcirculation/order_new_copy_step2" method="get" >
            <div class="bibcircbottom">
              <br />
              <table class="bibcirctable">
                <tr>
                  <td class="bibcirctableheader" width="10">%s</td>
                </tr>
                </table>
                <table class="bibcirctable">
                  <tr valign='top'>
                    <td width="400"><input type=hidden name=recid value='%s'>
                     <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      </table>
                      </td>
                      <td class="bibcirccontent"><img style='border: 1px solid #cfcfcf' src="%s" alt="Book Cover"/></td>
                      </tr>
               </table>
 
            <br />
 
            """ % (CFG_SITE_URL,
                    _("Item details"),
                    recid,
                    _("Name"),
                    book_title,
                    _("Author(s)"),
                    book_author,
                    _("Year"),
                    book_year,
                    _("Publisher"),
                    book_editor,
                    _("ISBN"),
                    book_isbn,
                    str(book_cover))
 
         out += """
 
         <script type="text/javascript" language='JavaScript' src="%s/js/jquery/jquery.ui.datepicker.min.js"></script>
 
              <table class="bibcirctable">
                 <tr>
                      <td class="bibcirctableheader">%s</td>
                 </tr>
              </table>
              <table class="tablesortermedium" border="0" cellpadding="0" cellspacing="1">
              <tr>
                <th width="100">%s</th>
                <td>
                  <input class="required" type="text" size="20" name="barcode" style='border: 1px solid #cfcfcf' />
                  <em>*</em>
                </td>
              </tr>
              <tr>
                <th width="100">%s</th>
                  <td>
                    <select name="vendor_id"  style='border: 1px solid #cfcfcf'>
 
                 """ % (CFG_SITE_URL,
                        _("Order details"), _("Barcode"),  _("Vendor"))
 
         for(vendor_id, name) in list_of_vendors:
             out += """<option value ="%s">%s</option>""" % (vendor_id, name)
 
         today = datetime.date.today()
         gap = datetime.timedelta(days=14)
         more_2_weeks = (today + gap).strftime('%Y-%m-%d')
 
         out += """
                     </select>
                     </td>
                 </tr>
                 <tr>
                     <th width="100">%s</th>
                     <td>
                     <input type="text"
                            style='border: 1px solid #cfcfcf'
                            size=12
                            name="cost">
                         <select name="currency"
                               style='border: 1px solid #cfcfcf'>
                             <option value ="EUR">EUR</option>
                             <option value ="CHF">CHF</option>
                             <option value ="USD">USD</option>
                         </select>
                     </td>
                 </tr>
                 """ % (_("Price"))
         out += """
                 <tr>
                     <th width="100">%s</th>
                     <td>
                         <select name="status"
                                 style='border: 1px solid #cfcfcf'>
                             <option value="%s">%s</option>
                             <option value="%s">%s</option>
                             <option value="%s">%s</option>
                         </select>
                     </td>
                 </tr>
                 """ % (_("Status"),
                          CFG_BIBCIRCULATION_ITEM_STATUS_ON_ORDER,
                        _(CFG_BIBCIRCULATION_ITEM_STATUS_ON_ORDER),
                          CFG_BIBCIRCULATION_ITEM_STATUS_CANCELLED,
                        _(CFG_BIBCIRCULATION_ITEM_STATUS_CANCELLED),
                          CFG_BIBCIRCULATION_ITEM_STATUS_NOT_ARRIVED,
                        _(CFG_BIBCIRCULATION_ITEM_STATUS_NOT_ARRIVED))
         out += """
                 <tr>
                 <th width="100">%s</th>
                     <td>
                         <script type="text/javascript">
                         $(function(){
                             $("#date_picker1").datepicker({dateFormat: 'yy-mm-dd', showOn: 'button', buttonImage: "%s/img/jquery/calendar.gif", buttonImageOnly: true});
                         });
                         </script>
                         <input type="text" size="12" id="date_picker1"
                                name="order_date" value="%s" style='border: 1px solid #cfcfcf'>
                     </td>
                 </tr>
                 <tr>
                 <th width="100">%s</th>
                     <td>
 
                        <script type="text/javascript">
                         $(function(){
                             $("#date_picker2").datepicker({dateFormat: 'yy-mm-dd', showOn: 'button', buttonImage: "%s/img/jquery/calendar.gif", buttonImageOnly: true});
                         });
                         </script>
                         <input type="text" size="12" id="date_picker2"
                                name="expected_date" value="%s" style='border: 1px solid #cfcfcf'>
 
                     </td>
                 </tr>
                 <tr>
                   <th width="100">%s</th>
                   <td>
                     <select name="library_id" style='border: 1px solid #cfcfcf'>
 
                 """ % (_("Order date"), CFG_SITE_URL, today,
                        _("Expected date"), CFG_SITE_URL, more_2_weeks,
                        _("Library"))
 
         for(library_id, name) in libraries:
             out += """<option value ="%s">%s</option>""" % (library_id, name)
 
         out += """
                     </select>
                     </td>
                 </tr>
                 <tr>
                    <th valign="top" width="100">%s</th>
                    <td><textarea name='notes' rows="6" cols="30" style='border: 1px solid #cfcfcf'></textarea></td>
                 </tr>
              </table>
              <br />
              <table class="bibcirctable">
                 <tr>
                   <td>
                        <input type=button value="%s"
                         onClick="history.go(-1)" class="formbutton">
 
                        <input type="submit"
                        value="%s" class="formbutton">
 
                   </td>
                  </tr>
              </table>
              </form>
              <br />
              <br />
              </div>
              """ % (_("Notes"), _("Back"), _("Continue"))
 
         return out
 
     def tmpl_order_new_copy_step2(self, order_info, ln=CFG_SITE_LANG):
         """
         @param order_info: order's informations
         @type order_info: tuple
 
         @param ln: language of the page
         """
 
         (recid, barcode, vendor_id, cost, currency, status,
          order_date, expected_date, library_id, notes) = order_info
 
         (book_title, book_year, book_author,
          book_isbn, book_editor) = book_information_from_MARC(recid)
 
         vendor_name = db.get_vendor_name(vendor_id)
         library_name = db.get_library_name(library_id)
 
         if book_isbn:
             book_cover = get_book_cover(book_isbn)
         else:
             book_cover = "%s/img/book_cover_placeholder.gif" % (CFG_SITE_URL)
 
         _ = gettext_set_language(ln)
 
         out = """
         """
         out += load_menu(ln)
 
         out += """
             <div class="bibcircbottom">
             <style type="text/css"> @import url("/img/tablesorter.css"); </style>
             <form name="step2_form" action="%s/admin2/bibcirculation/order_new_copy_step3" method="get" >
                 <input type=hidden name=order_info value="%s">
               <br />
               <table class="bibcirctable">
                   <tr>
                      <td class="bibcirctableheader" width="10">%s</td>
                   </tr>
                 </table>
 
                 <table class="bibcirctable">
                  <tr valign='top'>
                     <td width="400">
                     <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      </table>
                      </td>
                      <td class="bibcirccontent">
                      <img style='border: 1px solid #cfcfcf' src="%s" alt="Book Cover"/>
                      </td>
                      </tr>
               </table>
               <br />
               """ % (CFG_SITE_URL,
                      order_info,
                      _("Item details"),
                      _("Name"), book_title,
                      _("Author(s)"), book_author,
                      _("Year"), book_year,
                      _("Publisher"), book_editor,
                      _("ISBN"), book_isbn,
                      str(book_cover))
 
         out += """
               <br />
               <table class="bibcirctable">
                   <tr>
                      <td class="bibcirctableheader">%s</td>
                   </tr>
                 </table>
               <table class="tablesortersmall" border="0" cellpadding="0" cellspacing="1">
                 <tr>
                     <th width="100">%s</th>
                     <td>%s</td>
                 </tr>
                 <tr>
                     <th width="100">%s</th>
                     <td>%s</td>
                 </tr>
                 <tr>
                     <th width="100">%s</th>
                     <td>%s %s</td>
                 </tr>
                 <tr>
                     <th width="100">%s</th>
                     <td>%s</td>
                 </tr>
                 <tr>
                     <th width="100">%s</th>
                     <td>%s</td>
                  </tr>
                   <tr>
                     <th width="100">%s</th>
                     <td>%s</td>
                  </tr>
                  <tr>
                     <th width="100">%s</th>
                     <td>%s</td>
                  </tr>
                   <tr>
                     <th width="100">%s</th>
                     <td><i>%s</i></td>
                  </tr>
                 </table>
                 <br />
                 <table class="bibcirctable">
                    <tr>
                     <td>
                        <input type=button value="%s"
                         onClick="history.go(-1)" class="formbutton">
 
                        <input type="submit"
                        value="%s" class="formbutton">
 
                     </td>
                    </tr>
                  </table>
                </form>
                <br />
                <br />
                </div>
                """ % (_("Order details"),
                       _("Barcode"), barcode,
                       _("Vendor"), vendor_name,
                       _("Price"), cost, currency,
                       _("Status"), status,
                       _("Order date"), order_date,
                       _("Expected date"), expected_date,
                       _("Library"), library_name,
                       _("Notes"), notes,
                       _("Back"), _("Continue"))
 
 
         return out
 
     def tmpl_order_new_copy_step3(self, ln=CFG_SITE_LANG):
         """
         Last step of the request procedure.
 
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         out = """ """
 
         out += load_menu(ln)
 
 
         out += """
         <div class="bibcircbottom">
         <br />
         <br />
         <table class="bibcirctable">
         <tr>
         <td class="bibcirccontent" width="30">%s</td>
         </tr>
         </table>
         <br />
         <br />
         <table class="bibcirctable">
         <td>
             <input type=button
                 onClick="location.href='%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s'"
                 value='%s' class='formbutton'>
         </td>
         </table>
         <br />
         <br />
         </div>
 
         """ % (_("A new purchase has been registered with success."),
                CFG_SITE_URL, ln, _("Back to home"))
 
 
         return out
 
     def tmpl_ordered_books(self, ordered_books, ln=CFG_SITE_LANG):
         """
         Display list with all ordered books.
 
         @param ordered_books: list with all the ordered books
         @type ordered_books: list
         """
 
         _ = gettext_set_language(ln)
 
         out = """ """
 
         out += load_menu(ln)
 
 
         out += """
         <style type="text/css"> @import url("/img/tablesorter.css"); </style>
         <script src="/js/jquery/jquery.js" type="text/javascript"></script>
         <script src="/js/jquery/jquery.tablesorter.js" type="text/javascript"></script>
         <script type="text/javascript">
            $(document).ready(function() {
               $('#table_orders').tablesorter({widthFixed: true, widgets: ['zebra']})
             });
         </script>
         <div class="bibcircbottom">
         <br />
              <table id="table_orders" class="tablesorter" border="0" cellpadding="0" cellspacing="1">
              <thead>
                     <tr>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                </tr>
                </thead>
                <tbody>
 
          """% (_("Item"),
                _("Vendor"),
                _("Ordered date"),
                _("Price"),
                _("Status"),
                _("Expected date"),
                _("Notes"),
                _("Option(s)"))
 
         for (purchase_id, recid, vendor_id, ordered_date, expected_date,
              price, status, notes) in ordered_books:
 
             vendor_name = db.get_vendor_name(vendor_id)
 
             title_link = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_item_details',
                                     {'recid': recid, 'ln': ln},
                                     (book_title_from_MARC(recid)))
 
 
             no_notes_link = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_purchase_notes',
                                     {'purchase_id': purchase_id},
                                     (_("No notes")))
 
             see_notes_link = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_purchase_notes',
                                     {'purchase_id': purchase_id},
                                     (_("See notes")))
 
             if notes == "":
                 notes_link = no_notes_link
             else:
                 notes_link = see_notes_link
 
             out += """
             <tr  onMouseOver="this.className='highlight'" onmouseout="this.className='normal'">
                  <td class="bibcirccontent">%s</td>
                  <td class="bibcirccontent" align="center">%s</td>
                  <td class="bibcirccontent" align="center">%s</td>
                  <td class="bibcirccontent" align="center">%s</td>
                  <td class="bibcirccontent" align="center">%s</td>
                  <td class="bibcirccontent" align="center">%s</td>
                  <td class="bibcirccontent" align="center">%s</td>
                  <td align="center">
                    <input type=button onClick="location.href='%s/admin2/bibcirculation/ordered_books_details_step1?purchase_id=%s'" onmouseover="this.className='bibcircbuttonover'" onmouseout="this.className='bibcircbutton'"
                        value="%s" class='bibcircbutton'>
                     </td>
             </tr>
 
             """ % (title_link, vendor_name, ordered_date,
                    price, status, expected_date, notes_link,
                    CFG_SITE_URL, purchase_id, _("select"))
 
         out += """
            </tbody>
            </table>
            <br />
            <br />
            </div>
         """
 
         return out
 
     def tmpl_purchase_notes(self, purchase_notes, purchase_id,
                             ln=CFG_SITE_LANG):
         """
         @param purchase_notes: notes about a given purchase
         @type purchase_notes: dictionnary
 
         @param purchase_id: identify the purchase. Primary key of crcPURCHASE
         @type purchase_id: int
         """
 
         _ = gettext_set_language(ln)
 
         if not purchase_notes:
             purchase_notes = {}
         else:
             purchase_notes = eval(purchase_notes)
 
         out = """ """
 
         out += load_menu(ln)
 
         out += """
             <div class="bibcircbottom">
             <form name="borrower_notes"
                   action="%s/admin2/bibcirculation/get_purchase_notes"
                   method="get" >
             <input type=hidden name=purchase_id value='%s'>
             <br />
             <br />
             <table class="bibcirctable">
               <tr>
                 <td class="bibcirctableheader">%s</td>
               </tr>
             </table>
             <table class="bibcirctable">
               <tr>
                 <td>
                   <table class="bibcircnotes">
 
             """ % (CFG_SITE_URL, purchase_id,
                    _("Notes about acquisition"))
 
         key_array = purchase_notes.keys()
         key_array.sort()
 
         for key in key_array:
             delete_note = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_purchase_notes',
                                 {'delete_key': key, 'purchase_id': purchase_id,
                                 'ln': ln}, (_("[delete]")))
 
             out += """<tr class="bibcirccontent">
                         <td class="bibcircnotes" width="160" valign="top"
                             align="center"><b>%s</b></td>
                         <td width="400"><i>%s</i></td>
                         <td width="65" align="center">%s</td>
                       </tr>
 
                       """ % (key, purchase_notes[key], delete_note)
 
         out += """
                   </table>
                 </td>
               </tr>
             </table>
             <br />
             <table class="bibcirctable">
               <tr>
                 <td class="bibcirctableheader">%s</td>
               </tr>
             </table>
             <table class="bibcirctable">
               <tr>
                 <td class="bibcirccontent">
                   <textarea name="library_notes" rows="5" cols="90" style='border: 1px solid #cfcfcf'></textarea>
                 </td>
               </tr>
             </table>
             <br />
             <table class="bibcirctable">
                 <tr>
                     <td>
                        <input type=button
                         onClick="location.href='%s/admin2/bibcirculation/ordered_books?ln=%s'"
                             value="%s" class='formbutton'>
                        <input type="submit" value='%s' class="formbutton">
                     </td>
                 </tr>
              </table>
              <br />
              <br />
              <br />
              </form>
              </div>
         """ % (_("Write new note"),
                CFG_SITE_URL, ln,
                _("Back"),
                _("Confirm"))
 
         return out
 
     def tmpl_register_ill_request_step2(self, user_info, request_info,
                                         ln=CFG_SITE_LANG):
         """
         @param user_info: user's informations
         @type user_info: tuple
 
         @param request_info: request's informations
         @type request_info: tuple
 
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         (recid, period_of_interest_from, period_of_interest_to,
          notes, only_edition) = request_info
 
         (book_title, book_year, book_author,
          book_isbn, book_editor) = book_information_from_MARC(recid)
 
         (borrower_id, ccid, name, email, phone, address, mailbox) = user_info
 
         display_id = borrower_id
         id_string = _("ID")
         if CFG_CERN_SITE == 1:
             display_id = ccid
             id_string = _("CCID")
 
         out = """ """
 
         out += load_menu(ln)
 
         out += """
         <style type="text/css"> @import url("/img/tablesorter.css"); </style>
         <div class=bibcircbottom align="center">
         <br />
         <br />
          <form name="step1_form1"
                action="%s/admin2/bibcirculation/register_ill_request_step3"
                method="post" >
                  <table>
                    <tr align="center">
                      <td class="bibcirctableheader">%s</td>
                      <input type=hidden name=borrower_id value="%s">
                    </tr>
                  </table>
                  <table class="tablesorterborrower" border="0"
                         cellpadding="0" cellspacing="1">
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                       </table>
                       <table>
                          <tr align="center">
                            <td class="bibcirctableheader">%s</td>
                            <input type=hidden name=request_info value="%s">
                         </tr>
                        </table>
                        <table class="tablesorterborrower" border="0"
                               cellpadding="0" cellspacing="1">
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                       </table>
                       <table>
                          <tr align="center">
                            <td class="bibcirctableheader">%s</td>
                         </tr>
                        </table>
                        <table class="tablesorterborrower" border="0"
                               cellpadding="0" cellspacing="1">
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                       </table>
 
                       """ % (CFG_SITE_URL,
                              _("Item details"), borrower_id,
                              _("Title"), book_title,
                              _("Author(s)"), book_author,
                              _("Year"), book_year,
                              _("Publisher"), book_editor,
                              _("ISBN"), book_isbn,
                              _("ILL request details"), request_info,
                              _("Period of interest - From"),
                              period_of_interest_from,
                              _("Period of interest - To"),
                              period_of_interest_to,
                              _("Additional comments"), notes,
                              _("Only this edition"), only_edition,
                              _("Borrower details"),
                              id_string, display_id,
                              _("Name"), name,
                              _("Address"), address,
                              _("Mailbox"), mailbox,
                              _("Email"), email,
                              _("Phone"), phone)
 
         out += """<br />
                   <table class="bibcirctable">
                     <tr align="center">
                       <td>
                         <input type=button value="%s"
                         onClick="history.go(-1)" class="formbutton">
 
                        <input type="submit"
                        value="%s" class="formbutton">
                       </td>
                     </tr>
                 </table>""" % (_("Back"), _("Continue"))
 
 
         return out
 
     def tmpl_register_ill_request_step3(self, ln=CFG_SITE_LANG):
         """
         Last step of the request procedure.
 
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         out = """ """
 
         out += load_menu(ln)
 
 
         out += """
         <div class="bibcircbottom">
         <br />
         <br />
         <table class="bibcirctable">
         <tr>
         <td class="bibcirccontent" width="30">%s</td>
         </tr>
         </table>
         <br />
         <br />
         <table class="bibcirctable">
         <td>
             <input type=button
                     onClick="location.href='%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s'"
                     value='%s'
                     class='formbutton'></td>
         </table>
         <br />
         <br />
         </div>
 
         """ % (_("A new ILL request has been registered with success."),
                CFG_SITE_URL, ln, _("Back to home"))
 
 
         return out
 
     def tmpl_ill_request_with_recid(self, recid, infos, ln=CFG_SITE_LANG):
         """
         @param recid: identify the record. Primary key of bibrec.
         @type recid: int
 
         @param infos: informations
         @type infos: list
         """
 
         _ = gettext_set_language(ln)
 
         out = self.tmpl_infobox(infos, ln)
 
         (book_title, book_year, book_author,
          book_isbn, book_editor) = book_information_from_MARC(recid)
 
         today = datetime.date.today()
         within_six_months = (datetime.date.today() + \
                              datetime.timedelta(days=182)).strftime('%Y-%m-%d')
 
         out += """
            <div align="center">
            <style type="text/css"> @import url("/img/tablesorter.css"); </style>
            <form name="update_item_info_step4_form" action="%s/record/%s/holdings/ill_register_request_with_recid" method="post" >
                 <table class="bibcirctable">
                   <tr align="center">
                     <td><h1 class="headline">%s</h1></td>
                   </tr>
                 </table>
                 <table class="bibcirctable">
                   <tr align="center">
                     <td class="bibcirctableheader" width="10">%s</td>
                   </tr>
                 </table>
                 <table class="tablesorterborrower" border="0" cellpadding="0" cellspacing="1">
                 <input type=hidden name=recid value='%s'>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      </table>
                      <br />
                      <br />
 
            """ % (CFG_SITE_URL, recid,
                    _('Interlibrary loan request for books'),
                    _("Item details"),
                    recid,
                    _("Name"),
                    book_title,
                    _("Author(s)"),
                    book_author,
                    _("Year"),
                    book_year,
                    _("Publisher"),
                    book_editor,
                    _("ISBN"),
                    book_isbn)
 
         out += """
             <style type="text/css"> @import url("/img/tablesorter.css"); </style>
             <script type="text/javascript" language='JavaScript' src="%s/js/jquery/jquery.min.js"></script>
             <script type="text/javascript" language='JavaScript' src="%s/js/ui.datepicker.min.js"></script>
             """% (CFG_SITE_URL, CFG_SITE_URL)
 
         out += """
              <table class="bibcirctable">
                 <tr align="center">
                      <td class="bibcirctableheader">%s</td>
                 </tr>
              </table>
              <table class="tablesorterborrower" border="0" cellpadding="0" cellspacing="1">
                <tr>
                 <th width="150">%s</th>
                 <td>
                     <script type="text/javascript">
                         $(function() {
                             $("#date_picker1").datepicker({dateFormat: 'yy-mm-dd', showOn: 'button', buttonImage: "%s/img/jquery/calendar.gif", buttonImageOnly: true});
                         });
                     </script>
                     <input type="text" size="10" id="date_picker1" name="period_of_interest_from" value="%s" style='border: 1px solid #cfcfcf'>
                 </td>
                </tr>
                 <tr>
                 <th width="150">%s</th>
                 <td>
                     <script type="text/javascript">
                         $(function() {
                             $("#date_picker2").datepicker({dateFormat: 'yy-mm-dd', showOn: 'button', buttonImage: "%s/img/jquery/calendar.gif", buttonImageOnly: true});
                         });
                     </script>
                     <input type="text" size="10" id="date_picker2" name="period_of_interest_to" value="%s" style='border: 1px solid #cfcfcf'>
                 </td>
                 </tr>
                 <tr>
                    <th valign="top" width="150">%s</th>
                    <td><textarea name='additional_comments' rows="6" cols="30"
                    style='border: 1px solid #cfcfcf'></textarea></td>
                 </tr>
               </table>
               <table class="bibcirctable">
                 <tr align="center">
                   <td>
                     <input name="conditions" type="checkbox" value="accepted" />%s</td>
                 </tr>
                 <tr align="center">
                   <td>
                     <input name="only_edition" type="checkbox" value="Yes" />%s</td>
                 </tr>
              </table>
              <br />
              <table class="bibcirctable">
                 <tr align="center">
                   <td>
                        <input type=button value="%s"
                         onClick="history.go(-1)" class="formbutton">
 
                        <input type="submit"
                        value="%s" class="formbutton">
 
                   </td>
                  </tr>
              </table>
              </form>
              <br />
              <br />
              </div>
              """ % (_("ILL request details"),
                     _("Period of interest - From"),
                     CFG_SITE_URL, today,
                     _("Period of interest - To"),
                     CFG_SITE_URL, within_six_months,
                     _("Additional comments"),
                     _("I accept the %(x_url_open)sconditions%(x_url_close)s of the service in particular the return of books in due time.") % {'x_url_open': '<a href="http://library.web.cern.ch/library/Library/ill_faq.html" target="_blank">', 'x_url_close': '</a>'},
                     _("I want this edition only."),
                     _("Back"), _("Continue"))
 
         return out
 
     def tmpl_ill_register_request_with_recid(self, message, ln=CFG_SITE_LANG):
         """
         @param message: information to the borrower
         @type message: string
 
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         out = """
         <br /> <br />
         <table class="bibcirctable">
         <tr>
         <td class="bibcirccontent" width="30">%s</td>
         </tr>
         <tr>
         <td class="bibcirccontent" width="30">%s</td>
         </tr>
         </table>
         <br /> <br />
         <table class="bibcirctable">
         <td><input type=button onClick="location.href='%s'" value='%s' class='formbutton'></td>
         </table>
         <br /> <br />
         """ % (message,
                _("You can see your loans %(here_link)s.") % {'here_link':
                         create_html_link(CFG_SITE_URL + '/yourloans/display',
                                     {'ln': ln}, _("here"))},
                CFG_SITE_URL,
                _("Back to home"))
 
         return out
 
     def tmpl_list_ill_request(self, ill_req, ln=CFG_SITE_LANG):
         """
         @param ill_req: informations about ILL requests
         @type ill_req: tuple
         """
 
         _ = gettext_set_language(ln)
 
         out = """ """
 
         out += load_menu(ln)
 
         out += """
         <style type="text/css"> @import url("/img/tablesorter.css"); </style>
         <script src="/js/jquery/jquery.min.js" type="text/javascript"></script>
         <script src="/js/tablesorter/jquery.tablesorter.js" type="text/javascript"></script>
         <script type="text/javascript">
         $(document).ready(function() {
           $('#table_ill').tablesorter({widthFixed: true, widgets: ['zebra']})
         });
         </script>
         <div class="bibcircbottom">
             <br />
             <table id="table_ill" class="tablesorter" border="0"
                                    cellpadding="0" cellspacing="1">
                 <thead>
                     <tr>
                         <th>%s</th>
                         <th>%s</th>
                         <th>%s</th>
                         <th>%s</th>
                         <th>%s</th>
                         <th>%s</th>
                         <th>%s</th>
                         <th>%s</th>
                         <th>%s</th>
                     </tr>
                 </thead>
                 <tbody>
             """% (_("Borrower"),
                   _("Item"),
                   _("Supplier"),
                   _("Status"),
                   _("ID"),
                   _("Interest from"),
                   _("Due date"),
                   _("Type"),
                   _("Option(s)"))
 
         for (ill_request_id, borrower_id, borrower_name, library_id,
              ill_status, period_from, _period_to, due_date, item_info,
              request_type) in ill_req:
 
             borrower_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_borrower_details',
                                 {'borrower_id': borrower_id, 'ln': ln},
                                 (borrower_name))
 
             if library_id:
                 if request_type in CFG_BIBCIRCULATION_ACQ_TYPE:
                     library_name = db.get_vendor_name(library_id)
                 else:
                     library_name = db.get_library_name(library_id)
             else:
                 library_name = '-'
 
             item_info = eval(item_info)
 
             try:
                 title_link = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_item_details',
                                     {'recid': item_info['recid'], 'ln': ln},
                                 (book_title_from_MARC(int(item_info['recid']))))
             except KeyError:
                 if request_type in ['book'] + CFG_BIBCIRCULATION_ACQ_TYPE:
                     title_link = item_info['title']
                 else:
                     title_link = item_info['periodical_title']
 
             out += """
                    <tr>
                     <td class="bibcirccontent">%s</td>
                     <td class="bibcirccontent">%s</td>
                     <td class="bibcirccontent">%s</td>
                     <td class="bibcirccontent">%s</td>
                     <td class="bibcirccontent">%s</td>
                     <td class="bibcirccontent">%s</td>
                     <td class="bibcirccontent">%s</td>
                     <td class="bibcirccontent">%s</td>
                     <td align="center">
                     """ % (borrower_link, title_link, library_name, ill_status,
                            ill_request_id, period_from, due_date or '-',
                            request_type)
 
             if request_type in CFG_BIBCIRCULATION_ACQ_TYPE:
                 out += """
                        <input type=button onClick="location.href='%s/admin2/bibcirculation/acq_details_step1?ill_request_id=%s'" onmouseover="this.className='bibcircbuttonover'" onmouseout="this.className='bibcircbutton'"
                        value="%s" class='bibcircbutton'>
                     </td>
                    </tr>
                     """ % (CFG_SITE_URL, ill_request_id, _('select'))
             else:
                 out += """
                        <input type=button onClick="location.href='%s/admin2/bibcirculation/ill_request_details_step1?ill_request_id=%s'" onmouseover="this.className='bibcircbuttonover'" onmouseout="this.className='bibcircbutton'"
                        value="%s" class='bibcircbutton'>
                     </td>
                    </tr>
                     """ % (CFG_SITE_URL, ill_request_id, _('select'))
 
         out += """
            </tbody>
           </table>
          </div>
         """
 
         return out
 
     def tmpl_list_acquisition(self, ill_req, ln=CFG_SITE_LANG):
         """
         @param acq_req: informations about acquisition requests
         @type acq_req: tuple
         """
 
         _ = gettext_set_language(ln)
 
         out = """ """
 
         out += load_menu(ln)
 
         out += """
         <style type="text/css"> @import url("/img/tablesorter.css"); </style>
         <script src="/js/jquery/jquery.min.js" type="text/javascript"></script>
         <script src="/js/tablesorter/jquery.tablesorter.js" type="text/javascript"></script>
         <script type="text/javascript">
         $(document).ready(function() {
           $('#table_ill').tablesorter({widthFixed: true, widgets: ['zebra']})
         });
         </script>
          <div class="bibcircbottom">
            <br />
              <table id="table_ill" class="tablesorter" border="0"
                                    cellpadding="0" cellspacing="1">
              <thead>
                     <tr>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                        <th>%s</th>
                     </tr>
              </thead>
              <tbody>
             """% (_("Borrower"),
                   _("Item"),
                   _("Supplier"),
                   _("Cost"),
                   _("Status"),
                   _("ID"),
                   _("Date requested"),
                   _("Type"),
                   _("Options"))
 
         for (ill_request_id, borrower_id, borrower_name, vendor_id,
-             ill_status, period_from, _period_to, due_date, item_info, cost,
+             ill_status, period_from, _period_to, _due_date, item_info, cost,
              request_type) in ill_req:
 
             borrower_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_borrower_details',
                                 {'borrower_id': borrower_id, 'ln': ln},
                                 (borrower_name))
 
             if vendor_id:
                 vendor_name = db.get_vendor_name(vendor_id)
             else:
                 vendor_name = '-'
 
             item_info = eval(item_info)
 
             try:
                 title_link = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_item_details',
                                     {'recid': item_info['recid'], 'ln': ln},
                                 (book_title_from_MARC(int(item_info['recid']))))
             except KeyError:
                 title_link = item_info['title']
 
             out += """
                    <tr>
                     <td class="bibcirccontent">%s</td>
                     <td class="bibcirccontent">%s</td>
                     <td class="bibcirccontent">%s</td>
                     <td class="bibcirccontent">%s</td>
                     <td class="bibcirccontent">%s</td>
                     <td class="bibcirccontent">%s</td>
                     <td class="bibcirccontent">%s</td>
                     <td class="bibcirccontent">%s</td>
                     <td align="center">
                     """ % (borrower_link, title_link, vendor_name,
                            cost, ill_status, ill_request_id,
                            period_from, request_type)
 
             out += """
                        <input type=button onClick="location.href='%s/admin2/bibcirculation/acq_details_step1?ill_request_id=%s'" onmouseover="this.className='bibcircbuttonover'" onmouseout="this.className='bibcircbutton'"
                        value="%s" class='bibcircbutton'>
                     </td>
                    </tr>
                     """ % (CFG_SITE_URL, ill_request_id, _('select'))
 
         out += """
            </tbody>
           </table>
          </div>
         """
 
         return out
 
     def tmpl_ill_request_details_step1(self, ill_request_id,
                                        ill_request_details, libraries,
                                        ill_request_borrower_details,
                                        ln=CFG_SITE_LANG):
 
         """
         @param ill_request_id: identify the ILL request. Primary key of crcILLREQUEST
         @type ill_request_id: int
 
         @param ill_req_details: informations about a given ILL request
         @type ill_req_details: tuple
 
         @param libraries: list of libraries
         @type libraries: list
 
         @param ill_status: status of an ILL request
         @type ill_status: string
 
         @param ill_request_borrower_details: borrower's informations
         @type ill_request_borrower_details: tuple
         """
 
         book_statuses = [CFG_BIBCIRCULATION_ILL_STATUS_NEW,
                          CFG_BIBCIRCULATION_ILL_STATUS_REQUESTED,
                          CFG_BIBCIRCULATION_ILL_STATUS_ON_LOAN,
                          CFG_BIBCIRCULATION_ILL_STATUS_RETURNED,
                          CFG_BIBCIRCULATION_ILL_STATUS_CANCELLED]
 
         article_statuses = [CFG_BIBCIRCULATION_ILL_STATUS_NEW,
                             CFG_BIBCIRCULATION_ILL_STATUS_REQUESTED,
                             CFG_BIBCIRCULATION_ILL_STATUS_RECEIVED,
                             CFG_BIBCIRCULATION_ILL_STATUS_CANCELLED]
 
-        acq_statuses = []
-
         _ = gettext_set_language(ln)
 
         out = load_menu(ln)
 
         out += """
             <style type="text/css"> @import url("/img/tablesorter.css"); </style>
             <script type="text/javascript" language='JavaScript'
                     src="%s/js/jquery/jquery.min.js"></script>
             <script type="text/javascript" language='JavaScript'
                     src="%s/js/ui.datepicker.min.js"></script>
             """% (CFG_SITE_URL, CFG_SITE_URL)
 
         (_borrower_id, borrower_name, borrower_email, borrower_mailbox,
          period_from, period_to, item_info, borrower_comments,
          only_this_edition, request_type) = ill_request_borrower_details
 
         (library_id, request_date, expected_date, arrival_date, due_date,
          return_date, cost, barcode, library_notes,
          ill_status) = ill_request_details
         #request_ok = True
 
         if library_notes == '' or library_notes == None:
             previous_library_notes = {}
         else:
             previous_library_notes = eval(library_notes)
 
         key_array = previous_library_notes.keys()
         key_array.sort()
 
         item_info = eval(item_info)
 
         today = datetime.date.today()
         within_a_week = (datetime.date.today()
                           + datetime.timedelta(days=7)).strftime('%Y-%m-%d')
         within_a_month = (datetime.date.today()
                           + datetime.timedelta(days=30)).strftime('%Y-%m-%d')
 
 
         notes = ''
         for key in key_array:
             delete_note = create_html_link(CFG_SITE_URL +
                         '/admin2/bibcirculation/ill_request_details_step1',
                         {'delete_key': key, 'ill_request_id': ill_request_id,
                         'ln': ln}, (_("[delete]")))
 
             notes += """<tr class="bibcirccontent">
                             <td class="bibcircnotes" width="160" valign="top"
                                 align="center"><b>%s</b></td>
                             <td width="400"><i>%s</i></td>
                             <td width="65" align="center">%s</td>
                         </tr>
 
                      """ % (key, previous_library_notes[key], delete_note)
 
         if library_id:
             library_name = db.get_library_name(library_id)
         else:
             library_name = '-'
 
         try:
             (book_title, book_year, book_author, book_isbn,
               book_editor) = book_information_from_MARC(int(item_info['recid']))
 
             if book_isbn:
                 book_cover = get_book_cover(book_isbn)
             else:
                 book_cover = """%s/img/book_cover_placeholder.gif
                                 """ % (CFG_SITE_URL)
 
             out += """
             <form name="ill_req_form"
                   action="%s/admin2/bibcirculation/ill_request_details_step2" method="get" >
             <div class="bibcircbottom">
             <input type=hidden name=ill_request_id value="%s">
                 <br />
                 <table class="bibcirctable">
                     <tr>
                         <td class="bibcirctableheader" width="10">%s</td>
                     </tr>
                 </table>
                 <table class="bibcirctable">
                  <tr valign='top'>
                    <td width="400">
                     <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                     </table>
                    </td>
                    <td class="bibcirccontent">
                        <img style='border: 1px solid #cfcfcf' src="%s" alt="Book Cover"/>
                    </td>
                  </tr>
               </table>
               <br />
               """ % (CFG_SITE_URL,
                       ill_request_id,
                       _("Item details"),
                       _("Name"),
                       book_title,
                       _("Author(s)"),
                       book_author,
                       _("Year"),
                       book_year,
                       _("Publisher"),
                       book_editor,
                       _("ISBN"),
                       book_isbn,
                       str(book_cover))
 
         except KeyError:
             try:
                 book_cover = get_book_cover(item_info['isbn'])
             except KeyError:
                 book_cover = """%s/img/book_cover_placeholder.gif
                             """ % (CFG_SITE_URL)
 
             if str(request_type) == 'book':
                 out += """
                 <style type="text/css"> @import url("/img/tablesorter.css"); </style>
                 <form name="ill_req_form"
                       action="%s/admin2/bibcirculation/ill_request_details_step2"
                       method="get">
                    <div class="bibcircbottom">
                    <input type=hidden name=ill_request_id value="%s">
                     <br />
                     <table class="bibcirctable">
                       <tr>
                         <td class="bibcirctableheader" width="10">%s</td>
                       </tr>
                     </table>
                     <table class="bibcirctable">
                      <tr valign='top'>
                        <td width="800">
                         <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                          <tr>
                             <th width="100">%s</th>
                             <td>
                                 <textarea name='title' rows="2"
                                     style='width:98%%; border: 1px solid #cfcfcf;'>%s</textarea>
                             </td>
                          </tr>
                          <tr>
                             <th width="100">%s</th>
                             <td>
                                 <textarea name='authors' rows="1"
                                     style='width:98%%; border: 1px solid #cfcfcf;'>%s</textarea>
                             </td>
                          </tr>
                          <tr>
                             <th width="100">%s</th>
                             <td>
                                 <textarea name='place' rows="1"
                                     style='width:98%%; border: 1px solid #cfcfcf;'>%s</textarea>
                             </td>
                          </tr>
                          <tr>
                             <th width="100">%s</th>
                             <td>
                                 <textarea name='publisher' rows="1"
                                     style='width:98%%; border: 1px solid #cfcfcf;'>%s</textarea>
                             </td>
                          </tr>
                          <tr>
                             <th width="100">%s</th>
                             <td>
                                 <textarea name='year' rows="1"
                                     style='width:98%%; border: 1px solid #cfcfcf;'>%s</textarea>
                             </td>
                          </tr>
                          <tr>
                             <th width="100">%s</th>
                             <td>
                                 <textarea name='edition' rows="1"
                                     style='width:98%%; border: 1px solid #cfcfcf;'>%s</textarea>
                             </td>
                          </tr>
                           <tr>
                             <th width="100">%s</th>
                             <td>
                                 <textarea name='isbn' rows="1"
                                     style='width:98%%; border: 1px solid #cfcfcf;'>%s</textarea>
                             </td>
                          </tr>
                         </table>
                       </td>
                         <td class="bibcirccontent">
                             <img style='border: 1px solid #cfcfcf' src="%s" alt="Book Cover"/>
                         </td>
                       </tr>
                   </table>
                   <br />
                   """ % (CFG_SITE_URL, ill_request_id,
                           _("Item details"),
                           _("Title"), item_info['title'],
                           _("Author(s)"), item_info['authors'],
                           _("Place"), item_info['place'],
                           _("Publisher"), item_info['publisher'],
                           _("Year"), item_info['year'],
                           _("Edition"), item_info['edition'],
                           _("ISBN"), item_info['isbn'],
                           str(book_cover))
 
             # for articles
             elif str(request_type) == 'article':
                 #try:
                 #    (volume, issue, page) = item_info['volume'].split(',')
                 #except:
                 #    volume = item_info['volume']
                 #    issue = ''
                 #    page = ''
 
                 out += """
                 <style type="text/css"> @import url("/img/tablesorter.css"); </style>
                 <form name="ill_req_form"
                       action="%s/admin2/bibcirculation/ill_request_details_step2" method="get" >
                    <div class="bibcircbottom">
                    <input type=hidden name=ill_request_id value="%s">
                     <br />
                     <table class="bibcirctable">
                       <tr>
                         <td class="bibcirctableheader" width="10">%s</td>
                       </tr>
                     </table>
                     <table class="bibcirctable">
                      <tr valign='top'>
                        <td width="800">
                         <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                          <tr>
                             <th width="100">%s</th>
                             <td colspan="5">
                                 <textarea name='periodical_title' rows="2"
                                     style='width:98%%; border: 1px solid #cfcfcf;'>%s</textarea>
                             </td>
                          </tr>
                          <tr>
                             <th width="100">%s</th>
                             <td colspan="5">
                                 <textarea name='title' rows="2"
                                     style='width:98%%; border: 1px solid #cfcfcf;'>%s</textarea>
                             </td>
                          </tr>
                          <tr>
                             <th width="100">%s</th>
                             <td colspan="5">
                                 <textarea name='authors' rows="1"
                                     style='width:98%%; border: 1px solid #cfcfcf;'>%s</textarea>
                             </td>
                          </tr>
 
                          <tr>
                             <th width="100">%s</th>
                             <td>
                                 <textarea name='volume' rows="1"
                                           style='width:91%%;
                                           border: 1px solid #cfcfcf;'>%s</textarea>
                             </td>
                             <th width="50" align='right'>%s</th>
                             <td>
                                 <textarea name='issue' rows="1"
                                           style='width:91%%;
                                           border: 1px solid #cfcfcf;'>%s</textarea>
                             </td>
                             <th width="50" align='right'>%s</th>
                             <td>
                                 <textarea name='page' rows="1"
                                           style='width:91%%;
                                           border: 1px solid #cfcfcf;'>%s</textarea>
                             </td>
                          </tr>
 
                          <tr>
                             <th width="100">%s</th>
                             <td colspan="3">
                                 <textarea name='place' rows="1"
                                     style='width:96%%; border: 1px solid #cfcfcf;'>%s</textarea>
                             </td>
                             <th width="50" align='right'>%s</th>
                             <td>
                                 <textarea name='issn' rows="1"
                                     style='width:91%%; border: 1px solid #cfcfcf;'>%s</textarea>
                             </td>
                          </tr>
                          <tr>
                             <th width="100">%s</th>
                             <td colspan="3">
                                 <textarea name='publisher' rows="1"
                                     style='width:96%%; border: 1px solid #cfcfcf;'>%s</textarea>
                             </td>
                             <th width="50" align='right'>%s</th>
                             <td>
                                 <textarea name='year' rows="1"
                                     style='width:91%%; border: 1px solid #cfcfcf;'>%s</textarea>
                             </td>
                          </tr>
                         </table>
                       </td>
                       <td class="bibcirccontent">
                         <img style='border: 1px solid #cfcfcf' src="%s" alt="Book Cover"/>
                       </td>
                       </tr>
                   </table>
                   <br />
                   """ % (CFG_SITE_URL,
                          ill_request_id,
                          _("Item details"),
                          _("Periodical Title"), item_info['periodical_title'],
                          _("Article Title"), item_info['title'],
                          _("Author(s)"), item_info['authors'],
                          _("Volume"), item_info['volume'],
                          _("Issue"), item_info['issue'],
                          _("Page"), item_info['page'],
                          _("Place"), item_info['place'],
                          _("ISSN"), item_info['issn'],
                          _("Publisher"), item_info['publisher'],
                          _("Year"), item_info['year'],
                          str(book_cover))
 
             elif str(request_type) == 'acq-book':
                 out += """
                 <style type="text/css"> @import url("/img/tablesorter.css"); </style>
                 <form name="ill_req_form"
                       action="%s/admin2/bibcirculation/ill_request_details_step2"
                       method="get">
                    <div class="bibcircbottom">
                    <input type=hidden name=ill_request_id value="%s">
                     <br />
                     <table class="bibcirctable">
                       <tr>
                         <td class="bibcirctableheader" width="10">%s</td>
                       </tr>
                     </table>
                     <table class="bibcirctable">
                      <tr valign='top'>
                        <td width="800">
                         <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                          <tr>
                             <th width="100">%s</th>
                             <td>
                                 <textarea name='title' rows="2"
                                     style='width:98%%; border: 1px solid #cfcfcf;'>%s</textarea>
                             </td>
                          </tr>
                          <tr>
                             <th width="100">%s</th>
                             <td>
                                 <textarea name='authors' rows="1"
                                     style='width:98%%; border: 1px solid #cfcfcf;'>%s</textarea>
                             </td>
                          </tr>
                          <tr>
                             <th width="100">%s</th>
                             <td>
                                 <textarea name='place' rows="1"
                                     style='width:98%%; border: 1px solid #cfcfcf;'>%s</textarea>
                             </td>
                          </tr>
                          <tr>
                             <th width="100">%s</th>
                             <td>
                                 <textarea name='publisher' rows="1"
                                     style='width:98%%; border: 1px solid #cfcfcf;'>%s</textarea>
                             </td>
                          </tr>
                          <tr>
                             <th width="100">%s</th>
                             <td>
                                 <textarea name='year' rows="1"
                                     style='width:98%%; border: 1px solid #cfcfcf;'>%s</textarea>
                             </td>
                          </tr>
                          <tr>
                             <th width="100">%s</th>
                             <td>
                                 <textarea name='edition' rows="1"
                                     style='width:98%%; border: 1px solid #cfcfcf;'>%s</textarea>
                             </td>
                          </tr>
                           <tr>
                             <th width="100">%s</th>
                             <td>
                                 <textarea name='isbn' rows="1"
                                     style='width:98%%; border: 1px solid #cfcfcf;'>%s</textarea>
                             </td>
                          </tr>
                         </table>
                       </td>
                         <td class="bibcirccontent">
                             <img style='border: 1px solid #cfcfcf' src="%s" alt="Book Cover"/>
                         </td>
                       </tr>
                   </table>
                   <br />
                   """ % (CFG_SITE_URL, ill_request_id,
                           _("Item details"),
                           _("Title"), item_info['title'],
                           _("Author(s)"), item_info['authors'],
                           _("Place"), item_info['place'],
                           _("Publisher"), item_info['publisher'],
                           _("Year"), item_info['year'],
                           _("Edition"), item_info['edition'],
                           _("ISBN"), item_info['isbn'],
                           str(book_cover))
 
             else:
                 out += """Wrong type."""
 
         out += """
         <table class="bibcirctable">
           <tr valign='top'>
             <td width="550">
               <table>
                 <tr>
                   <td class="bibcirctableheader">%s</td>
                 </tr>
               </table>
               <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                 <tr>
                   <th width="150">%s</th>
                   <td>%s</td>
                 </tr>
                 <tr>
                   <th width="150">%s</th>
                   <td>%s</td>
                 </tr>
                 <tr>
                   <th width="150">%s</th>
                   <td>%s</td>
                 </tr>
                 <tr>
                   <th width="150">%s</th>
                   <td>%s</td>
                 </tr>
                 <tr>
                   <th width="150">%s</th>
                   <td>%s</td>
                 </tr>
                 <tr>
                    <th width="150">%s</th>
                    <td width="350"><i>%s</i></td>
                 </tr>
                 <tr>
                   <th width="150">%s</th>
                   <td>%s</td>
                 </tr>
               </table>
               </td>
               <td>
               <table>
                 <tr>
                      <td class="bibcirctableheader">%s</td>
                 </tr>
              </table>
 
              """ % (_("Borrower request"), _("Name"), borrower_name,
                     _("Email"), borrower_email,
                     _("Mailbox"), borrower_mailbox,
                     _("Period of interest (From)"), period_from,
                     _("Period of interest (To)"), period_to,
                     _("Borrower comments"), borrower_comments or '-',
                     _("Only this edition?"), only_this_edition or 'No',
                     _("ILL request details"))
 
 
         out += """
                         <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                             <tr>
                                 <input type=hidden name=new_status value="%s">
                               <th width="100">%s</th>
                               <td>
                                 <select style='border: 1px solid #cfcfcf'
                                 onchange="location = this.options[this.selectedIndex].value;">
              """ % (ill_status, _("Status"))
 
         if request_type == 'book':
             statuses = book_statuses
         elif request_type in CFG_BIBCIRCULATION_ACQ_TYPE:
             statuses = CFG_BIBCIRCULATION_ACQ_STATUS
         elif request_type == 'article':
             statuses = article_statuses
 
         for status in statuses:
             if status == ill_status:
                 out += """
             <option value ="ill_request_details_step1?ill_request_id=%s&new_status=%s" selected>
                     %s
                     </option>
             """ % (ill_request_id, status, status)
             else:
                 out += """
             <option value ="ill_request_details_step1?ill_request_id=%s&new_status=%s">
                     %s
                     </option>
             """ % (ill_request_id, status, status)
 
         out += """
                                 </select>
                               </td>
                             </tr>
             """
 
 #### NEW ####
         if ill_status == CFG_BIBCIRCULATION_ILL_STATUS_NEW \
            or ill_status == None \
            or ill_status == '':
 
             out += """
                             <tr>
                               <th width="150">%s</th>
                               <td>%s</td>
                             </tr>
                             <tr>
                               <th width="100" valign="top">%s</th>
                               <td>
                                 <table class="bibcircnotes">
                         """ % (_("ILL request ID"), ill_request_id,
                                _("Previous notes"))
 
             out += notes
 
             out += """
                             </table>
                           </td>
                         </tr>
                         <tr>
                           <th valign="top" width="100">%s</th>
                           <td>
                             <textarea name='library_notes' rows="6" cols="74"
                                       style='border: 1px solid #cfcfcf'>
                             </textarea>
                           </td>
                         </tr>
                       </table>
                     </td>
                   </tr>
                 </table>
 
                       """ % (_("Library notes"))
 
 ############# REQUESTED ##############
         elif ill_status ==  CFG_BIBCIRCULATION_ILL_STATUS_REQUESTED:
 
             out += """
                             <tr>
                               <th width="150">%s</th>
                               <td class="bibcirccontent">%s</td>
                             </tr>
                         """ % (_("ILL request ID"), ill_request_id)
 
             out += """
                             <tr>
                               <th width="150">%s</th>
                               <td class="bibcirccontent">
                                 <select name="library_id"  style='border: 1px solid #cfcfcf'>
             """ % (_("Library/Supplier"))
 
             for(lib_id, name) in libraries:
                 if lib_id == library_id:
                     out += """       <option value="%s" selected>%s</option>
                             """ % (lib_id, name)
                 else:
                     out += """       <option value="%s">%s</option>
                             """ % (lib_id, name)
 
             out += """
                          </select>
                        </td>
                      </tr>
                      <tr>
                        <th width="150">%s</th>
                        <td class="bibcirccontent">
 
                         <script type="text/javascript">
                              $(function() {
                                  $("#date_picker1").datepicker({dateFormat: 'yy-mm-dd', showOn: 'button', buttonImage: "%s/img/jquery/calendar.gif", buttonImageOnly: true});
                              });
                         </script>
                         <input type="text" size="10" id="date_picker1"
                                name="request_date" value="%s" style='border: 1px solid #cfcfcf'>
 
                       </td>
                     </tr>
                     <tr>
                       <th width="150">%s</th>
                       <td class="bibcirccontent">
 
                         <script type="text/javascript">
                              $(function() {
                                  $("#date_picker2").datepicker({dateFormat: 'yy-mm-dd', showOn: 'button', buttonImage: "%s/img/jquery/calendar.gif", buttonImageOnly: true});
                              });
                         </script>
                         <input type="text" size="10" id="date_picker2"
                                name="expected_date" value="%s" style='border: 1px solid #cfcfcf'>
 
                       </td>
                     </tr>
                     <tr>
                       <th width="100">%s</th>
                       <td class="bibcirccontent">
                         <input type="text" size="12" name="cost"
                                value="%s" style='border: 1px solid #cfcfcf'>
                         """ % (_("Request date"),
                                CFG_SITE_URL, today,
                                _("Expected date"),
                                CFG_SITE_URL, within_a_week,
                                _("Cost"), cost)
 
             out += """
                       </td>
                     </tr>
                     <tr>
                       <th width="100">%s</th>
                       <td class="bibcirccontent"><input type="text" size="12" name="barcode"
                           value="%s" style='border: 1px solid #cfcfcf'>
                       </td>
                     </tr>
                     <tr>
                           <th width="100" valign="top">%s</th>
                           <td>
                             <table class="bibcircnotes">
                     """ % (_("Barcode"), barcode or 'No barcode asociated',
                            _("Previous notes"))
 
             out += notes
 
             out += """
                             </table>
                           </td>
                         </tr>
                     <tr>
                        <th valign="top" width="150">%s</th>
                           <td>
                             <textarea name='library_notes' rows="6" cols="74"
                                       style='border: 1px solid #cfcfcf'></textarea>
                           </td>
                      </tr>
                    </table>
                  </td>
                </tr>
              </table>
 
                       """ % (_("Library notes"))
 
 ##### ON LOAN ##############
         elif ill_status == CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN:
 
             out += """
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent">%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent">%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent">%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent">%s</td>
                         </tr>
                     """ % (_("ILL request ID"), ill_request_id, _("Library"),
                            library_name, _("Request date"), request_date,
                            _("Expected date"), expected_date)
 
             if str(arrival_date) == '0000-00-00':
                 date1 = today
             else:
                 date1 = arrival_date
 
             if str(due_date) == '0000-00-00':
                 date2 = within_a_month
             else:
                 date2 = due_date
 
 
             out += """
                     <tr>
                        <th width="150">%s</th>
                        <td class="bibcirccontent">
 
                         <script type="text/javascript">
                              $(function() {
                                  $("#date_picker1").datepicker({dateFormat: 'yy-mm-dd', showOn: 'button', buttonImage: "%s/img/calendar.gif", buttonImageOnly: true});
                              });
                         </script>
                         <input type="text" size="10" id="date_picker1" name="arrival_date" value="%s" style='border: 1px solid #cfcfcf'>
 
                       </td>
                     </tr>
                     <tr>
                       <th width="150">%s</th>
                       <td class="bibcirccontent">
 
                         <script type="text/javascript">
                              $(function() {
                                  $("#date_picker2").datepicker({dateFormat: 'yy-mm-dd', showOn: 'button', buttonImage: "%s/img/calendar.gif", buttonImageOnly: true});
                              });
                         </script>
                         <input type="text" size="10" id="date_picker2" name="due_date" value="%s" style='border: 1px solid #cfcfcf'>
                         <input type="hidden" name="request_date" value="%s">
                         <input type="hidden" name="expected_date" value="%s">
                         <input type="hidden" name="library_id" value="%s">
                       </td>
                     </tr>
             """ % (_("Arrival date"), CFG_SITE_URL, date1, _("Due date"),
                 CFG_SITE_URL, date2, request_date, expected_date, library_id)
 
             out += """
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent"><input type="text" size="12" name="cost" value="%s" style='border: 1px solid #cfcfcf'>
                     """ % (_("Cost"), cost)
             out += """
                           </td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent"><input type="text" size="12" name="barcode" value="%s" style='border: 1px solid #cfcfcf'>
                         </tr>
                         <tr>
                           <th width="100" valign="top">%s</th>
                           <td>
                             <table class="bibcircnotes">
                         """ % (_("Barcode"), barcode, _("Previous notes"))
 
             out += notes
 
 
             out += """
                             </table>
                           </td>
                         </tr>
                         <tr>
                           <th valign="top" width="100">%s</th>
                           <td><textarea name='library_notes' rows="6" cols="74" style='border: 1px solid #cfcfcf'></textarea></td>
                         </tr>
                       </table>
                      </td>
                    </tr>
                  </table>
 
                       """ % (_("Library notes"))
 
 
 ##### RETURNED ##############
         elif ill_status == CFG_BIBCIRCULATION_ILL_STATUS_RETURNED or \
              ill_status == CFG_BIBCIRCULATION_ILL_STATUS_CANCELLED:
 
             date1 = return_date
 
             if ill_status == CFG_BIBCIRCULATION_ILL_STATUS_RETURNED and \
                str(return_date)=='0000-00-00':
                 date1 = today
 
             out += """
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent">%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent">%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent">%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent">%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent">%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent">%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent">
                             <script type="text/javascript">
                                 $(function() {
                                     $("#date_picker1").datepicker({dateFormat: 'yy-mm-dd',
                                         showOn: 'button', buttonImage: "%s/img/calendar.gif",
                                         buttonImageOnly: true});
                                 });
                             </script>
                             <input type="text" size="10" id="date_picker1" name="return_date"
                                    value="%s" style='border: 1px solid #cfcfcf'>
                             <input type="hidden" name="request_date"  value="%s">
                             <input type="hidden" name="expected_date" value="%s">
                             <input type="hidden" name="arrival_date"  value="%s">
                             <input type="hidden" name="due_date"      value="%s">
                             <input type="hidden" name="library_id"    value="%s">
                           </td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent">
                             <input type="text" size="12" name="cost"
                                    value="%s" style='border: 1px solid #cfcfcf'>
         """ % (_("ILL request ID"), ill_request_id, _("Library"),
             library_name, _("Request date"), request_date, _("Expected date"),
             expected_date, _("Arrival date"), arrival_date, _("Due date"),
             due_date, _("Return date"), CFG_SITE_URL, date1, request_date,
             expected_date, arrival_date, due_date, library_id, _("Cost"), cost)
 
             out += """
                             </select>
                           </td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent">%s</td>
                         </tr>
                         <tr>
                           <th width="100" valign="top">%s</th>
                           <td>
                             <table class="bibcircnotes">
                     """ % (_("Barcode"), barcode, _("Previous notes"))
 
             out += notes
 
             out += """
                             </table>
                           </td>
                         </tr>
                         <tr>
                           <th valign="top" width="100">%s</th>
                           <td>
                             <textarea name='library_notes' rows="6" cols="74"
                                       style='border: 1px solid #cfcfcf'></textarea>
                           </td>
                         </tr>
                       </table>
                      </td>
                    </tr>
                  </table>
 
                       """ % (_("Library notes"))
 
 ##### RECEIVED ##############
         elif ill_status == CFG_BIBCIRCULATION_ILL_STATUS_RECEIVED:
             if str(arrival_date) == '0000-00-00':
                 date1 = today
             else:
                 date1 = arrival_date
 
             out += """
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent">%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent">%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent">%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent">%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent">
                             <script type="text/javascript">
                                 $(function() {
                                     $("#date_picker1").datepicker({dateFormat: 'yy-mm-dd',
                                         showOn: 'button', buttonImage: "%s/img/calendar.gif",
                                         buttonImageOnly: true});
                                 });
                             </script>
                             <input type="text" size="10" id="date_picker1"
                                name="arrival_date" value="%s" style='border: 1px solid #cfcfcf'>
                             <input type="hidden" name="request_date" value="%s">
                             <input type="hidden" name="expected_date" value="%s">
                             <input type="hidden" name="library_id" value="%s">
                           </td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent"><input type="text" size="12"
                               name="cost" value="%s" style='border: 1px solid #cfcfcf'>
         """ % (_("ILL request ID"), ill_request_id, _("Library"), library_name,
             _("Request date"), request_date, _("Expected date"), expected_date,
             _("Arrival date"), CFG_SITE_URL, date1, request_date, expected_date,
             library_id, _("Cost"), cost)
 
             out += """
                           </td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent">%s</td>
                         </tr>
                         <tr>
                           <th width="100" valign="top">%s</th>
                           <td>
                             <table class="bibcircnotes">
                 """ % (_("Barcode"), barcode, _("Previous notes"))
 
             out += notes
 
             out += """
                             </table>
                           </td>
                         </tr>
                         <tr>
                           <th valign="top" width="100">%s</th>
                           <td>
                             <textarea name='library_notes' rows="6" cols="74"
                                       style='border: 1px solid #cfcfcf'></textarea>
                           </td>
                         </tr>
                       </table>
                      </td>
                    </tr>
                  </table>
 
                       """ % (_("Library notes"))
 
 ###### END STATUSES ######
 
         out += """
              <br />
              <table class="bibcirctable">
                 <tr>
                   <td>
                        <input type=button value="%s"
                               onClick="history.go(-1)" class="formbutton">
                        <input type="submit"
                               value="%s" class="formbutton">
                   </td>
                  </tr>
              </table>
              </div>
              </form>
              <br />
              <br />
                """ % (_("Back"), _("Continue"))
 
         return out
 
     def tmpl_acq_details_step1(self, ill_request_id,
                                      ill_request_details, libraries,
                                      ill_request_borrower_details,
                                      ln=CFG_SITE_LANG):
 
         _ = gettext_set_language(ln)
 
         out = load_menu(ln)
 
         out += """
-            <style type="text/css"> @import url("/img/tablesorter.css"); </style>
+            <style  type="text/css"> @import url("/img/tablesorter.css"); </style>
             <script type="text/javascript" language='JavaScript'
                     src="%s/js/jquery/jquery.min.js"></script>
             <script type="text/javascript" language='JavaScript'
                     src="%s/js/ui.datepicker.min.js"></script>
             """% (CFG_SITE_URL, CFG_SITE_URL)
 
         (_borrower_id, borrower_name, borrower_email,
          borrower_mailbox, period_from, period_to,
          item_info, borrower_comments, only_this_edition,
          budget_code, request_type) = ill_request_borrower_details
 
         (library_id, request_date, expected_date, arrival_date, due_date,
-         return_date, cost, barcode, library_notes,
+         return_date, cost, _barcode, library_notes,
          ill_status) = ill_request_details
 
         if library_notes == '' or library_notes == None:
             previous_library_notes = {}
         else:
             previous_library_notes = eval(library_notes)
 
         key_array = previous_library_notes.keys()
         key_array.sort()
 
         item_info = eval(item_info)
 
         today = datetime.date.today()
         within_a_week = (datetime.date.today()
                        + datetime.timedelta(days=7)).strftime('%Y-%m-%d')
         within_a_month = (datetime.date.today()
                         + datetime.timedelta(days=30)).strftime('%Y-%m-%d')
 
         notes = ''
         for key in key_array:
             delete_note = create_html_link(CFG_SITE_URL +
                         '/admin2/bibcirculation/acq_details_step1',
                         {'delete_key': key, 'ill_request_id': ill_request_id,
                         'ln': ln}, (_("[delete]")))
 
             notes += """<tr class="bibcirccontent">
                             <td class="bibcircnotes" width="160" valign="top"
                                 align="center"><b>%s</b></td>
                             <td width="400"><i>%s</i></td>
                             <td width="65" align="center">%s</td>
                         </tr>
                      """ % (key, previous_library_notes[key], delete_note)
 
         if library_id:
             library_name = db.get_vendor_name(library_id)
         else:
             library_name = '-'
 
         try:
             (book_title, book_year, book_author, book_isbn,
              book_editor) = book_information_from_MARC(int(item_info['recid']))
 
             if book_isbn:
                 book_cover = get_book_cover(book_isbn)
             else:
                 book_cover = """%s/img/book_cover_placeholder.gif
                                 """ % (CFG_SITE_URL)
 
             out += """
             <form name="ill_req_form"
                   action="%s/admin2/bibcirculation/acq_details_step2" method="get" >
             <div class="bibcircbottom">
             <input type=hidden name=ill_request_id value="%s">
                 <br />
                 <table class="bibcirctable">
                     <tr>
                         <td class="bibcirctableheader" width="10">%s</td>
                     </tr>
                 </table>
                 <table class="bibcirctable">
                  <tr valign='top'>
                    <td width="400">
                     <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                     </table>
                    </td>
                    <td class="bibcirccontent">
                        <img style='border: 1px solid #cfcfcf' src="%s" alt="Book Cover"/>
                    </td>
                  </tr>
                 </table>
                 <br />
               """ % (CFG_SITE_URL,
                       ill_request_id,
                       _("Item details"),
                       _("Name"),
                       book_title,
                       _("Author(s)"),
                       book_author,
                       _("Year"),
                       book_year,
                       _("Publisher"),
                       book_editor,
                       _("ISBN"),
                       book_isbn,
                       str(book_cover))
 
         except KeyError:
             try:
                 book_cover = get_book_cover(item_info['isbn'])
             except KeyError:
                 book_cover = """%s/img/book_cover_placeholder.gif
                             """ % (CFG_SITE_URL)
 
             if str(request_type) in CFG_BIBCIRCULATION_ACQ_TYPE:
                 out += """
                 <style type="text/css"> @import url("/img/tablesorter.css"); </style>
                 <form name="ill_req_form"
                       action="%s/admin2/bibcirculation/acq_details_step2"
                       method="get">
                    <div class="bibcircbottom">
                    <input type=hidden name=ill_request_id value="%s">
                     <br />
                     <table class="bibcirctable">
                       <tr>
                         <td class="bibcirctableheader" width="10">%s</td>
                       </tr>
                     </table>
                     <table class="bibcirctable">
                      <tr valign='top'>
                        <td width="800">
                         <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                          <tr>
                             <th width="100">%s</th>
                             <td>
                                 <textarea name='title' rows="2"
                                     style='width:98%%; border: 1px solid #cfcfcf;'>%s</textarea>
                             </td>
                          </tr>
                          <tr>
                             <th width="100">%s</th>
                             <td>
                                 <textarea name='authors' rows="1"
                                     style='width:98%%; border: 1px solid #cfcfcf;'>%s</textarea>
                             </td>
                          </tr>
                          <tr>
                             <th width="100">%s</th>
                             <td>
                                 <textarea name='place' rows="1"
                                     style='width:98%%; border: 1px solid #cfcfcf;'>%s</textarea>
                             </td>
                          </tr>
                          <tr>
                             <th width="100">%s</th>
                             <td>
                                 <textarea name='publisher' rows="1"
                                     style='width:98%%; border: 1px solid #cfcfcf;'>%s</textarea>
                             </td>
                          </tr>
                          <tr>
                             <th width="100">%s</th>
                             <td>
                                 <textarea name='year' rows="1"
                                     style='width:98%%; border: 1px solid #cfcfcf;'>%s</textarea>
                             </td>
                          </tr>
                          <tr>
                             <th width="100">%s</th>
                             <td>
                                 <textarea name='edition' rows="1"
                                     style='width:98%%; border: 1px solid #cfcfcf;'>%s</textarea>
                             </td>
                          </tr>
                          <tr>
                             <th width="100">%s</th>
                             <td>
                                 <textarea name='isbn' rows="1"
                                     style='width:98%%; border: 1px solid #cfcfcf;'>%s</textarea>
                             </td>
                          </tr>
                          <tr>
                             <th width="100">%s</th>
                             <td>
                                 <textarea name='standard_number' rows="1"
                                     style='width:98%%; border: 1px solid #cfcfcf;'>%s</textarea>
                             </td>
                          </tr>
                         </table>
                       </td>
                         <td class="bibcirccontent">
                             <img style='border: 1px solid #cfcfcf' src="%s" alt="Book Cover"/>
                         </td>
                       </tr>
                   </table>
                   <br />
                   """ % (CFG_SITE_URL, ill_request_id,
                           _("Item details"),
                           _("Title"), item_info['title'],
                           _("Author(s)"), item_info['authors'],
                           _("Place"), item_info['place'],
                           _("Publisher"), item_info['publisher'],
                           _("Year"), item_info['year'],
                           _("Edition"), item_info['edition'],
                           _("ISBN"), item_info['isbn'],
                           _("Standard number"), item_info['standard_number'],
                           str(book_cover))
 
             else:
                 out += """Wrong type."""
 
         out += """
         <table class="bibcirctable">
           <tr valign='top'>
             <td width="550">
               <table>
                 <tr>
                   <td class="bibcirctableheader">%s</td>
                 </tr>
               </table>
               <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                 <tr>
                   <th width="150">%s</th>
                   <td>%s</td>
                 </tr>
                 <tr>
                   <th width="150">%s</th>
                   <td>%s</td>
                 </tr>
                 <tr>
                   <th width="150">%s</th>
                   <td>%s</td>
                 </tr>
                 <tr>
                   <th width="150">%s</th>
                   <td>%s</td>
                 </tr>
                 <tr>
                   <th width="150">%s</th>
                   <td>%s</td>
                 </tr>
                 <tr>
                    <th width="150">%s</th>
                    <td width="350"><i>%s</i></td>
                 </tr>
                 <tr>
                   <th width="150">%s</th>
                   <td>%s</td>
                 </tr>
               </table>
               </td>
               <td>
               <table>
                 <tr>
                      <td class="bibcirctableheader">%s</td>
                 </tr>
              </table>
 
              """ % (_("Borrower request"), _("Name"), borrower_name,
                     _("Email"), borrower_email,
                     _("Mailbox"), borrower_mailbox,
                     _("Period of interest (From)"), period_from,
                     _("Period of interest (To)"), period_to,
                     _("Borrower comments"), borrower_comments or '-',
                     _("Only this edition?"), only_this_edition or 'No',
                     _("Request details"))
 
 
         out += """
                         <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                             <tr>
                                 <input type=hidden name=new_status value="%s">
                               <th width="100">%s</th>
                               <td colspan="3">
                                 <select style='border: 1px solid #cfcfcf'
                                 onchange="location = this.options[this.selectedIndex].value;">
              """ % (ill_status, _("Status"))
 
         for status in CFG_BIBCIRCULATION_ACQ_STATUS:
             if status == ill_status:
                 out += """
             <option value ="acq_details_step1?ill_request_id=%s&new_status=%s" selected>
                     %s
                     </option>
             """ % (ill_request_id, status, status)
             else:
                 out += """
             <option value ="acq_details_step1?ill_request_id=%s&new_status=%s">
                     %s
                     </option>
             """ % (ill_request_id, status, status)
 
         out += """
                                 </select>
                               </td>
                             </tr>
             """
 
 ######## NEW ########
         if ill_status == CFG_BIBCIRCULATION_ACQ_STATUS_NEW \
            or ill_status == None \
            or ill_status == '':
 
             out += """
                             <tr>
                               <th width="150">%s</th>
                               <td>%s</td>
                               <th width="150">%s</th>
                               <td>%s</td>
                             </tr>
                             <tr>
                               <th width="150">%s</th>
                               <td colspan="3">
                                 <input type="text" size="12"
                                        name="budget_code"
                                        value="%s"
                                        style='border: 1px solid #cfcfcf'>
                               </td>
                             </tr>
                             <tr>
                               <th width="100" valign="top">%s</th>
                               <td colspan="3">
                                 <table class="bibcircnotes">
                     """ % (_("ILL request ID"), ill_request_id,
                            _("Type"), request_type,
                            _("Budget code"), budget_code,
                            _("Previous notes"))
 
             out += notes
 
             out += """
                             </table>
                           </td>
                         </tr>
                         <tr>
                           <th valign="top" width="100">%s</th>
                           <td colspan="3">
                             <textarea name='library_notes' rows="6" cols="74"
                                       style='border: 1px solid #cfcfcf'>
                             </textarea>
                           </td>
                         </tr>
                       </table>
                     </td>
                   </tr>
                 </table>
                       """ % (_("Library notes"))
 
 ############# ON ORDER ##############
         elif ill_status ==  CFG_BIBCIRCULATION_ACQ_STATUS_ON_ORDER:
 
             out += """
                             <tr>
                               <th width="150">%s</th>
                               <td class="bibcirccontent">%s</td>
                               <th width="150">%s</th>
                               <td class="bibcirccontent">%s</td>
                             </tr>
                         """ % (_("ILL request ID"), ill_request_id,
                                _("Type"), request_type)
 
             out += """
                             <tr>
                               <th width="150">%s</th>
                               <td class="bibcirccontent" colspan="3">
                                 <select name="library_id"  style='border: 1px solid #cfcfcf'>
                         """ % (_("Vendor"))
 
             for(lib_id, name) in libraries:
                 if lib_id == library_id:
                     out += """       <option value="%s" selected>%s</option>
                             """ % (lib_id, name)
                 else:
                     out += """       <option value="%s">%s</option>
                             """ % (lib_id, name)
 
             out += """
                          </select>
                        </td>
                      </tr>
                      <tr>
                        <th width="150">%s</th>
                        <td class="bibcirccontent" colspan="3">
 
                         <script type="text/javascript">
                              $(function(){
                                  $("#date_picker1").datepicker({dateFormat: 'yy-mm-dd',
                                    showOn: 'button', buttonImage: "%s/img/calendar.gif",
                                    buttonImageOnly: true});
                              });
                         </script>
                         <input type="text" size="10" id="date_picker1"
                                name="request_date" value="%s" style='border: 1px solid #cfcfcf'>
 
                       </td>
                     </tr>
                     <tr>
                       <th width="150">%s</th>
                       <td class="bibcirccontent" colspan="3">
                         <script type="text/javascript">
                              $(function() {
                                  $("#date_picker2").datepicker({dateFormat: 'yy-mm-dd',
                                         showOn: 'button', buttonImage: "%s/img/calendar.gif",
                                         buttonImageOnly: true});
                              });
                         </script>
                         <input type="text" size="10" id="date_picker2"
                                name="expected_date" value="%s" style='border: 1px solid #cfcfcf'>
 
                       </td>
                     </tr>
                     <tr>
                       <th width="100">%s</th>
                       <td class="bibcirccontent" colspan="3">
                         <input type="text" size="12" name="cost"
                                value="%s" style='border: 1px solid #cfcfcf'>
                         """ % (_("Request date"),
                                CFG_SITE_URL, today,
                                _("Expected date"),
                                CFG_SITE_URL, within_a_week,
                                _("Cost"), cost)
 
             out += """
                       </td>
                     </tr>
                     <tr>
                       <th width="100">%s</th>
                       <td class="bibcirccontent" colspan="3">
                             <input type="text" size="12" name="budget_code"
                                    value="%s" style='border: 1px solid #cfcfcf'>
                       </td>
                     </tr>
                     <tr>
                           <th width="100" valign="top">%s</th>
                           <td colspan="3">
                             <table class="bibcircnotes">
                     """ % (_("Budget code"), budget_code,
                            _("Previous notes"))
 
             out += notes
 
             out += """
                             </table>
                           </td>
                     </tr>
                     <tr>
                         <th valign="top" width="150">%s</th>
                             <td colspan="3">
                                 <textarea name='library_notes' rows="6" cols="74"
                                           style='border: 1px solid #cfcfcf'></textarea>
                             </td>
                     </tr>
                    </table>
                  </td>
                </tr>
              </table>
                       """ % (_("Library notes"))
 
 ##### PARTIAL RECEIPT ##############
         elif ill_status == CFG_BIBCIRCULATION_ACQ_STATUS_PARTIAL_RECEIPT:
 
             out += """
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent">%s</td>
                           <th width="100">%s</th>
                           <td class="bibcirccontent">%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent" colspan="3">%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent" colspan="3">%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent" colspan="3">%s</td>
                         </tr>
                     """ % (_("ILL request ID"), ill_request_id,
                            _("Type"), request_type, _("Library"),
                            library_name, _("Request date"), request_date,
                            _("Expected date"), expected_date)
 
             if str(arrival_date) == '0000-00-00':
                 date1 = today
             else:
                 date1 = arrival_date
 
             if str(due_date) == '0000-00-00':
                 date2 = within_a_month
             else:
                 date2 = due_date
 
 
             out += """
                     <tr>
                        <th width="150">%s</th>
                        <td class="bibcirccontent" colspan="3">
 
                         <script type="text/javascript">
                              $(function() {
                                  $("#date_picker1").datepicker({dateFormat: 'yy-mm-dd', showOn: 'button', buttonImage: "%s/img/calendar.gif", buttonImageOnly: true});
                              });
                         </script>
                         <input type="text" size="10" id="date_picker1" name="arrival_date" value="%s" style='border: 1px solid #cfcfcf'>
 
                       </td>
                     </tr>
                     <tr>
                       <th width="150">%s</th>
                       <td class="bibcirccontent" colspan="3">
 
                         <script type="text/javascript">
                              $(function() {
                                  $("#date_picker2").datepicker({dateFormat: 'yy-mm-dd', showOn: 'button', buttonImage: "%s/img/calendar.gif", buttonImageOnly: true});
                              });
                         </script>
                         <input type="text" size="10" id="date_picker2" name="due_date" value="%s" style='border: 1px solid #cfcfcf'>
                         <input type="hidden" name="request_date" value="%s">
                         <input type="hidden" name="expected_date" value="%s">
                         <input type="hidden" name="library_id" value="%s">
                       </td>
                     </tr>
             """ % (_("Arrival date"), CFG_SITE_URL, date1, _("Due date"),
                 CFG_SITE_URL, date2, request_date, expected_date, library_id)
 
             out += """
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent" colspan="3">
                             <input type="text" size="12" name="cost" value="%s"
                                    style='border: 1px solid #cfcfcf'>
                     """ % (_("Cost"), cost)
 
             out += """
                           </td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent" colspan="3">
                             <input type="text" size="12" name="budget_code"
                                    value="%s" style='border: 1px solid #cfcfcf'>
                         </tr>
                         <tr>
                           <th width="100" valign="top">%s</th>
                           <td colspan="3">
                             <table class="bibcircnotes">
                         """ % (_("Budget code"), budget_code, _("Previous notes"))
 
             out += notes
 
 
             out += """
                             </table>
                           </td>
                         </tr>
                         <tr>
                           <th valign="top" width="100">%s</th>
                           <td colspan="3">
                             <textarea name='library_notes' rows="6" cols="74"
                                       style='border: 1px solid #cfcfcf'></textarea>
                           </td>
                         </tr>
                       </table>
                      </td>
                    </tr>
                  </table>
 
                       """ % (_("Library notes"))
 
 
 ##### CANCELED ##############
         elif ill_status == CFG_BIBCIRCULATION_ACQ_STATUS_CANCELLED:
 
             date1 = return_date
 
             if ill_status == CFG_BIBCIRCULATION_ILL_STATUS_RETURNED and \
                str(return_date)=='0000-00-00':
                 date1 = today
 
             out += """
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent">%s</td>
                           <th width="100">%s</th>
                           <td class="bibcirccontent">%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent" colspan="3">%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent" colspan="3">%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent" colspan="3">%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent" colspan="3">%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent" colspan="3">%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent" colspan="3">
                             <script type="text/javascript">
                                 $(function() {
                                     $("#date_picker1").datepicker({dateFormat: 'yy-mm-dd',
                                         showOn: 'button', buttonImage: "%s/img/calendar.gif",
                                         buttonImageOnly: true});
                                 });
                             </script>
                             <input type="text" size="10" id="date_picker1" name="return_date"
                                    value="%s" style='border: 1px solid #cfcfcf'>
                             <input type="hidden" name="request_date"  value="%s">
                             <input type="hidden" name="expected_date" value="%s">
                             <input type="hidden" name="arrival_date"  value="%s">
                             <input type="hidden" name="due_date"      value="%s">
                             <input type="hidden" name="library_id"    value="%s">
                             <input type="hidden" name="budget_code"   value="%s">
                           </td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent" colspan="3">
                             <input type="text" size="12" name="cost"
                                    value="%s" style='border: 1px solid #cfcfcf'>
         """ % (_("ILL request ID"), ill_request_id, _("Type"), request_type,
                _("Library"), library_name, _("Request date"), request_date,
                _("Expected date"), expected_date, _("Arrival date"),
                arrival_date, _("Due date"), due_date, _("Return date"),
                CFG_SITE_URL, date1, request_date, expected_date, arrival_date,
                due_date, library_id, budget_code, _("Cost"), cost)
 
             out += """
                           </td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent" colspan="3">%s</td>
                         </tr>
                         <tr>
                           <th width="100" valign="top">%s</th>
                           <td colspan="3">
                             <table class="bibcircnotes">
                     """ % (_("Budget code"), budget_code, _("Previous notes"))
 
             out += notes
 
             out += """
                             </table>
                           </td>
                         </tr>
                         <tr>
                           <th valign="top" width="100">%s</th>
                           <td colspan="3">
                             <textarea name='library_notes' rows="6" cols="74"
                                       style='border: 1px solid #cfcfcf'></textarea>
                           </td>
                         </tr>
                       </table>
                      </td>
                    </tr>
                  </table>
 
                       """ % (_("Library notes"))
 
 ##### RECEIVED ##############
         elif ill_status == CFG_BIBCIRCULATION_ACQ_STATUS_RECEIVED:
             if str(arrival_date) == '0000-00-00':
                 date1 = today
             else:
                 date1 = arrival_date
 
             out += """
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent">%s</td>
                           <th width="100">%s</th>
                           <td class="bibcirccontent">%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent" colspan="3">%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent" colspan="3">%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent" colspan="3">%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent" colspan="3">
                             <script type="text/javascript">
                                 $(function() {
                                     $("#date_picker1").datepicker({dateFormat: 'yy-mm-dd',
                                         showOn: 'button', buttonImage: "%s/img/calendar.gif",
                                         buttonImageOnly: true});
                                 });
                             </script>
                             <input type="text" size="10" id="date_picker1"
                                name="arrival_date" value="%s" style='border: 1px solid #cfcfcf'>
                             <input type="hidden" name="request_date" value="%s">
                             <input type="hidden" name="expected_date" value="%s">
                             <input type="hidden" name="library_id" value="%s">
                           </td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent" colspan="3"><input type="text" size="12"
                               name="cost" value="%s" style='border: 1px solid #cfcfcf'>
         """ % (_("ILL request ID"), ill_request_id, _("Type"), request_type,
                _("Library"), library_name, _("Request date"), request_date,
                _("Expected date"), expected_date, _("Arrival date"),
                CFG_SITE_URL, date1, request_date, expected_date, library_id,
                _("Cost"), cost)
 
             out += """
                           </td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td class="bibcirccontent" colspan="3"><input type="text" size="12"
                             name="budget_code" value="%s" style='border: 1px solid #cfcfcf'></td>
                         </tr>
                         <tr>
                           <th width="100" valign="top">%s</th>
                           <td colspan="3">
                             <table class="bibcircnotes">
                 """ % (_("Budget code"), budget_code, _("Previous notes"))
 
             out += notes
 
             out += """
                             </table>
                           </td>
                         </tr>
                         <tr>
                           <th valign="top" width="100">%s</th>
                           <td colspan="3">
                             <textarea name='library_notes' rows="6" cols="74"
                                       style='border: 1px solid #cfcfcf'></textarea>
                           </td>
                         </tr>
                       </table>
                      </td>
                    </tr>
                  </table>
 
                       """ % (_("Library notes"))
 
 ###### END STATUSES ######
 
         out += """
 
              <br />
              <table class="bibcirctable">
                 <tr>
                   <td>
                        <input type=button value="%s"
                         onClick="history.go(-1)" class="formbutton">
 
                        <input type="submit"
                        value="%s" class="formbutton">
 
                   </td>
                  </tr>
              </table>
              </div>
              </form>
              <br />
              <br />
                """ % (_("Back"), _("Continue"))
 
         return out
 
 
     def tmpl_ordered_book_details_step1(self, order_details, list_of_vendors,
                                         ln=CFG_SITE_LANG):
         """
         @param order_details: informations about a given order.
         @type order_details: tuple
 
         @param list_of_vendors: list with all the vendors
         @type list_of_vendors: list
         """
 
         _ = gettext_set_language(ln)
 
         out = """
         """
         out += load_menu(ln)
 
         (purchase_id, recid, vendor, order_date, expected_date,
                                         price, status, notes) = order_details
 
         purchase_notes = eval(notes)
 
         (book_title, book_year, book_author,
                     book_isbn, book_editor) = book_information_from_MARC(recid)
 
         (value, currency) = price.split()
 
         if book_isbn:
             book_cover = get_book_cover(book_isbn)
         else:
             book_cover = "%s/img/book_cover_placeholder.gif" % (CFG_SITE_URL)
 
         out += """
            <style type="text/css"> @import url("/img/tablesorter.css"); </style>
            <form name="update_item_info_step4_form" action="%s/admin2/bibcirculation/ordered_books_details_step2" method="get" >
            <div class="bibcircbottom">
            <input type=hidden name=purchase_id value="%s">
                 <br />
                      <table class="bibcirctable">
                           <tr>
                                <td class="bibcirctableheader" width="10">%s</td>
                           </tr>
                 </table>
                 <table class="bibcirctable">
                  <tr valign='top'>
                     <td width="400"><input type=hidden name=recid value='%s'>
                     <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                      <tr>
                         <th width="100">%s</th>
                         <td class="bibcirccontent">%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td class="bibcirccontent">%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td class="bibcirccontent">%s</td>
                          </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td class="bibcirccontent">%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td class="bibcirccontent">%s</td>
                      </tr>
                      </table>
                      </td>
                      <td class="bibcirccontent"><img style='border: 1px solid #cfcfcf' src="%s" alt="Book Cover"/></td>
                      </tr>
               </table>
 
            <br />
 
            """ % (CFG_SITE_URL,
                    purchase_id,
                    _("Item details"),
                    recid,
                    _("Name"),
                    book_title,
                    _("Author(s)"),
                    book_author,
                    _("Year"),
                    book_year,
                    _("Publisher"),
                    book_editor,
                    _("ISBN"),
                    book_isbn,
                    str(book_cover))
 
         out += """
 
         <script type="text/javascript" language='JavaScript' src="%s/js/ui.datepicker.min.js"></script>
 
              <table class="bibcirctable">
                 <tr>
                      <td class="bibcirctableheader">%s</td>
                 </tr>
              </table>
              <table class="tablesortermedium" border="0" cellpadding="0" cellspacing="1">
                 <tr>
                     <th width="100">%s</th>
                     <td class="bibcirccontent">
                     <select name="vendor_id"  style='border: 1px solid #cfcfcf'>
             """ % (CFG_SITE_URL, _("Order details"), _("Vendor"))
 
         for(vendor_id, name) in list_of_vendors:
             if vendor_id == vendor:
                 out += """<option value="%s" selected>%s</option>
                         """ % (vendor_id, name)
             else:
                 out += """<option value="%s">%s</option>""" % (vendor_id, name)
 
         out += """
                     </select>
                     </td>
                 </tr>
                 <tr>
                     <th width="100">%s</th>
                     <td class="bibcirccontent">
                     <input type="text" size="12" name="cost" value="%s" style='border: 1px solid #cfcfcf'>
                     <select name="currency"  style='border: 1px solid #cfcfcf'>
 
                 """ % (_("Cost"), value)
 
         if currency == 'EUR':
             out += """
              <option value="EUR" selected>EUR</option>
              <option value="CHF">CHF</option>
              <option value="USD">USD</option> """
 
         elif currency == 'CHF':
             out += """
              <option value="EUR">EUR</option>
              <option value="CHF" selected>CHF</option>
              <option value="USD">USD</option> """
 
         else:
             out += """
             <option value="EUR">EUR</option>
             <option value="CHF">CHF</option>
             <option value="USD" selected>USD</option> """
 
 
         out += """
                     </select>
                     </td>
                 </tr>
                 <tr>
                     <th width="100">%s</th>
                     <td class="bibcirccontent">
                       <select name="status" style='border: 1px solid #cfcfcf'>
                       """ % (_("Status"))
 
         for st in (CFG_BIBCIRCULATION_ITEM_STATUS_ON_ORDER,
                    CFG_BIBCIRCULATION_REQUEST_STATUS_CANCELLED,
                    CFG_BIBCIRCULATION_ITEM_STATUS_NOT_ARRIVED):
             if st == status:
                 out += """<option value="%s" selected>%s</option>
                        """ % (st, _(st))
             else:
                 out += """<option value="%s">%s</option>
                        """ % (st, _(st))
 
         out += """
                       </select>
                     </td>
                 </tr>
                 <tr>
                 <th width="100">%s</th>
                 <td class="bibcirccontent">
 
                         <script type="text/javascript">
                              $(function() {
                                  $("#date_picker1").datepicker({dateFormat: 'yy-mm-dd', showOn: 'button', buttonImage: "%s/img/calendar.gif", buttonImageOnly: true});
                              });
                         </script>
                         <input type="text" size="10" id="date_picker1" name="order_date" value="%s" style='border: 1px solid #cfcfcf'>
 
                     </td>
                 </tr>
                 <tr>
                 <th width="100">%s</th>
                 <td class="bibcirccontent">
                         <script type="text/javascript">
                              $(function() {
                                  $("#date_picker2").datepicker({dateFormat: 'yy-mm-dd', showOn: 'button', buttonImage: "%s/img/calendar.gif", buttonImageOnly: true});
                              });
                         </script>
                         <input type="text" size="10" id="date_picker2" name="expected_date" value="%s" style='border: 1px solid #cfcfcf'>
 
                     </td>
                 </tr>
                 <tr>
                     <th width="100" valign="top">%s</th>
                     <td>
                       <table class="bibcircnotes">
 
                     """ % (_("Order date"), CFG_SITE_URL, order_date,
                            _("Expected date"), CFG_SITE_URL, expected_date,
                            _("Previous notes"))
 
         key_array = purchase_notes.keys()
         key_array.sort()
 
         for key in key_array:
 
             delete_note = create_html_link(CFG_SITE_URL +
                     '/admin2/bibcirculation/ordered_books_details_step1',
                     {'delete_key': key, 'purchase_id': purchase_id, 'ln': ln},
                     (_("[delete]")))
 
             out += """<tr class="bibcirccontent">
                         <td class="bibcircnotes" width="160" valign="top" align="center"><b>%s</b></td>
                         <td width="400"><i>%s</i></td>
                         <td width="65" align="center">%s</td>
                       </tr>
 
                       """ % (key, purchase_notes[key], delete_note)
 
 
         out += """
                    </table></td>
                </tr>
                <input type=hidden name="purchase_notes" value="%s">
                <tr>
                  <th width="100" valign="top">%s</th>
                  <td class="bibcirccontent">
                    <textarea name="library_notes" rows="5" cols="90" style='border: 1px solid #cfcfcf'></textarea>
                  </td>
                </tr>
              </table>
              <br />
              <table class="bibcirctable">
                 <tr>
                   <td>
                        <input type=button value="%s"
                         onClick="history.go(-1)" class="formbutton">
 
                        <input type="submit"
                        value="%s" class="formbutton">
 
                   </td>
                  </tr>
              </table>
              </form>
              <br />
              <br />
              </div>
              """ % (purchase_notes, _("Notes"), _("Back"), _("Continue"))
 
         return out
 
     def tmpl_ordered_book_details_step2(self, order_details, ln=CFG_SITE_LANG):
         """
         @param order_details: informations about a given order.
         @type order_details: tuple
 
         @param ln: language of the page
         """
 
         (purchase_id, recid, vendor_id, cost, currency, status, order_date,
          expected_date, purchase_notes, library_notes) = order_details
 
         vendor_name = db.get_vendor_name(vendor_id)
 
         (book_title, book_year, book_author,
          book_isbn, book_editor) = book_information_from_MARC(recid)
 
         if book_isbn:
             book_cover = get_book_cover(book_isbn)
         else:
             book_cover = "%s/img/book_cover_placeholder.gif" % (CFG_SITE_URL)
 
         _ = gettext_set_language(ln)
 
         out = """
         """
         out += load_menu(ln)
 
         out += """
             <div class="bibcircbottom">
             <form name="step2_form" action="%s/admin2/bibcirculation/ordered_books_details_step3" method="get" >
                 <input type=hidden name=purchase_id value="%s">
                 <input type=hidden name=recid value="%s">
                 <input type=hidden name=vendor_id value="%s">
                 <input type=hidden name=cost value="%s">
                 <input type=hidden name=currency value="%s">
                 <input type=hidden name=status value="%s">
                 <input type=hidden name=order_date value="%s">
                 <input type=hidden name=expected_date value="%s">
                 <input type=hidden name=purchase_notes value="%s">
                 <input type=hidden name=library_notes value="%s">
               <br />
               <table class="bibcirctable">
                   <tr>
                      <td class="bibcirctableheader" width="10">%s</td>
                   </tr>
                 </table>
 
                 <table class="bibcirctable">
                  <tr valign='top'>
                     <td width="400">
                     <table>
                      <tr>
                         <td width="100">%s</td>
                         <td class="bibcirccontent">%s</td>
                      </tr>
                      <tr>
                         <td width="100">%s</td>
                         <td class="bibcirccontent">%s</td>
                      </tr>
                      <tr>
                         <td width="100">%s</td>
                         <td class="bibcirccontent">%s</td>
                      </tr>
                      <tr>
                         <td width="100">%s</td>
                         <td class="bibcirccontent">%s</td>
                      </tr>
                      <tr>
                         <td width="100">%s</td>
                         <td class="bibcirccontent">%s</td>
                      </tr>
                      </table>
                      </td>
                      <td class="bibcirccontent">
                      <img style='border: 1px solid #cfcfcf' src="%s" alt="Book Cover"/>
                      </td>
                      </tr>
               </table>
               <br />
               """ % (CFG_SITE_URL,
                      purchase_id, recid,
                      vendor_id, cost,
                      currency, status,
                      order_date,
                      expected_date,
                      purchase_notes,
                      library_notes,
                      _("Item details"),
                      _("Name"), book_title,
                      _("Author(s)"), book_author,
                      _("Year"), book_year,
                      _("Publisher"), book_editor,
                      _("ISBN"), book_isbn,
                      str(book_cover))
 
         out += """
               <br />
               <table class="bibcirctable">
                   <tr>
                      <td class="bibcirctableheader">%s</td>
                   </tr>
                 </table>
               <table class="bibcirctable">
                 <tr>
                     <td width="100">%s</td>
                     <td class="bibcirccontent">%s</td>
                 </tr>
                 <tr>
                     <td width="100">%s</td>
                     <td class="bibcirccontent">%s %s</td>
                 </tr>
                 <tr>
                     <td width="100">%s</td>
                     <td class="bibcirccontent">%s</td>
                 </tr>
                 <tr>
                     <td width="100">%s</td>
                     <td class="bibcirccontent">%s</td>
                  </tr>
                   <tr>
                     <td width="100">%s</td>
                     <td class="bibcirccontent">%s</td>
                  </tr>
                   <tr>
                     <td width="100" valign="top">%s</td>
                     <td><table class="bibcircnotes">
 
                     """ % (_("Order details"),
                            _("Vendor"), vendor_name,
                            _("Price"), cost, currency,
                            _("Status"), status,
                            _("Order date"), order_date,
                            _("Expected date"), expected_date,
                            _("Previous notes"))
 
         purchase_notes = eval(purchase_notes)
 
         key_array = purchase_notes.keys()
         key_array.sort()
 
         for key in key_array:
             out += """<tr class="bibcirccontent">
                         <td class="bibcircnotes" width="160" valign="top" align="center"><b>[%s]</b></td>
                         <td width="400"><i>%s</i></td>
                       </tr>
 
                       """ % (key, purchase_notes[key])
 
         out += """
                    </table>
                   </td>
                  </tr>
                   <tr>
                     <td width="100">%s</td>
                     <td class="bibcirccontent">%s</td>
                  </tr>
                 </table>
                 <br />
                 <table class="bibcirctable">
                    <tr>
                     <td>
                        <input type=button value="%s"
                         onClick="history.go(-1)" class="formbutton">
 
                        <input type="submit"
                        value="%s" class="formbutton">
 
                     </td>
                    </tr>
                  </table>
                </form>
                <br />
                <br />
                </div>
                """ % (_("Notes"), library_notes,
                       _("Back"), _("Continue"))
 
         return out
 
     def tmpl_ordered_book_details_step3(self, ln=CFG_SITE_LANG):
         """
         Last step of the request procedure.
 
         @param ln: language
         """
 
         _ = gettext_set_language(ln)
 
         out = """ """
 
         out += load_menu(ln)
 
 
         out += """
         <div class="bibcircbottom">
         <br />
         <br />
         <table class="bibcirctable">
         <tr>
         <td class="bibcirccontent" width="30">%s</td>
         </tr>
         </table>
         <br />
         <br />
         <table class="bibcirctable">
         <td>
             <input type=button
                 onClick="location.href='%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s'"
                 value='%s' class='formbutton'>
         </td>
         </table>
         <br />
         <br />
         </div>
 
         """ % (_("Purchase information updated with success."),
                CFG_SITE_URL, ln, _("Back to home"))
 
 
         return out
 
     def tmpl_add_new_vendor_step1(self, ln=CFG_SITE_LANG):
         """
         @param ln: language
         """
 
         _ = gettext_set_language(ln)
 
         out = """ """
 
         out += load_menu(ln)
 
         out += """
             <style type="text/css"> @import url("/img/tablesorter.css"); </style>
             <div class="bibcircbottom" align="center">
             <form name="add_new_vendor_step1_form" action="%s/admin2/bibcirculation/add_new_vendor_step2" method="get" >
               <br />
               <br />
                <table class="bibcirctable">
                 <tr align="center">
                      <td class="bibcirctableheader">%s</td>
                 </tr>
               </table>
               <table class="tablesorterborrower" border="0" cellpadding="0" cellspacing="1">
                 <tr>
                     <th width="70">%s</th>
                     <td class="bibcirccontent">
                       <input type="text" style='border: 1px solid #cfcfcf' size=45 name="name">
                     </td>
                 </tr>
                 <tr>
                     <th width="70">%s</th>
                     <td class="bibcirccontent">
                       <input type="text" style='border: 1px solid #cfcfcf' size=45 name="email">
                     </td>
                 </tr>
                 <tr>
                     <th width="70">%s</th>
                     <td class="bibcirccontent">
                       <input type="text" style='border: 1px solid #cfcfcf' size=45 name="phone">
                     </td>
                 </tr>
                 <tr>
                     <th width="70">%s</th>
                     <td class="bibcirccontent">
                       <input type="text" style='border: 1px solid #cfcfcf' size=45 name="address">
                     </td>
                  </tr>
                  <tr>
                     <th width="70" valign="top">%s</th>
                     <td class="bibcirccontent">
                       <textarea name="notes" rows="5" cols="39" style='border: 1px solid #cfcfcf'></textarea>
                     </td>
                  </tr>
                 </table>
                 <br />
                 <table class="bibcirctable">
                 <tr align="center">
                   <td>
                        <input type=button value="%s" onClick="history.go(-1)" class="formbutton">
                        <input type="submit"   value="%s" class="formbutton">
                   </td>
                  </tr>
                 </table>
                 <br />
                 <br />
                 </form>
                 </div>
                 """ % (CFG_SITE_URL, _("New vendor information"), _("Name"),
                        _("Email"), _("Phone"), _("Address"), _("Notes"),
                        _("Back"), _("Continue"))
 
 
         return out
 
     def tmpl_add_new_vendor_step2(self, tup_infos, ln=CFG_SITE_LANG):
         """
         @param tup_infos: borrower's informations
         @type tup_infos: tuple
 
         @param ln: language
         """
 
         _ = gettext_set_language(ln)
 
         (name, email, phone, address, notes) = tup_infos
 
         out = """ """
 
         out += load_menu(ln)
 
         out += """
             <style type="text/css"> @import url("/img/tablesorter.css"); </style>
             <div class="bibcircbottom" align="center">
             <form name="add_new_vendor_step2_form" action="%s/admin2/bibcirculation/add_new_vendor_step3" method="get" >
               <br />
               <br />
                <table class="bibcirctable">
                 <tr align="center">
                      <td class="bibcirctableheader">%s</td>
                 </tr>
               </table>
               <table class="tablesorterborrower" border="0" cellpadding="0" cellspacing="1">
                 <tr>
                     <th width="70">%s</th> <td class="bibcirccontent">%s</td>
                 </tr>
                 <tr>
                     <th width="70">%s</th> <td class="bibcirccontent">%s</td>
                 </tr>
                 <tr>
                     <th width="70">%s</th> <td class="bibcirccontent">%s</td>
                 </tr>
                 <tr>
                     <th width="70">%s</th> <td class="bibcirccontent">%s</td>
                 </tr>
                 <tr>
                     <th width="70">%s</th> <td class="bibcirccontent">%s</td>
                  </tr>
                 </table>
                 <br />
                 <table class="bibcirctable">
                 <tr align="center">
                   <td>
                        <input type=button value="%s" onClick="history.go(-1)" class="formbutton">
                        <input type="submit"   value="%s" class="formbutton">
                        <input type=hidden name=name value="%s">
                        <input type=hidden name=email value="%s">
                        <input type=hidden name=phone value="%s">
                        <input type=hidden name=address value="%s">
                        <input type=hidden name=notes value="%s">
                   </td>
                  </tr>
                 </table>
                 <br />
                 <br />
                 </form>
                 </div>
                 """ % (CFG_SITE_URL, _("New vendor information"),
                        _("Name"), name,
                        _("Email"), email,
                        _("Phone"), phone,
                        _("Address"), address,
                        _("Notes"), notes,
                        _("Back"), _("Confirm"),
                        name, email, phone, address, notes)
 
         return out
 
     def tmpl_add_new_vendor_step3(self, ln=CFG_SITE_LANG):
         """
         @param ln: language
         """
 
         _ = gettext_set_language(ln)
 
         out = """ """
 
         out += load_menu(ln)
 
         out += """
             <div class="bibcircbottom">
               <br />
               <br />
               <table class="bibcirctable">
                 <tr>
                     <td class="bibcirccontent">%s</td>
                 </tr>
                 </table>
                 <br />
                 <table class="bibcirctable">
                 <tr>
                   <td>
                        <input type=button value="%s"
                 onClick="location.href='%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s'"
                         class="formbutton">
                   </td>
                  </tr>
                 </table>
                 <br />
                 <br />
                 </div>
                 """ % (_("A new vendor has been registered."),
                        _("Back to home"),
                        CFG_SITE_URL, ln)
 
         return out
 
     def tmpl_update_vendor_info_step1(self, infos, ln=CFG_SITE_LANG):
         """
         @param infos: informations
         @type infos: list
 
         @param ln: language
         """
         _ = gettext_set_language(ln)
 
         out = self.tmpl_infobox(infos, ln)
 
         out += load_menu(ln)
 
         out += """
         <div class="bibcircbottom">
         <br />
         <br />
         <br />
         <form name="update_vendor_info_step1_form"
               action="%s/admin2/bibcirculation/update_vendor_info_step2"
               method="get" >
             <table class="bibcirctable">
                 <tr align="center">
                     <td class="bibcirctableheader">%s
                         <input type="radio" name="column" value="name" checked>%s
                         <input type="radio" name="column" value="email">%s
                         <br>
                         <br>
                     </td>
                 </tr>
                 """ % (CFG_SITE_URL,
                        _("Search vendor by"),
                        _("name"),
                        _("email"))
 
         out += """
                 <tr align="center">
                     <td>
                         <input type="text" size="45" name="string"
                                style='border: 1px solid #cfcfcf'>
                     </td>
                 </tr>
             </table>
             <br />
             <table class="bibcirctable">
                 <tr align="center">
                     <td>
                         <input type=button value='%s'
                                onClick="history.go(-1)" class="formbutton">
                         <input type="submit" value="%s" class="formbutton">
                     </td>
                 </tr>
             </table>
         <form>
         <br />
         <br />
         <br />
         <br />
         </div>
         """ % (_("Back"), _("Search"))
 
         return out
 
     def tmpl_update_vendor_info_step2(self, result, ln=CFG_SITE_LANG):
         """
         @param result: search result
         @type result: list
 
         @param ln: language
         """
 
         _ = gettext_set_language(ln)
 
         out = """ """
 
         out += load_menu(ln)
 
         out += """
         <style type="text/css"> @import url("/img/tablesorter.css"); </style>
         <div class="bibcircbottom" align="center">
         <br />
         <table class="bibcirctable">
           <tr align="center">
             <td class="bibcirccontent">
               <strong>%s vendor(s) found</strong>
             </td>
           </tr>
         </table>
         <br />
         <table class="tablesortersmall" border="0" cellpadding="0" cellspacing="1">
           <tr align="center">
             <th>%s</th>
           </tr>
 
         """ % (len(result), _("Vendor(s)"))
 
         for (vendor_id, name) in result:
             vendor_link = create_html_link(CFG_SITE_URL +
                             '/admin2/bibcirculation/update_vendor_info_step3',
                             {'vendor_id': vendor_id, 'ln': ln}, (name))
 
             out += """
             <tr align="center">
                  <td class="bibcirccontent" width="70">%s
                  <input type=hidden name=vendor_id value="%s"></td>
             </tr>
             """ % (vendor_link, vendor_id)
 
 
         out += """
              </table>
              <br />
              """
 
         out += """
         <table class="bibcirctable">
              <tr align="center">
                   <td><input type=button value="%s"
                        onClick="history.go(-1)" class="formbutton"></td>
              </tr>
         </table>
         <br />
         <br />
         <br />
         </form>
         </div>
         """ % (_("Back"))
 
         return out
 
     def tmpl_update_vendor_info_step3(self, vendor_info, ln=CFG_SITE_LANG):
         """
         @param vendor_infos: information about a given vendor
         @type vendor_infos: tuple
         """
 
         _ = gettext_set_language(ln)
 
         (vendor_id, name, address, email, phone, _notes) = vendor_info
 
         out = """ """
 
         out += load_menu(ln)
 
         out += """
             <style type="text/css"> @import url("/img/tablesorter.css"); </style>
             <div class="bibcircbottom" align="center">
             <form name="update_vendor_info_step3_form" action="%s/admin2/bibcirculation/update_vendor_info_step4" method="get" >
              <input type=hidden name=vendor_id value="%s">
               <br />
               <br />
               <table class="bibcirctable">
                 <tr align="center">
                      <td class="bibcirctableheader">%s</td>
                 </tr>
               </table>
               <table class="tablesorterborrower" border="0" cellpadding="0" cellspacing="1">
                 <tr>
                     <th width="70">%s</th>
                     <td class="bibcirccontent">
                       <input type="text" style='border: 1px solid #cfcfcf' size=45 name="name" value="%s">
                     </td>
                 </tr>
                 <tr>
                     <th width="70">%s</th>
                     <td class="bibcirccontent">
                       <input type="text" style='border: 1px solid #cfcfcf' size=45 name="email" value="%s">
                     </td>
                 </tr>
                 <tr>
                     <th width="70">%s</th>
                     <td class="bibcirccontent">
                       <input type="text" style='border: 1px solid #cfcfcf' size=45 name="phone" value="%s">
                     </td>
                 </tr>
                 <tr>
                     <th width="70">%s</th>
                     <td class="bibcirccontent">
                       <input type="text" style='border: 1px solid #cfcfcf' size=45 name="address" value="%s">
                     </td>
                  </tr>
                 </table>
                 <br />
                 <table class="bibcirctable">
                 <tr align="center">
                   <td>
                        <input type=button value="%s"
                         onClick="history.go(-1)" class="formbutton">
 
                        <input type="submit"
                        value="%s" class="formbutton">
 
                   </td>
                  </tr>
                 </table>
                 <br />
                 <br />
                 </form>
                 </div>
                 """ % (CFG_SITE_URL, vendor_id, _("Vendor information"),
                        _("Name"), name,
                        _("Email"), email,
                        _("Phone"), phone,
                        _("Address"), address,
                        _("Back"), _("Continue"))
 
 
         return out
 
     def tmpl_update_vendor_info_step4(self, tup_infos, ln=CFG_SITE_LANG):
         """
         @param tup_infos: information about a given vendor
         @type tup_infos: tuple
         """
 
         (vendor_id, name, email, phone, address) = tup_infos
 
         _ = gettext_set_language(ln)
 
         out = """ """
 
         out += load_menu(ln)
 
         out += """
             <style type="text/css"> @import url("/img/tablesorter.css"); </style>
             <div class="bibcircbottom" align="center">
             <form name="update_vendor_info_step4_form" action="%s/admin2/bibcirculation/update_vendor_info_step5" method="get" >
               <br />
               <br />
               <table class="bibcirctable">
                 <tr align="center">
                      <td class="bibcirctableheader">%s</td>
                 </tr>
               </table>
               <table class="tablesorterborrower" border="0" cellpadding="0" cellspacing="1">
                 <tr>
                     <th width="70">%s</th> <td class="bibcirccontent">%s</td>
                 </tr>
                 <tr>
                     <th width="70">%s</th> <td class="bibcirccontent">%s</td>
                 </tr>
                 <tr>
                     <th width="70">%s</th> <td class="bibcirccontent">%s</td>
                 </tr>
                 <tr>
                     <th width="70">%s</th> <td class="bibcirccontent">%s</td>
                  </tr>
                 </table>
                 <br />
                 <table class="bibcirctable">
                 <tr align="center">
                   <td>
                        <input type=button value="%s"
                         onClick="history.go(-1)" class="formbutton">
 
                        <input type="submit"
                        value="%s" class="formbutton">
 
                        <input type=hidden name=vendor_id value="%s">
                        <input type=hidden name=name value="%s">
                        <input type=hidden name=email value="%s">
                        <input type=hidden name=phone value="%s">
                        <input type=hidden name=address value="%s">
                   </td>
                  </tr>
                 </table>
                 <br />
                 <br />
                 </form>
                 </div>
                 """ % (CFG_SITE_URL, _("Vendor information"),
                        _("Name"), name,
                        _("Email"), email,
                        _("Phone"), phone,
                        _("Address"), address,
                        _("Back"), _("Continue"),
                        vendor_id, name, email, phone, address)
 
         return out
 
     def tmpl_update_vendor_info_step5(self, ln=CFG_SITE_LANG):
         """
         @param ln: language
         """
 
         _ = gettext_set_language(ln)
 
         out = """ """
 
         out += load_menu(ln)
 
         out += """
             <div class="bibcircbottom">
               <br />
               <br />
               <table class="bibcirctable">
                 <tr>
                     <td class="bibcirccontent">%s</td>
                 </tr>
                 </table>
                 <br />
                 <table class="bibcirctable">
                 <tr>
                   <td>
                        <input type=button value="%s"
                  onClick="location.href='%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s'"
                         class="formbutton">
                   </td>
                  </tr>
                 </table>
                 <br />
                 <br />
                 </div>
                 """ % (_("The information has been updated."),
                        _("Back to home"),
                        CFG_SITE_URL, ln)
 
         return out
 
     def tmpl_search_vendor_step1(self, infos, ln=CFG_SITE_LANG):
         """
         @param infos: informations
         @type infos: list
 
         @param ln: language
         """
         _ = gettext_set_language(ln)
 
         out = self.tmpl_infobox(infos, ln)
 
         out += load_menu(ln)
 
         out += """
         <div class="bibcircbottom">
         <br />
         <br />
         <br />
         <form name="search_vendor_step1_form"
               action="%s/admin2/bibcirculation/search_vendor_step2"
               method="get" >
           <table class="bibcirctable">
            <tr align="center">
              <td class="bibcirctableheader">%s
                <input type="radio" name="column" value="name" checked>%s
                <input type="radio" name="column" value="email">%s
                <br>
                <br>
              </td>
            </tr>
            """ % (CFG_SITE_URL,
                   _("Search vendor by"),
                   _("name"),
                   _("email"))
 
         out += """
            <tr align="center">
              <td>
                 <input type="text" size="45" name="string" id='string'
                        style='border: 1px solid #cfcfcf'>
                 <script language="javascript" type="text/javascript">
                     document.getElementById("string").focus();
                 </script>
              </td>
            </tr>
           </table>
           <br />
           <table class="bibcirctable">
              <tr align="center">
                   <td>
                         <input type=button value='%s'
                           onClick="history.go(-1)" class="formbutton">
                         <input type="submit" value='%s' class="formbutton">
                   </td>
              </tr>
         </table>
         <form>
         <br />
         <br />
         <br />
         <br />
         </div>
 
         """ % (_("Back"), _("Search"))
 
 
         return out
 
     def tmpl_search_vendor_step2(self, result, ln=CFG_SITE_LANG):
         """
         @param result: search result
         @type result:list
 
         @param ln: language
         """
 
         _ = gettext_set_language(ln)
 
         out = """ """
 
         out += load_menu(ln)
 
         out += """
         <style type="text/css"> @import url("/img/tablesorter.css"); </style>
         <div class="bibcircbottom" align="center">
         <br />
         <table class="bibcirctable">
           <tr align="center">
             <td class="bibcirccontent">
               <strong>%s vendor(s) found</strong>
             </td>
           </tr>
         </table>
         <br />
         <table class="tablesortersmall" border="0" cellpadding="0" cellspacing="1">
           <tr align="center">
              <th>%s</th>
            </tr>
         """ % (len(result), _("Vendor(s)"))
 
         for (vendor_id, name) in result:
 
             vendor_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_vendor_details',
                                 {'vendor_id': vendor_id, 'ln': ln}, (name))
 
             out += """
             <tr align="center">
                  <td class="bibcirccontent" width="70">%s
                  <input type=hidden name=library_id value="%s"></td>
             </tr>
             """ % (vendor_link, vendor_id)
 
         out += """
         </table>
         <br />
         <table class="bibcirctable">
              <tr align="center">
                   <td>
                     <input type=button value="%s"
                      onClick="history.go(-1)" class="formbutton"></td>
              </tr>
         </table>
         <br />
         <br />
         <br />
         </form>
         </div>
 
         """ % (_("Back"))
 
         return out
 
     def tmpl_vendor_details(self, vendor_details, ln=CFG_SITE_LANG):
         """
         @param vendor_details: details about a given vendor
         @type vendor_details: tuple
 
         @param ln: language of the page
         """
         _ = gettext_set_language(ln)
 
         out = """
         """
         out += load_menu(ln)
 
         out += """
         <div class="bibcircbottom" align="center">
         <br />
         <style type="text/css"> @import url("/img/tablesorter.css"); </style>
         """
         (vendor_id, name, address, email, phone, notes) = vendor_details
 
         no_notes_link = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_vendor_notes',
                                     {'vendor_id': vendor_id},
                                     (_("No notes")))
 
         see_notes_link = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_vendor_notes',
                                     {'vendor_id': vendor_id},
                                     (_("Notes about this vendor")))
 
         if notes == "":
             notes_link = no_notes_link
         else:
             notes_link = see_notes_link
 
         out += """
             <table class="bibcirctable">
                  <tr align="center">
                       <td width="80" class="bibcirctableheader">%s</td>
                  </tr>
             </table>
             <table class="tablesorterborrower" border="0" cellpadding="0" cellspacing="1">
 
                  <tr>
                       <th width="80">%s</th>
                       <td class="bibcirccontent">%s</td>
                  </tr>
                  <tr>
                       <th width="80">%s</th>
                       <td class="bibcirccontent">%s</td>
                  </tr>
                  <tr>
                       <th width="80">%s</th>
                       <td class="bibcirccontent">%s</td>
                  </tr>
                  <tr>
                       <th width="80">%s</th>
                       <td class="bibcirccontent">%s</td>
                  </tr>
                  <tr>
                       <th width="80">%s</th>
                       <td class="bibcirccontent">%s</td>
                  </tr>
                  </table>
                  <table>
                  <tr>
                       <td><input type=button onClick="location.href='%s/admin2/bibcirculation/update_vendor_info_step3?vendor_id=%s'" onmouseover="this.className='bibcircbuttonover'" onmouseout="this.className='bibcircbutton'"
                       value="%s"  class="bibcircbutton">
                       </td>
                  </tr>
             </table>
             """ % (_("Vendor details"),
                    _("Name"), name,
                    _("Address"), address,
                    _("Email"), email,
                    _("Phone"), phone,
                    _("Notes"), notes_link,
                    CFG_SITE_URL, vendor_id, _("Update"))
 
         out += """
            </table>
            <br />
            <br />
            <table class="bibcirctable">
                 <tr align="center">
                      <td><input type=button value='%s'
                           onClick="history.go(-1)" class="formbutton"></td>
                 </tr>
            </table>
            <br />
            <br />
            <br />
            </form>
            </div>
            """ % (_("Back"))
 
         return out
 
     def tmpl_vendor_notes(self, vendor_notes, vendor_id, add_notes,
                           ln=CFG_SITE_LANG):
 
         _ = gettext_set_language(ln)
 
         out = """ """
 
         out += load_menu(ln)
 
         out += """
             <div class="bibcircbottom">
             <form name="vendor_notes" action="%s/admin2/bibcirculation/get_vendor_notes" method="get" >
             <br />
             <br />
             <table class="bibcirctable">
                   <tr>
                      <td class="bibcirctableheader">%s</td>
                   </tr>
                   """ % (CFG_SITE_URL,
                          _("Notes about this vendor"))
 
         notes = vendor_notes.split('\n')
 
 
         for values in notes:
             out += """ <tr>
                         <td class="bibcirccontent">%s</td>
                        </tr>
                        """ % (values)
 
         if add_notes:
             out += """
                 <tr>
                   <td><textarea name='new_note' rows="10" cols="60" style='border: 1px solid #cfcfcf'></textarea></td>
                   </tr>
                    <tr>
                   <td>
                       <input type='submit' name='confirm_note' value='%s' class='formbutton'>
                       <input type=hidden name=vendor_id value="%s">
                   </td>
              </tr>
             </table>
 
             """ % (_("Confirm"), vendor_id)
 
         else:
             out += """
                 <tr><td></td></tr>
                 <tr><td></td></tr>
                 <tr><td></td></tr>
                 <tr>
                   <td>
                        <input type='submit' name='add_notes' value='%s' class='formbutton'>
                        <input type=hidden name=vendor_id value="%s">
                   </td>
              </tr>
             </table>
 
             """ % (_("Add notes"), vendor_id)
 
         out += """
             <br />
             <br />
              <table class="bibcirctable">
              <tr>
                   <td>
                        <input type=button
         onClick="location.href='%s/admin2/bibcirculation/get_vendor_details?vendor_id=%s&ln=%s'"
                        value="%s" class='formbutton'>
                   </td>
              </tr>
              </table>
              <br />
              <br />
              <br />
              </form>
              </div>
         """ % (CFG_SITE_URL,
                vendor_id, ln,
                _("Back"))
 
         return out
 
     def tmpl_register_ill_request_with_no_recid_step1(self, infos, borrower_id,
                                                       admin=True,
                                                       ln=CFG_SITE_LANG):
         """
         @param infos: informations
         @type infos: list
         """
 
         _ = gettext_set_language(ln)
 
         if admin:
             form_url = CFG_SITE_URL + '/admin2/bibcirculation/register_ill_request_with_no_recid_step2'
         else:
             form_url = CFG_SITE_URL+'/ill/book_request_step2'
 
 
         out = self.tmpl_infobox(infos, ln)
 
         if admin:
             out += load_menu(ln)
 
             out += """
             <br />
             <br />
               <div class="bibcircbottom" align="center">
               <div class="bibcircinfoboxmsg"><strong>%s<br />%s</strong></div>
               <br />
               <br />
             """ % (_("Book does not exists in %(CFG_SITE_NAME)s") % \
                         {'CFG_SITE_NAME': CFG_SITE_NAME},
                    _("Please fill the following form."))
 
         out += """
           <style type="text/css"> @import url("/img/tablesorter.css"); </style>
            <form name="display_ill_form" action="%s" method="get">
            """ % (form_url)
         out += """
              <table class="bibcirctable">
                   <tr align="center">
                     <td class="bibcirctableheader">%s</td>
                   </tr>
                 </table>
             """ % (_("Item details"))
 
         if borrower_id not in (None, ''):
             out += """
                 <input type=hidden name=borrower_id value="%s">
             """ % (borrower_id)
 
         out += """
                 <table class="tablesorterborrower" border="0" cellpadding="0" cellspacing="1">
                     <tr>
                         <th width="100">%s</th>
                         <td>
                           <input type="text" size="45" name="title" style='border: 1px solid #cfcfcf'>
                         </td>
                     </tr>
                     <tr>
                         <th width="100">%s</th>
                         <td>
                           <input type="text" size="45" name="authors" style='border: 1px solid #cfcfcf'>
                         </td>
                     </tr>
                     <tr>
                         <th width="100">%s</th>
                         <td>
                           <input type="text" size="30" name="place" style='border: 1px solid #cfcfcf'>
                         </td>
                     </tr>
                     <tr>
                         <th width="100">%s</th>
                         <td>
                           <input type="text" size="30" name="publisher" style='border: 1px solid #cfcfcf'>
                         </td>
                     </tr>
                     <tr>
                         <th width="100">%s</th>
                         <td>
                           <input type="text" size="30" name="year" style='border: 1px solid #cfcfcf'>
                         </td>
                     </tr>
                     <tr>
                         <th width="100">%s</th>
                         <td>
                           <input type="text" size="30" name="edition" style='border: 1px solid #cfcfcf'>
                         </td>
                     </tr>
                     <tr>
                         <th width="100">%s</th>
                         <td>
                           <input type="text" size="30" name="isbn" style='border: 1px solid #cfcfcf'>
                         </td>
                     </tr>
                 </table>
 
 
            <br />
 
            """ % (_("Book title"),
                    _("Author(s)"),
                    _("Place"),
                    _("Publisher"),
                    _("Year"),
                    _("Edition"),
                    _("ISBN"))
 
         out += """
         <script type="text/javascript" language='JavaScript' src="%s/js/jquery/jquery.ui.datepicker.min.js"></script>
 
              <table class="bibcirctable">
                 <tr align="center">
                      <td class="bibcirctableheader">%s</td>
                 </tr>
              </table>
              <table class="tablesorterborrower" border="0" cellpadding="0" cellspacing="1">
              <!--
                 <tr>
                     <th width="100">%s</th>
                     <td>
                         <input type="text" size="30" name="budget_code" style='border: 1px solid #cfcfcf'>
                     </td>
                 </tr>
                 -->
                 <tr>
                     <th valign="center" width="100">%s</th>
                     <td valign="center" width="250">
 
                         <script type="text/javascript">
                              $(function() {
                                  $("#date_picker1").datepicker({dateFormat: 'yy-mm-dd', showOn: 'button', buttonImage: "%s/img/jquery/calendar.gif", buttonImageOnly: true});
                              });
                          </script>
                          <input type="text" size="10" id="date_picker1" name="period_of_interest_from" value="%s" style='border: 1px solid #cfcfcf'>
 
                     </td>
                 </tr>
                 """% (CFG_SITE_URL,
                       _("ILL request details"), _("Budget code"),
                       _("Period of interest (From)"),
                       CFG_SITE_URL,
                     datetime.date.today().strftime('%Y-%m-%d'))
 
         out += """
                 <tr>
                 <th valign="top" width="100">%s</th>
                 <td width="250">
 
                         <script type="text/javascript">
                              $(function() {
                                  $("#date_picker2").datepicker({dateFormat: 'yy-mm-dd', showOn: 'button', buttonImage: "%s/img/jquery/calendar.gif", buttonImageOnly: true});
                              });
                          </script>
                          <input type="text" size="10" id="date_picker2" name="period_of_interest_to" value="%s" style='border: 1px solid #cfcfcf'>
 
                     </td>
                 </tr>
                 <tr>
                    <th valign="top" width="100">%s</th>
                    <td width="250"><textarea name='additional_comments' rows="6" cols="34"
                    style='border: 1px solid #cfcfcf'></textarea></td>
                 </tr>
               </table>
               <table class="bibcirctable">
               <!--<tr>
                   <td>
                     <input name="conditions" type="checkbox" value="accepted" />%s</td>
                 </tr> -->
                 <tr align="center">
                   <td>
                     <input name="only_edition" type="checkbox" value="Yes" />%s</td>
                 </tr>
              </table>
              <br />
              <table class="bibcirctable">
                 <tr align="center">
                   <td>
                        <input type=button value="%s"
                         onClick="history.go(-1)" class="formbutton">
 
                        <input type="submit"
                        value="%s" class="formbutton">
 
                   </td>
                  </tr>
              </table>
              </form>
              <br />
              <br />
              </div>
              """ % (_("Period of interest (To)"), CFG_SITE_URL,
     (datetime.date.today() + datetime.timedelta(days=365)).strftime('%Y-%m-%d'),
     _("Additional comments"),
     _("Borrower accepts the %(x_url_open)sconditions%(x_url_close)s of the service in particular the return of books in due time.") % {'x_url_open': '<a href="http://library.web.cern.ch/library/Library/ill_faq.html" target="_blank">', 'x_url_close': '</a>'},
     _("Borrower wants this edition only."), _("Back"), _("Continue"))
 
         return out
 
     def tmpl_register_ill_request_with_no_recid_step2(self, book_info,
                                                       request_details, result,
                                                       key, string, infos, ln):
         """
         @param book_info: book's informations
         @type book_info: tuple
 
         @param request_details: details about a given request
         @type request_details: tuple
 
         @param result: borrower's informations
         @type result: list
 
         @param key: field (name, email, etc...)
         @param key: string
 
         @param string: pattern
         @type string: string
 
         @param infos: informations
         @type infos: list
         """
 
         (title, authors, place, publisher, year, edition, isbn) = book_info
 
         (budget_code, period_of_interest_from, period_of_interest_to,
          additional_comments, only_edition)= request_details
 
         _ = gettext_set_language(ln)
 
         out = self.tmpl_infobox(infos, ln)
 
         out += load_menu(ln)
 
         #if isbn:
         #    book_cover = get_book_cover(isbn)
         #else:
         #    book_cover = "%s/img/book_cover_placeholder.gif" % (CFG_SITE_URL)
 
         out += """
         <style type="text/css"> @import url("/img/tablesorter.css"); </style>
         <div class="bibcircbottom">
          <form name="step1_form1" action="%s/admin2/bibcirculation/register_ill_request_with_no_recid_step2" method="get" >
         <br />
 
                 <table class="bibcirctable">
                   <tr>
                     <td width="500" valign='top'>
                        <table class="bibcirctable">
                         <tr>
                             <td class="bibcirctableheader" width="10">%s</td>
                         </tr>
                        </table>
                       <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=title value="%s">
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=authors value="%s">
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=place value="%s">
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=year value="%s">
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=publisher value="%s">
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=edition value="%s">
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=isbn value="%s">
                         </tr>
                       </table>
                       <table>
                          <tr>
                            <td class="bibcirctableheader">%s</td>
                         </tr>
                        </table>
                        <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                        <!--
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=budget_code value="%s">
                         </tr>
                         -->
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=period_of_interest_from value="%s">
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=period_of_interest_to value="%s">
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=additional_comments value="%s">
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=only_edition value="%s">
                         </tr>
                       </table>
                      </td>
                      <td width="200" align='center' valign='top'>
                        <table>
                          <tr>
                            <td>
 
                            </td>
                          </tr>
                        </table>
                      </td>
                      """ % (CFG_SITE_URL,
                 _("Item details"),
                 _("Name"), title, title,
                 _("Author(s)"), authors, authors,
                 _("Place"), place, place,
                 _("Year"), year, year,
                 _("Publisher"), publisher, publisher,
                 _("Edition"), edition, edition,
                 _("ISBN"), isbn, isbn,
                 _("ILL request details"),
                 _("Budget code"), budget_code, budget_code,
                 _("Period of interest - From"),
                 period_of_interest_from, period_of_interest_from,
                 _("Period of interest - To"),
                 period_of_interest_to, period_of_interest_to,
                 _("Additional comments"),
                 additional_comments, additional_comments,
                 _("Only this edition."), only_edition, only_edition)
 
 #<img style='border: 1px solid #cfcfcf' src="%s" alt="Book Cover"/> ,
                          #   str(book_cover)
         out += """
         <td valign='top' align='center'>
          <table>
 
             """
 
         if CFG_CERN_SITE == 1:
             out += """
                 <tr>
                    <td class="bibcirctableheader" align="center">%s
                    """ % (_("Search user by"))
 
             if key == 'email':
                 out += """
                    <input type="radio" name="key" value="ccid">%s
                    <input type="radio" name="key" value="name">%s
                    <input type="radio" name="key" value="email" checked>%s
                    """ % ('ccid', _('name'), _('email'))
 
             elif key == 'name':
                 out += """
                    <input type="radio" name="key" value="ccid">%s
                    <input type="radio" name="key" value="name" checked>%s
                    <input type="radio" name="key" value="email">%s
                    """ % ('ccid', _('name'), _('email'))
 
             else:
                 out += """
                    <input type="radio" name="key" value="ccid" checked>%s
                    <input type="radio" name="key" value="name">%s
                    <input type="radio" name="key" value="email">%s
                    """ % ('ccid', _('name'), _('email'))
 
         else:
             out += """
                  <tr>
                    <td align="center" class="bibcirctableheader">%s
                    """ % (_("Search borrower by"))
 
             if key == 'email':
                 out += """
                    <input type="radio" name="key" value="id">%s
                    <input type="radio" name="key" value="name">%s
                    <input type="radio" name="key" value="email" checked>%s
                    """ % (_('id'), _('name'), _('email'))
 
             elif key == 'id':
                 out += """
                    <input type="radio" name="key" value="id" checked>%s
                    <input type="radio" name="key" value="name">%s
                    <input type="radio" name="key" value="email">%s
                    """ % (_('id'), _('name'), _('email'))
 
             else:
                 out += """
                    <input type="radio" name="key" value="id">%s
                    <input type="radio" name="key" value="name" checked>%s
                    <input type="radio" name="key" value="email">%s
                    """ % (_('id'), _('name'), _('email'))
 
 
         out += """
                     <br><br>
                     </td>
                     </tr>
                     <tr>
                     <td align="center">
                     <input type="text" size="40" id="string" name="string"
                             value='%s' style='border: 1px solid #cfcfcf'>
                     </td>
                     </tr>
                     <tr>
                     <td align="center">
                     <br>
                     <input type="submit" value="%s" class="formbutton">
                     </td>
                     </tr>
 
                    </table>
           </form>
 
         """ % (string or '', _("Search"))
 
         if result:
             out += """
             <br />
             <form name="step1_form2"
                   action="%s/admin2/bibcirculation/register_ill_request_with_no_recid_step3"
                   method="get" >
             <input type=hidden name=title value="%s">
             <input type=hidden name=authors value="%s">
             <input type=hidden name=place value="%s">
             <input type=hidden name=publisher value="%s">
             <input type=hidden name=year value="%s">
             <input type=hidden name=edition value="%s">
             <input type=hidden name=isbn value="%s">
 
             <table class="bibcirctable">
               <tr width="200">
                 <td align="center">
                   <select name="user_info" size="8"
                           style='border: 1px solid #cfcfcf; width:80%%'>
 
             """ % (CFG_SITE_URL, title, authors, place,
                    publisher, year, edition, isbn)
                    #book_info)
 
             for (borrower_id, ccid, name, email,
                  phone, address, mailbox) in result:
                 out += """
                        <option value ='%s,%s,%s,%s,%s,%s,%s'>%s
                        """ % (borrower_id, ccid, name, email, phone,
                               address, mailbox, name)
 
             out += """
                     </select>
                     </td>
                     </tr>
                     </table>
                     <table class="bibcirctable">
                     <tr>
                         <td align="center">
                         <input type="submit" value='%s' class="formbutton">
                         </td>
                     </tr>
                     </table>
                     <!-- <input type=hidden name=budget_code value="%s"> -->
                     <input type=hidden name=period_of_interest_from value="%s">
                     <input type=hidden name=period_of_interest_to value="%s">
                     <input type=hidden name=additional_comments value="%s">
                     <input type=hidden name=only_edition value="%s">
                     </form>
                     """ % (_("Select user"), budget_code,
                                             period_of_interest_from,
                                             period_of_interest_to,
                                             additional_comments,
                                             only_edition)
                            #request_details)
 
         out += """
                   </td>
                 </tr>
               </table>
               <br />
               <br />
               <br />
               <br />
               </div>
               """
 
         return out
 
     def tmpl_register_ill_request_with_no_recid_step3(self, book_info,
                                                     user_info, request_details,
                                                     admin=True,
                                                     ln=CFG_SITE_LANG):
         """
         @param book_info: book's informations
         @type book_info: tuple
 
         @param user_info: user's informations
         @type user_info: tuple
 
         @param request_details: details about a given request
         @type request_details: tuple
         """
 
         _ = gettext_set_language(ln)
 
         if admin:
             form_url = CFG_SITE_URL+'/admin2/bibcirculation/register_ill_request_with_no_recid_step4'
         else:
             form_url = CFG_SITE_URL+'/ill/book_request_step3'
 
 
         (title, authors, place, publisher, year, edition, isbn) = book_info
 
         (borrower_id, ccid, name, email, phone, address, mailbox) = user_info
 
         display_id = borrower_id
         id_string = _("ID")
         if CFG_CERN_SITE == 1:
             display_id = ccid
             id_string = _("CCID")
 
         (budget_code, period_of_interest_from, period_of_interest_to,
          additional_comments, only_edition)= request_details
 
         out = ""
         if admin:
             out += load_menu(ln)
 
         out += """
         <style type="text/css"> @import url("/img/tablesorter.css"); </style>
         <div class="bibcircbottom">
         <form name="step3_form1" action="%s" method="post" >
         <br />
                 <table class="bibcirctable">
                   <tr>
                     <td width="200" valign='top'>
         """ % (form_url)
 
         out += """
                     <input type=hidden name=title value='%s'>
                     <input type=hidden name=authors value='%s'>
                     <input type=hidden name=place value='%s'>
                     <input type=hidden name=publisher value='%s'>
                     <input type=hidden name=year value='%s'>
                     <input type=hidden name=edition value='%s'>
                     <input type=hidden name=isbn value='%s'>
                 """ % (title, authors, place, publisher, year, edition, isbn)
 
         out += """
                     <!-- <input type=hidden name=budget_code value='%s'> -->
                     <input type=hidden name=period_of_interest_from value='%s'>
                     <input type=hidden name=period_of_interest_to value='%s'>
                     <input type=hidden name=additional_comments value='%s'>
                     <input type=hidden name=only_edition value='%s'>
                 """ % (budget_code, period_of_interest_from,
                     period_of_interest_to, additional_comments, only_edition)
 
         out += """    <table class="bibcirctable">
                         <tr>
                             <td class="bibcirctableheader" width="10">%s</td>
                         </tr>
                        </table>
                       <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                       </table>
                       """ % (_("Item details"),
                             _("Title"), title,
                             _("Author(s)"), authors,
                             _("Place"), place,
                             _("Year"), year,
                             _("Publisher"), publisher,
                             _("Edition"), edition,
                             _("ISBN"), isbn)
 
         out += """
                       <table>
                          <tr>
                            <td class="bibcirctableheader">%s</td>
                         </tr>
                        </table>
                        <table class="tablesorter" border="0"
                               cellpadding="0" cellspacing="1">
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td>
                         </tr>
                       </table>
                      </td>
                      <td width="50" valign='top'>
                        <table>
                          <tr>
                            <td>
 
                            </td>
                          </tr>
                        </table>
                      </td>
                 """ % (_("ILL request details"),
                     _("Budget code"), budget_code,
                     _("Period of interest (From)"), period_of_interest_from,
                     _("Period of interest (To)"), period_of_interest_to,
                     _("Additional comments"), additional_comments,
                     _("Only this edition"), only_edition)
 
         out += """
                     <td width="200" valign='top'>
 
                             <table>
                                 <tr align="center">
                                   <td class="bibcirctableheader">%s</td>
                                   <input type=hidden name=borrower_id value="%s">
                                 </tr>
                             </table>
                             <table class="tablesorter" width="200" border="0"
                                     cellpadding="0" cellspacing="1">
                                 <tr>
                                  <th width="100">%s</th>
                                  <td>%s</td>
                                 </tr>
                                 <tr>
                                  <th width="100">%s</th>
                                  <td>%s</td>
                                 </tr>
                                 <tr>
                                  <th width="100">%s</th>
                                  <td>%s</td>
                                 </tr>
                                 <tr>
                                  <th width="100">%s</th>
                                  <td>%s</td>
                                 </tr>
                                 <tr>
                                  <th width="100">%s</th>
                                  <td>%s</td>
                                 </tr>
                                 <tr>
                                  <th width="100">%s</th>
                                  <td>%s</td>
                                 </tr>
                             </table>
 
                     </td>
                 </tr>
             </table>
                       """ % (_("Borrower details"), borrower_id,
                              id_string, display_id,
                              _("Name"), name,
                              _("Address"), address,
                              _("Mailbox"), mailbox,
                              _("Email"), email,
                              _("Phone"), phone)
 
         out += """<br />
                   <table class="bibcirctable">
                     <tr align="center">
                       <td>
                         <input type=button value="%s"
                         onClick="history.go(-1)" class="formbutton">
 
                        <input type="submit"
                        value="%s" class="formbutton">
                       </td>
                     </tr>
                 </table>""" % (_("Back"), _("Continue"))
 
 
         return out
 
     def tmpl_borrower_ill_details(self, result, borrower_id,
                                   ln=CFG_SITE_LANG):
         """
         @param result: ILL request's informations:
         @type result: list
 
         @param borrower_id: identify the borrower. Primary key of crcBORROWER.
         @type borrower_id: int
 
         @param ill_id: identify the ILL request. Primray key of crcILLREQUEST
         @type ill_id: int
 
         @param ln: language of the page
         """
         _ = gettext_set_language(ln)
 
         out = load_menu(ln)
 
         out += """
         <style type="text/css"> @import url("/img/tablesorter.css"); </style>
         <script src="/js/jquery/jquery.js" type="text/javascript"></script>
         <script src="/js/jquery/jquery.tablesorter.js" type="text/javascript"></script>
         <script type="text/javascript">
         $(document).ready(function() {
           $('#table_ill').tablesorter({widthFixed: true, widgets: ['zebra']})
         });
         </script>
         <div class="bibcircbottom">
         <br />
         <table id="table_ill" class="tablesorter" border="0"
                cellpadding="0" cellspacing="1">
         <thead>
           <tr>
             <th>%s</th>
             <th>%s</th>
             <th>%s</th>
             <th>%s</th>
             <th>%s</th>
             <th>%s</th>
             <th>%s</th>
             <th>%s</th>
             <th>%s</th>
           </tr>
         </thead>
         <tbody>
          """ % (_("ILL ID"),
                 _("Item"),
                 _("Supplier"),
                 _("Request date"),
                 _("Expected date"),
                 _("Arrival date"),
                 _("Due date"),
                 _("Status"),
                 _("Library notes"))
 
         for (ill_id, book_info, supplier_id, request_date,
              expected_date, arrival_date, due_date, status,
              library_notes, request_type) in result:
 
             #get supplier name
             if supplier_id:
                 if request_type in CFG_BIBCIRCULATION_ACQ_TYPE:
                     library_name = db.get_vendor_name(supplier_id)
                     library_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_vendor_details',
                                 {'vendor_id': supplier_id, 'ln': ln},
                                 (library_name))
                 else:
                     library_name = db.get_library_name(supplier_id)
                     library_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_library_details',
                                 {'library_id': supplier_id, 'ln': ln},
                                 (library_name))
             else:
                 library_link = '-'
 
             #get book title
             book_info = eval(book_info)
             try:
                 title_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_item_details',
                                 {'recid': book_info['recid'], 'ln': ln},
                                 (book_title_from_MARC(int(book_info['recid']))))
             except KeyError:
                 title_link = book_info['title']
 
             if request_type in CFG_BIBCIRCULATION_ACQ_TYPE:
                 ill_id_link = create_html_link(CFG_SITE_URL +
                             '/admin2/bibcirculation/acq_details_step1',
                             {'ill_request_id': str(ill_id), 'ln': ln},
                             str(ill_id))
             else:
                 ill_id_link = create_html_link(CFG_SITE_URL +
                             '/admin2/bibcirculation/ill_request_details_step1',
                             {'ill_request_id': str(ill_id), 'ln': ln},
                             str(ill_id))
 
             # links to notes pages
             lib_no_notes_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_ill_library_notes',
                                 {'ill_id': ill_id}, (_("No notes")))
 
             lib_see_notes_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_ill_library_notes',
                                 {'ill_id': ill_id}, (_("Notes about this ILL")))
 
             if library_notes == "":
                 notes_link = lib_no_notes_link
             else:
                 notes_link = lib_see_notes_link
 
             out += """
             <tr>
               <td>%s</td>
               <td>%s</td>
               <td>%s</td>
               <td>%s</td>
               <td>%s</td>
               <td>%s</td>
               <td>%s</td>
               <td>%s</td>
               <td>%s</td>
             </tr>
             """ % (ill_id_link, title_link, library_link, request_date,
                    expected_date, arrival_date, due_date, status,
                    notes_link)
 
         out += """
         </tbody>
         </table>
         <br />
         <table class="bibcirctable">
           <tr>
             <td>
               <input type=button
     onClick="location.href='%s/admin2/bibcirculation/get_borrower_details?borrower_id=%s&ln=%s'"
               value='%s' class='formbutton'>
             </td>
           </tr>
         </table>
         <br />
         </div>
         """ % (CFG_SITE_URL,
                borrower_id, ln,
                _("Back"))
 
         return out
 
     def tmpl_ill_notes(self, ill_notes, ill_id, ln=CFG_SITE_LANG):
         """
         @param ill_notes: notes about an ILL request
         @type ill_notes: dictionnary
 
         @param ill_id: identify the ILL request. Primray key of crcILLREQUEST
         @type ill_id: int
         """
 
         _ = gettext_set_language(ln)
 
         if not ill_notes:
             ill_notes = {}
         else:
             ill_notes = eval(ill_notes)
 
         out = """ """
 
         out += load_menu(ln)
 
         out += """
             <div class="bibcircbottom">
             <form name="borrower_notes"
                   action="%s/admin2/bibcirculation/get_ill_library_notes"
                   method="get" >
             <input type=hidden name=ill_id value='%s'>
             <br />
             <br />
             <table class="bibcirctable">
               <tr>
                 <td class="bibcirctableheader">%s</td>
               </tr>
             </table>
             <table class="bibcirctable">
               <tr>
                 <td>
                   <table class="bibcircnotes">
 
             """ % (CFG_SITE_URL, ill_id,
                    _("Notes about acquisition"))
 
         key_array = ill_notes.keys()
         key_array.sort()
 
         for key in key_array:
             delete_note = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_ill_library_notes',
                                 {'delete_key': key, 'ill_id': ill_id, 'ln': ln},
                                 (_("[delete]")))
 
             out += """<tr class="bibcirccontent">
                         <td class="bibcircnotes" width="160" valign="top"
                             align="center"><b>%s</b></td>
                         <td width="400"><i>%s</i></td>
                         <td width="65" align="center">%s</td>
                       </tr>
 
                       """ % (key, ill_notes[key], delete_note)
 
         out += """
                   </table>
                   </td>
               </tr>
             </table>
             <br />
             <table class="bibcirctable">
               <tr>
                 <td class="bibcirctableheader">%s</td>
               </tr>
             </table>
             <table class="bibcirctable">
               <tr>
                 <td class="bibcirccontent">
                   <textarea name="library_notes" rows="5" cols="90"
                             style='border: 1px solid #cfcfcf'>
                   </textarea>
                 </td>
               </tr>
             </table>
             <br />
             <table class="bibcirctable">
               <tr>
                   <td>
                     <input type=button
                            onClick="location.href='%s/admin2/bibcirculation/ordered_books?ln=%s'"
                            value="%s" class='formbutton'>
                     <input type="submit" value='%s' class="formbutton">
                   </td>
              </tr>
              </table>
              <br />
              <br />
              <br />
              </form>
              </div>
         """ % (_("Write new note"),
                CFG_SITE_URL,
                ln,
                _("Back"),
                _("Confirm"))
 
         return out
 
     def tmpl_get_expired_loans_with_requests(self, result, ln=CFG_SITE_LANG):
         """
         @param result: loans' informations:
         @param result: list
         """
 
         _ = gettext_set_language(ln)
 
         out = """ """
 
         out += load_menu(ln)
 
         if len(result) == 0:
             out += """
             <div class="bibcircbottom">
             <br /> <br />            <br /> <br />
             <table class="bibcirctable_contents">
                  <td class="bibcirccontent" align="center">%s</td>
             </table>
             <br /> <br />            <br />
             <table class="bibcirctable_contents">
             <td align="center">
             <input type=button
                    onClick="location.href='%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s'"
                    value='%s'
                    class='formbutton'>
             </td>
             </table>
             <br />
             </div>
             """ % (_("No more requests are pending or waiting."),
                    CFG_SITE_URL, ln,
                    _("Back to home"))
 
         else:
             out += """
             <style type="text/css"> @import url("/js/jquery/tablesorter/themes/blue/style.css"); </style>
             <style type="text/css"> @import url("/js/jquery/tablesorter/addons/pager/jquery.tablesorter.pager.css"); </style>
 
             <script src="/js/jquery/tablesorter/jquery.tablesorter.js" type="text/javascript"></script>
             <script src="/js/jquery/tablesorter/addons/pager/jquery.tablesorter.pager.js" type="text/javascript"></script>
             <script type="text/javascript">
 
             $(document).ready(function(){
                 $("#table_requests")
                     .tablesorter({sortList: [[4,0], [0,0]],widthFixed: true, widgets: ['zebra']})
                     .bind("sortStart",function(){$("#overlay").show();})
                     .bind("sortEnd",function(){$("#overlay").hide()})
                     .tablesorterPager({container: $("#pager"), positionFixed: false});
             });
             </script>
 
             <div class="bibcircbottom">
             <br />
             <br />
             <table id="table_requests" class="tablesorter" border="0" cellpadding="0" cellspacing="1">
             <thead>
               <tr>
                 <th>%s</th>
                 <th>%s</th>
                 <th>%s</th>
                 <th>%s</th>
                 <th>%s</th>
                 <th>%s</th>
                 <th>%s</th>
                 <th>%s</th>
               </tr>
             </thead>
             <tbody>
          """% (_("Name"),
                _("Item"),
                _('Library'),
                _("Location"),
                _("From"),
                _("To"),
                _("Request date"),
                _("Actions"))
 
             for (request_id, recid, borrower_id, library_id, location,
                  date_from, date_to, request_date) in result:
 
                 borrower_name = db.get_borrower_name(borrower_id)
                 library_name = db.get_library_name(library_id)
 
 
                 title_link = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_item_details',
                                     {'recid': recid, 'ln': ln},
                                     (book_title_from_MARC(recid)))
 
                 if borrower_name:
                     borrower_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_borrower_details',
                                 {'borrower_id': borrower_id, 'ln': ln},
                                 (borrower_name))
                 else:
                     borrower_link = str(borrower_id)
 
 
                 out += """
                 <script type="text/javascript">
                 function confirmation(id){
                   var answer = confirm("Delete this request?")
                   if (answer){
                     window.location = "%s/admin2/bibcirculation/get_expired_loans_with_requests?request_id="+id;
                   }
                   else{
                     alert("Request not deleted.")
                   }
                 }
                 </script>
                 <tr>
                   <td width='150'>%s</td>
                   <td width='250'>%s</td>
                   <td>%s</td>
                   <td>%s</td>
                   <td>%s</td>
                   <td>%s</td>
                   <td>%s</td>
                   <td algin='center'>
                     <input type="button" value='%s' style="background: url(/img/jquery/dialog-cancel.png)
                         no-repeat; width: 75px; text-align: right;"
                         onClick="confirmation(%s)"
                         onmouseover="this.className='bibcircbuttonover'" onmouseout="this.className='bibcircbutton'"
                         class="bibcircbutton">
                     <input type=button style="background: url(/img/dialog-yes.png) no-repeat; width: 150px; text-align: right;"
                         onClick="location.href='%s/admin2/bibcirculation/associate_barcode?request_id=%s&recid=%s&borrower_id=%s&ln=%s'"
                         onmouseover="this.className='bibcircbuttonover'" onmouseout="this.className='bibcircbutton'"
                         value='%s' class="bibcircbutton">
                   </td>
                 </tr>
                 """ % (CFG_SITE_URL,
                        borrower_link,
                        title_link,
                        library_name,
                        location,
                        date_from,
                        date_to,
                        request_date,
                        _("Delete"),
                         request_id,
                        CFG_SITE_URL,
                        request_id,
                        recid,
                        borrower_id,
                        ln,
                        _("Associate barcode"))
 
             out += """
                   </tbody>
                 </table>
                  <div id="pager" class="pager">
                         <form>
                             <br />
                             <img src="/img/sb.gif" class="first" />
                             <img src="/img/sp.gif" class="prev" />
                             <input type="text" class="pagedisplay" />
                             <img src="/img/sn.gif" class="next" />
                             <img src="/img/se.gif" class="last" />
                             <select class="pagesize">
                                 <option value="10" selected="selected">10</option>
                                 <option value="20">20</option>
                                 <option value="30">30</option>
                                 <option value="40">40</option>
                             </select>
                         </form>
                     </div>
 
                   <br />
                   <table class="bibcirctable">
                     <tr>
                       <td>
                         <input type=button style="background: url(/img/document-print.png) no-repeat; width: 135px; text-align: right;"
                         onClick="location.href='%s/admin2/bibcirculation/get_pending_requests?print_data=true&ln=%s'"
                         onmouseover="this.className='bibcircbuttonover'" onmouseout="this.className='bibcircbutton'"
                         value='%s' class="bibcircbutton">
                       </td>
                     </tr>
                   </table>
                   <br />
                   </div>
                   """ % (CFG_SITE_URL, ln,
                          _("Printable format"))
 
 
         return out
 
     def tmpl_register_ill_book_request(self, infos, borrower_id,
                                        ln=CFG_SITE_LANG):
         """
         @param infos: informations
         @type infos: list
 
         @param ln: language of the page
         """
         _ = gettext_set_language(ln)
 
         out = self.tmpl_infobox(infos, ln)
 
         out += load_menu(ln)
 
         out += """
         <div class=bibcircbottom align="center">
         <form name="search_form"
               action="%s/admin2/bibcirculation/register_ill_book_request_result"
               method="get" >
         <br />
         <br />
         <div class="bibcircinfoboxmsg"><strong>%s</strong></div>
         <br />
         <input type=hidden name=start value="0">
         <input type=hidden name=end value="10">
         """ % (CFG_SITE_URL,
             _("Check if the book already exists on %(CFG_SITE_NAME)s, before sending your ILL request.") % {'CFG_SITE_NAME': CFG_SITE_NAME})
 
         if borrower_id is not None:
             out += """
             <input type=hidden name=borrower_id value="%s">
             """ % (borrower_id)
 
         out += """
         <table class="bibcirctable">
           <tr align="center">
             <td class="bibcirctableheader">%s
               <input type="radio" name="f" value="" checked>%s
               <input type="radio" name="f" value="barcode">%s
               <input type="radio" name="f" value="author">%s
               <input type="radio" name="f" value="title">%s
               <br />
               <br />
             </td>
             """ % (_("Search item by"), _("any field"), _("barcode"),
                    _("author"), _("title"))
 
         out += """
           </tr>
           <tr align="center">
             <td>
                 <input type="text" size="50" name="p" id='p' style='border: 1px solid #cfcfcf'>
                 <script language="javascript" type="text/javascript">
                     document.getElementById("p").focus();
                 </script>
             </td>
           </tr>
         </table>
         <br />
         <table class="bibcirctable">
           <tr align="center">
             <td>
               <input type=button value='%s'
                      onClick="history.go(-1)" class="formbutton">
               <input type="submit" value='%s' class="formbutton">
             </td>
           </tr>
         </table>
         <br />
         <br />
         <br />
         <br />
         </div>
         </form>
 
         """ % (_("Back"), _("Search"))
 
         return out
 
     def tmpl_register_ill_book_request_result(self, result, borrower_id,
                                               ln=CFG_SITE_LANG):
         """
         @param result: book's information
         @type result: list
 
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         out = load_menu(ln)
 
         if len(result) == 0:
             out += """
             <div class="bibcircbottom" align="center">
             <br />
             <div class="bibcircinfoboxmsg">%s</div>
             <br />
             """ % (_("0 items found."))
             if borrower_id is not None:
                 out += """
                     <input type=hidden name=borrower_id value="%s">
                 """ % (borrower_id)
 
         else:
             out += """
         <style type="text/css"> @import url("/img/tablesorter.css"); </style>
         <div class="bibcircbottom">
         <form name="search_form"
               action="%s/admin2/bibcirculation/register_ill_request_with_no_recid_step1"
               method="get" >
         <br />
         """ % (CFG_SITE_URL)
 
             if borrower_id is not None and borrower_id is not '':
                 out += """
         <input type=hidden name=borrower_id value="%s">
         """ % (borrower_id)
 
             out += """
         <table class="bibcirctable">
           <tr align="center">
             <td>
                <strong>%s item(s) found</strong>
             </td>
           </tr>
         </table>
         <br />
           <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
           <thead>
             <tr>
               <th>%s</th>
               <th>%s</th>
               <th>%s</th>
               <th>%s</th>
             </tr>
           </thead>
           <tbody>
         """ % (len(result), _("Title"),
                _("Author"), _("Publisher"),
                _("# copies"))
 
             for recid in result:
 
                 (book_author, book_editor,
                  book_copies) = get_item_info_for_search_result(recid)
 
                 title_link = create_html_link(CFG_SITE_URL +
                                     '/admin2/bibcirculation/get_item_details',
                                     {'recid': recid, 'ln': ln},
                                     (book_title_from_MARC(recid)))
 
                 out += """
                 <tr>
                 <td>%s</td>
                 <td>%s</td>
                 <td>%s</td>
                 <td>%s</td>
                 </tr>
                 """ % (title_link, book_author,
                        book_editor, book_copies)
 
         out += """
           </tbody>
           </table>
         <br />
         <table class="bibcirctable">
           <tr align="center">
             <td>
               <input type=button value='%s'
                onClick="history.go(-1)" class="formbutton">
               <input type="submit" value='%s' class="formbutton">
             </td>
           </tr>
         </table>
         <br />
         <br />
         <br />
         </form>
         </div>
 
         """ % (_("Back"), _("Proceed anyway"))
 
         return out
 
     #def tmpl_register_ill_book_request_from_borrower_page(self, infos,
     #                                                      borrower_id,
     #                                                      ln=CFG_SITE_LANG):
     #    """
     #    @param infos: informations
     #    @type infos: list
     #
     #    @param borrower_id: identify the borrower. Primary key of crcBORROWER.
     #    @type borrower_id: int
     #
     #    @param ln: language of the page
     #    """
     #    _ = gettext_set_language(ln)
     #
     #    out = self.tmpl_infobox(infos, ln)
     #
     #    out += load_menu(ln)
     #
     #    out += """
     #    <div class=bibcircbottom align="center">
     #    <form name="search_form"
     #        action="%s/admin2/bibcirculation/register_ill_book_request_from_borrower_page_result"
     #        method="get" >
     #    <input type=hidden name=borrower_id value="%s">
     #    <br />
     #    <br />
     #    <div class="bibcircinfoboxmsg"><strong>%s</strong></div>
     #    <br />
     #    <input type=hidden name=start value="0">
     #    <input type=hidden name=end value="10">
     #    """ % (CFG_SITE_URL, borrower_id,
     #    _("Check if the book already exists before sending your ILL request."))
     #
     #    out += """
     #    <table class="bibcirctable">
     #      <tr align="center">
     #        <td class="bibcirctableheader">%s
     #          <input type="radio" name="f" value="" checked>%s
     #          <input type="radio" name="f" value="barcode">%s
     #          <input type="radio" name="f" value="author">%s
     #          <input type="radio" name="f" value="title">%s
     #          <br />
     #          <br />
     #        </td>
     #      </tr>
     #      """ % (_("search item by"), _("any field"), _("barcode"),
     #             _("author"),_("title"))
     #
     #    out += """
     #      <tr align="center">
     #        <td>
     #            <input type="text" size="50" name="p" style='border: 1px solid #cfcfcf'>
     #        </td>
     #      </tr>
     #    </table>
     #    <br />
     #    <table class="bibcirctable">
     #      <tr align="center">
     #        <td>
     #          <input type=button value='%s'
     #                 onClick="history.go(-1)"
     #                 class="formbutton">
     #          <input type="submit" value='%s' class="formbutton">
     #        </td>
     #      </tr>
     #    </table>
     #    <br />
     #    <br />
     #    <br />
     #    <br />
     #    </div>
     #    <form>
     #    """ % (_("Back"), _("Search"))
     #
     #    return out
 
     #def tmpl_register_ill_book_request_from_borrower_page_result(self, result,
     #                                                        ln=CFG_SITE_LANG):
     #    """
     #    @param result: book's information
     #    @type result: list
     #
     #    @param borrower_id: identify the borrower. Primary key of crcBORROWER.
     #    @type borrower_id: int
     #
     #    @param ln: language of the page
     #    """
     #
     #    _ = gettext_set_language(ln)
     #
     #    out = load_menu(ln)
     #
     #    if len(result) == 0:
     #        out += """
     #        <div class="bibcircbottom" align="center">
     #        <br />
     #        <div class="bibcircinfoboxmsg">%s</div>
     #        <br />
     #        """ % (_("0 items found."))
     #
     #    else:
     #        out += """
     #    <style type="text/css"> @import url("/img/tablesorter.css"); </style>
     #    <div class="bibcircbottom">
     #    <br />
     #    <table class="bibcirctable">
     #      <tr align="center">
     #        <td>
     #           <strong>%s item(s) found</strong>
     #        </td>
     #      </tr>
     #    </table>
     #    <br />
     #      <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
     #      <thead>
     #        <tr>
     #          <th>%s</th>
     #          <th>%s</th>
     #          <th>%s</th>
     #          <th>%s</th>
     #        </tr>
     #      </thead>
     #      <tbody>
     #    """ % (len(result), _("Title"),
     #           _("Author"), _("Publisher"),
     #           _("# copies"))
     #
     #        for recid in result:
     #
     #            (book_author, book_editor,
     #             book_copies) = get_item_info_for_search_result(recid)
     #
     #            title_link = create_html_link(CFG_SITE_URL +
     #                            '/admin2/bibcirculation/get_item_details',
     #                            {'recid': recid, 'ln': ln},
     #                            (book_title_from_MARC(recid)))
     #
     #            out += """
     #            <tr>
     #            <td>%s</td>
     #            <td>%s</td>
     #            <td>%s</td>
     #            <td>%s</td>
     #            </tr>
     #            """ % (title_link, book_author,
     #                   book_editor, book_copies)
     #
     #    out += """
     #      </tbody>
     #      </table>
     #    <br />
     #    <table class="bibcirctable">
     #      <tr align="center">
     #        <td>
     #          <input type=button value='%s'
     #           onClick="history.go(-1)" class="formbutton">
     #        </td>
     #      </tr>
     #    </table>
     #    <br />
     #    <br />
     #    <br />
     #    </div>
     #
     #    """ % (_("Back"))
     #
     #    return out
 
     #def tmpl_register_ill_request_from_borrower_page_step1(self, infos,
     #                                                       borrower_id,
     #                                                       ln=CFG_SITE_LANG):
     #    """
     #    @param infos: informations
     #    @type infos: list
     #
     #    @param borrower_id: identify the borrower. Primary key of crcBORROWER.
     #    @type borrower_id: int
     #    """
     #
     #    _ = gettext_set_language(ln)
     #
     #    out = self.tmpl_infobox(infos, ln)
     #
     #    out += load_menu(ln)
     #
     #
     #    out += """
     #    <br />
     #    <br />
     #      <div class="bibcircbottom" align="center">
     #      <div class="bibcircinfoboxmsg"><strong>%s</strong>%s</div>
     #      <br />
     #      <br />
     #      <style type="text/css"> @import url("/img/tablesorter.css"); </style>
     #       <form name="display_ill_form" action="%s/admin2/bibcirculation/register_ill_request_from_borrower_page_step2" method="get">
     #       <input type=hidden name=borrower_id value="%s">
     #         <table class="bibcirctable">
     #              <tr align="center">
     #                <td class="bibcirctableheader" width="10">%s</td>
     #              </tr>
     #            </table>
     #            <table class="tablesorterborrower" border="0" cellpadding="0" cellspacing="1">
     #                <tr>
     #                    <th width="100">%s</th>
     #                    <td>
     #                      <input type="text" size="45" name="title" style='border: 1px solid #cfcfcf'>
     #                    </td>
     #                 </tr>
     #                 <tr>
     #                    <th width="100">%s</th>
     #                    <td>
     #                      <input type="text" size="45" name="authors" style='border: 1px solid #cfcfcf'>
     #                    </td>
     #                 </tr>
     #                 <tr>
     #                    <th width="100">%s</th>
     #                    <td>
     #                      <input type="text" size="30" name="place" style='border: 1px solid #cfcfcf'>
     #                    </td>
     #                 </tr>
     #                 <tr>
     #                    <th width="100">%s</th>
     #                    <td>
     #                      <input type="text" size="30" name="publisher" style='border: 1px solid #cfcfcf'>
     #                    </td>
     #                 </tr>
     #                 <tr>
     #                    <th width="100">%s</th>
     #                    <td>
     #                      <input type="text" size="30" name="year" style='border: 1px solid #cfcfcf'>
     #                    </td>
     #                 </tr>
     #                 <tr>
     #                    <th width="100">%s</th>
     #                    <td>
     #                      <input type="text" size="30" name="edition" style='border: 1px solid #cfcfcf'>
     #                    </td>
     #                 </tr>
     #                 <tr>
     #                    <th width="100">%s</th>
     #                    <td>
     #                      <input type="text" size="30" name="isbn" style='border: 1px solid #cfcfcf'>
     #                    </td>
     #                 </tr>
     #            </table>
     #
     #
     #       <br />
     #
     #       """ % (_("Book does not exists in %(CFG_SITE_NAME)s") % \
     #                    {'CFG_SITE_NAME': CFG_SITE_NAME},
     #               _("Please fill the following form."),
     #               CFG_SITE_URL, borrower_id,
     #               _("Item details"),
     #               _("Book title"),
     #               _("Author(s)"),
     #               _("Place"),
     #               _("Publisher"),
     #               _("Year"),
     #               _("Edition"),
     #               _("ISBN"))
     #
     #    out += """
     #    <script type="text/javascript" language='JavaScript' src="/jsCalendar/calendar.js"></script>
     #    <script type="text/javascript" language='JavaScript' src="/jsCalendar/calendar-setup.js"></script>
     #    <script type="text/javascript" language='JavaScript' src="/jsCalendar/calendar-en.js"></script>
     #    <style type="text/css"> @import url("/jsCalendar/calendar-blue.css"); </style>
     #
     #         <table class="bibcirctable">
     #            <tr align="center">
     #                 <td class="bibcirctableheader">%s</td>
     #            </tr>
     #         </table>
     #         <table class="tablesorterborrower" border="0" cellpadding="0" cellspacing="1">
     #           <tr>
     #            <th width="150">%s</th>
     #            <td>
     #                   <input type="text" size="12" id="%s" name="period_of_interest_from" value="" style='border: 1px solid #cfcfcf'>
     #                   <img src="/jsCalendar/jsCalendar.gif" alt="select period of interest" id="%s"
     #                   onmouseover="this.style.background='red';" onmouseout="this.style.background=''"
     #                   >
     #                   <script type="text/javascript" language='JavaScript'>
     #                   Calendar.setup({
     #                       inputField     :    '%s',
     #                       ifFormat       :    '%%Y-%%m-%%d',
     #                       button	  :    '%s'
     #                       });
     #                   </script>
     #                </td>
     #            </tr>
     #            <tr>
     #            <th width="150">%s</th>
     #            <td>
     #                <input type="text" size="12" id="%s" name="period_of_interest_to"
     #                       value="" style='border: 1px solid #cfcfcf'>
     #                    <img src="/jsCalendar/jsCalendar.gif"
     #                         alt="select period of interest" id="%s"
     #                         onmouseover="this.style.background='red';"
     #                         onmouseout="this.style.background=''">
     #                   <script type="text/javascript" language='JavaScript'>
     #                   Calendar.setup({
     #                       inputField     :    '%s',
     #                       ifFormat       :    '%%Y-%%m-%%d',
     #                       button	  :    '%s'
     #                       });
     #                   </script>
     #                </td>
     #            </tr>
     #            <tr>
     #               <th valign="top" width="150">%s</th>
     #               <td><textarea name='additional_comments' rows="6" cols="30"
     #               style='border: 1px solid #cfcfcf'></textarea></td>
     #            </tr>
     #          </table>
     #          <table class="bibcirctable">
     #          <!--<tr>
     #              <td>
     #                <input name="conditions" type="checkbox" value="accepted" />%s</td>
     #            </tr> -->
     #            <tr align="center">
     #              <td>
     #                <input name="only_edition" type="checkbox" value="Yes" />%s</td>
     #            </tr>
     #         </table>
     #         <br />
     #         <table class="bibcirctable">
     #            <tr align="center">
     #              <td>
     #                   <input type=button value="%s"
     #                    onClick="history.go(-1)" class="formbutton">
     #
     #                   <input type="submit"
     #                   value="%s" class="formbutton">
     #
     #              </td>
     #             </tr>
     #         </table>
     #         </form>
     #         <br />
     #         <br />
     #         </div>
     #""" % (_("ILL request details"), _("Period of interest - From"),
     #    "period_of_interest_from",
     #    "jsCal1", "period_of_interest_from", "jsCal1",
     #    _("Period of interest - To"), "period_of_interest_to",
     #    "jsCal2", "period_of_interest_to", "jsCal2",
     #    _("Additional comments"),
     #    _("Borrower accepts the %(x_url_open)sconditions%(x_url_close)s of the service in particular the return of books in due time.") % {'x_url_open': '<a href="http://library.web.cern.ch/library/Library/ill_faq.html" target="_blank">', 'x_url_close': '</a>'},
     #    _("Borrower wants this edition only."),
     #    _("Back"), _("Continue"))
     #
     #
     #    return out
     #
     #def tmpl_register_ill_request_from_borrower_page_step3(self, book_info,
     #                                        user_info, request_details, ln):
     #    """
     #    @param book_info: book's informations
     #    @type book_info: tuple
     #
     #    @param user_info: user's informations
     #    @type user_info: tuple
     #
     #    @param request_details: details about a given request
     #    @type request_details: tuple
     #    """
     #
     #    _ = gettext_set_language(ln)
     #
     #    (title, authors, place, publisher, year, edition, isbn) = book_info
     #
     #    (borrower_id, ccid, name, email, phone, address, mailbox) = user_info
     #
     #    display_id = borrower_id
     #    id_string = _("ID")
     #    if CFG_CERN_SITE == 1:
     #        display_id = ccid
     #        id_string = _("CCID")
     #
     #    (period_of_interest_from, period_of_interest_to,
     #     additional_comments, only_edition)= request_details
     #
     #    out = """ """
     #
     #    out += load_menu(ln)
     #
     #    out += """
     #    <style type="text/css"> @import url("/img/tablesorter.css"); </style>
     #    <div class=bibcircbottom align="center">
     #    <br />
     #    <br />
     #        <form name="step1_form1"
     #              action="%s/admin2/bibcirculation/register_ill_request_from_borrower_page_step4"
     #              method="get" >
     #            <table>
     #               <tr align="center">
     #                 <td class="bibcirctableheader">%s</td>
     #                 <input type=hidden name=book_info value="%s">
     #               </tr>
     #            </table>
     #            <table class="tablesorterborrower" border="0" cellpadding="0" cellspacing="1">
     #                    <tr>
     #                      <th width="100">%s</th>
     #                      <td>%s</td>
     #                    </tr>
     #                    <tr>
     #                      <th width="100">%s</th>
     #                      <td>%s</td>
     #                    </tr>
     #                    <tr>
     #                      <th width="100">%s</th>
     #                      <td>%s</td>
     #                    </tr>
     #                    <tr>
     #                      <th width="100">%s</th>
     #                      <td>%s</td>
     #                    </tr>
     #                    <tr>
     #                      <th width="100">%s</th>
     #                      <td>%s</td>
     #                    </tr>
     #                    <tr>
     #                      <th width="100">%s</th>
     #                      <td>%s</td>
     #                    </tr>
     #                    <tr>
     #                      <th width="100">%s</th>
     #                      <td>%s</td>
     #                    </tr>
     #                  </table>
     #                  <table>
     #                     <tr align="center">
     #                       <td class="bibcirctableheader">%s</td>
     #                       <input type=hidden name=request_details value="%s">
     #                    </tr>
     #                   </table>
     #                   <table class="tablesorterborrower" border="0"
     #                          cellpadding="0" cellspacing="1">
     #                    <tr>
     #                      <th width="100">%s</th>
     #                      <td>%s</td>
     #                    </tr>
     #                    <tr>
     #                      <th width="100">%s</th>
     #                      <td>%s</td>
     #                    </tr>
     #                    <tr>
     #                      <th width="100">%s</th>
     #                      <td>%s</td>
     #                    </tr>
     #                    <tr>
     #                      <th width="100">%s</th>
     #                      <td>%s</td>
     #                    </tr>
     #                  </table>
     #                  <table>
     #                     <tr align="center">
     #                       <td class="bibcirctableheader">%s</td>
     #                       <input type=hidden name=user_info value="%s">
     #                    </tr>
     #                   </table>
     #                   <table class="tablesorterborrower" border="0"
     #                          cellpadding="0" cellspacing="1">
     #                    <tr>
     #                      <th width="100">%s</th>
     #                      <td>%s</td>
     #                    </tr>
     #                    <tr>
     #                      <th width="100">%s</th>
     #                      <td>%s</td>
     #                    </tr>
     #                    <tr>
     #                      <th width="100">%s</th>
     #                      <td>%s</td>
     #                    </tr>
     #                    <tr>
     #                      <th width="100">%s</th>
     #                      <td>%s</td>
     #                    </tr>
     #                    <tr>
     #                      <th width="100">%s</th>
     #                      <td>%s</td>
     #                    </tr>
     #                    <tr>
     #                      <th width="100">%s</th>
     #                      <td>%s</td>
     #                    </tr>
     #                  </table>
     #        """ % (CFG_SITE_URL,
     #            _("Item details"), book_info,
     #            _("Title"), title,
     #            _("Author(s)"), authors,
     #            _("Place"), place,
     #            _("Year"), year,
     #            _("Publisher"), publisher,
     #            _("Edition"), edition,
     #            _("ISBN"), isbn,
     #            _("ILL request details"), request_details,
     #            _("Period of interest - From"), period_of_interest_from,
     #            _("Period of interest - To"), period_of_interest_to,
     #            _("Additional comments"), additional_comments,
     #            _("Only this edition"), only_edition or 'No',
     #            _("Borrower details"), user_info,
     #            id_string, display_id,
     #            _("Name"), name,
     #            _("Address"), address,
     #            _("Mailbox"), mailbox,
     #            _("Email"), email,
     #            _("Phone"), phone)
     #
     #    out += """<br />
     #              <table class="bibcirctable">
     #                <tr align="center">
     #                  <td>
     #                    <input type=button value="%s"
     #                    onClick="history.go(-1)" class="formbutton">
     #
     #                   <input type="submit"
     #                   value="%s" class="formbutton">
     #                  </td>
     #                </tr>
     #            </table>""" % (_("Back"), _("Continue"))
     #
     #
     #    return out
 
     def tmpl_register_purchase_request_step1(self, infos, fields, admin=True,
                                              ln=CFG_SITE_LANG):
         """
         @param infos: informations
         @type infos: list
        """
 
         _ = gettext_set_language(ln)
 
         if admin:
             form_url = CFG_SITE_URL + \
                     '/admin2/bibcirculation/register_purchase_request_step2'
         else:
             form_url = CFG_SITE_URL+'/ill/acq_request_step2'
 
         if fields is not None:
-            (type, title, authors, place, publisher, year, edition,
-             this_edition_only, isbn, standard_number, budget_code, cash,
-             period_of_interest_from, period_of_interest_to,
-             additional_comments) = fields
+            (request_type, title, authors, place, publisher, year, edition,
+             this_edition_only, isbn, standard_number, _budget_code, cash,
+             _period_of_interest_from, _period_of_interest_to,
+             _additional_comments) = fields
 
         if cash:
             checked_cash = 'checked'
         else:
             checked_cash = ''
 
         if this_edition_only == 'Yes':
             checked_edition = 'checked'
         else:
             checked_edition = ''
 
         out = ''
 
         if admin:
             out += load_menu(ln)
 
         out += """<br />""" + self.tmpl_infobox(infos, ln)
 
         if not admin:
             out += _("According to a decision from the Scientific Information Policy Board, books purchased with budget codes other than Team accounts will be added to the Library catalogue, with the indication of the purchaser.")
         out += """
           <div class="bibcircbottom" align="center">
           <br />
           <style type="text/css"> @import url("/img/tablesorter.css"); </style>
           """
         out += """
             <form name="display_ill_form" action="%s" method="post">
                 """ % (form_url)
         out += """
                 <table class="bibcirctable">
                     <tr align="center">
                         <td class="bibcirctableheader" width="10">%s</td>
                     </tr>
                 </table>
                 <table class="tablesorterborrower" border="0"
                        cellpadding="0" cellspacing="1">
                     <tr>
                         <th width="100">%s</th>
                         <td>
                             <SELECT name="type" style='border: 1px solid #cfcfcf'>
                 """ % (_("Document details"), _("Document type"))
 
         for acq_type in CFG_BIBCIRCULATION_ACQ_TYPE:
-            if type == acq_type or type == '':
+            if request_type == acq_type or request_type == '':
                 out += """
                                 <OPTION VALUE="%s" selected="selected">%s
                 """ % (acq_type, acq_type)
             else:
                 out += """
                                 <OPTION VALUE="%s">%s
                 """ % (acq_type, acq_type)
 
         out += """
                             </SELECT>
                         </td>
                     </tr>
                     <tr>
                         <th width="100">%s</th>
                         <td>
                             <input type="text" size="45" name="title"
                                    id='title' value='%s'
                                    style='border: 1px solid #cfcfcf'>
                             <script language="javascript" type="text/javascript">
                                     document.getElementById("title").focus();
                             </script>
                         </td>
                     </tr>
                     <tr>
                         <th width="100">%s</th>
                         <td>
                             <input type="text" size="45" name="authors"
                                    value='%s'
                                    style='border: 1px solid #cfcfcf'>
                         </td>
                     </tr>
                     <tr>
                         <th width="100">%s</th>
                         <td>
                             <input type="text" size="30" name="place"
                                    value='%s'
                                    style='border: 1px solid #cfcfcf'>
                         </td>
                     </tr>
                     <tr>
                         <th width="100">%s</th>
                         <td>
                             <input type="text" size="30" name="publisher"
                                    value='%s'
                                    style='border: 1px solid #cfcfcf'>
                         </td>
                     </tr>
                     <tr>
                         <th width="100">%s</th>
                         <td>
                             <input type="text" size="30" name="year"
                                    value='%s'
                                    style='border: 1px solid #cfcfcf'>
                         </td>
                     </tr>
                     <tr>
                         <th width="100">%s</th>
                         <td>
                             <input type="text" size="30" name="edition"
                                    value='%s'
                                    style='border: 1px solid #cfcfcf'>
                                    <br />
                             <input name="this_edition_only"
                                    type="checkbox" value="Yes" %s/>%s</td>
                         </td>
                     </tr>
                     <tr>
                         <th width="100">%s</th>
                         <td>
                             <input type="text" size="30" name="isbn"
                                    value='%s'
                                    style='border: 1px solid #cfcfcf'>
                         </td>
                     </tr>
                     <tr>
                         <th width="100">%s</th>
                         <td>
                             <input type="text" size="30" name="standard_number"
                                    value='%s'
                                    style='border: 1px solid #cfcfcf'>
                         </td>
                     </tr>
                 </table>
             <br />
            """ % (_("Title"), title,
                   _("Author(s)"), authors,
                   _("Place"), place,
                   _("Publisher"), publisher,
                   _("Year"), year,
                   _("Edition"), edition,
                   checked_edition, _("This edition only"),
                   _("ISBN"), isbn,
                   _("Standard number"), standard_number)
-        # type, title, author, place, publisher, year, edition, isbn, standard_number
 
         out += """
             <script type="text/javascript" language='JavaScript'
                     src="%s/js/jquery/jquery.min.js"></script>
             <script type="text/javascript" language='JavaScript'
                     src="%s/js/ui.datepicker.min.js"></script>
 
              <table class="bibcirctable">
                 <tr align="center">
                      <td class="bibcirctableheader">%s</td>
                 </tr>
              </table>
              <table class="tablesorterborrower" border="0" cellpadding="0" cellspacing="1">
                 <tr>
                     <th width="100">%s</th>
                     <td>
                         <input type="text" size="30" name="budget_code"
                                style='border: 1px solid #cfcfcf'>
                         <input name="cash" type="checkbox" value="Yes" %s/>%s</td>
                 </tr>
                 <tr>
                     <th width="150">%s</th>
                     <td>
                         <script type="text/javascript">
                             $(function(){
                             $("#date_picker1").datepicker({dateFormat: 'yy-mm-dd',
                                          showOn: 'button', buttonImage: "%s/img/calendar.gif",
                                          buttonImageOnly: true});
                             });
                         </script>
                         <input type="text" size="12" id="date_picker1"
                                name="period_of_interest_from" value="%s"
                                style='border: 1px solid #cfcfcf'>
                     </td>
                 </tr>
                 <tr>
                     <th width="150">%s</th>
                     <td>
                         <script type="text/javascript">
                             $(function(){
                             $("#date_picker2").datepicker({dateFormat: 'yy-mm-dd',
                                         showOn: 'button', buttonImage: "%s/img/calendar.gif",
                                         buttonImageOnly: true});
                             });
                         </script>
                         <input type="text" size="12" id="date_picker2"
                                name="period_of_interest_to" value="%s"
                                style='border: 1px solid #cfcfcf'>
                     </td>
                 </tr>
                 <tr>
                    <th valign="top" width="150">%s</th>
                     <td>
                         <textarea name='additional_comments' rows="6" cols="30"
                                   style='border: 1px solid #cfcfcf'></textarea>
                         </td>
                 </tr>
               </table>
               <table class="bibcirctable">
                 <tr align="center">
                     <td>
                         <input type=button value="%s"
                                onClick="history.go(-1)" class="formbutton">
                         <input type="submit"
                                value="%s" class="formbutton">
                     </td>
                 </tr>
               </table>
               </form>
               <br />
               </div>
     """ % (CFG_SITE_URL, CFG_SITE_URL, _("Request details"),
            _("Budget code"), checked_cash, _("Cash"),
            _("Period of interest - From"), CFG_SITE_URL,
            datetime.date.today().strftime('%Y-%m-%d'),
            _("Period of interest - To"), CFG_SITE_URL,
     (datetime.date.today() + datetime.timedelta(days=365)).strftime('%Y-%m-%d'),
           _("Additional comments"), _("Back"), _("Continue"))
 
         return out
 
     def tmpl_register_purchase_request_step2(self, infos, fields, result,
                                              p, f, ln=CFG_SITE_LANG):
 
         if fields is not None:
-            (type, title, authors, place, publisher, year, edition,
+            (request_type, title, authors, place, publisher, year, edition,
              this_edition_only, isbn, standard_number, budget_code, cash,
              period_of_interest_from, period_of_interest_to,
              additional_comments) = fields
 
         _ = gettext_set_language(ln)
 
         out = self.tmpl_infobox(infos, ln)
 
         out += load_menu(ln)
 
         out += """
         <style type="text/css"> @import url("/img/tablesorter.css"); </style>
         <div class="bibcircbottom">
          <form name="step2_form1"
                action="%s/admin2/bibcirculation/register_purchase_request_step2"
                method="get">
         <br />
           <table class="bibcirctable">
                   <tr>
                      <td class="bibcirctableheader" width="10">%s</td>
                   </tr>
                 </table>
                 <table class="bibcirctable">
                   <tr>
                     <td width="500" valign='top'>
                       <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=type value="%s">
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=title value="%s">
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=authors value="%s">
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=place value="%s">
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=publisher value="%s">
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=year value="%s">
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=edition value="%s">
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=isbn value="%s">
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=standard_number value="%s">
                         </tr>
                       </table>
                       <table>
                          <tr>
                            <td class="bibcirctableheader">%s</td>
                         </tr>
                        </table>
                        <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                         <tr>
                             <th width="100">%s</th>
                             <td>%s</td><input type=hidden name=budget_code value="%s">
                         </tr>
 
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=period_of_interest_from value="%s">
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=period_of_interest_to value="%s">
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=additional_comments value="%s">
                         </tr>
                       </table>
                      </td>
                      <td width="200" align='center' valign='top'>
                      </td>
         """ % (CFG_SITE_URL,
              _("Item details"),
-             _("Type"), type, type,
+             _("Type"), request_type, request_type,
              _("Title"), title, title,
              _("Author(s)"), authors, authors,
              _("Place"), place, place,
              _("Publisher"), publisher, publisher,
              _("Year"), year, year,
              _("Edition"), edition, edition,
              _("ISBN"), isbn, isbn,
              _("Standard number"), standard_number, standard_number,
              _("Request details"),
              _("Budget code"), budget_code, budget_code,
              _("Period of interest - From"),
              period_of_interest_from, period_of_interest_from,
              _("Period of interest - To"),
              period_of_interest_to, period_of_interest_to,
              _("Additional comments"),
              additional_comments, additional_comments)
 
         out += """
         <td valign='top' align='center'>
          <table>
             """
 
         if CFG_CERN_SITE == 1:
             out += """
                 <tr>
                    <td class="bibcirctableheader" align="center">%s
                    """ % (_("Search user by"))
 
             if f == 'email':
                 out += """
                    <input type="radio" name="f" value="ccid">%s
                    <input type="radio" name="f" value="name">%s
                    <input type="radio" name="f" value="email" checked>%s
                    """ % ('ccid', _('name'), _('email'))
 
             elif f == 'name':
                 out += """
                    <input type="radio" name="f" value="ccid">%s
                    <input type="radio" name="f" value="name" checked>%s
                    <input type="radio" name="f" value="email">%s
                    """ % ('ccid', _('name'), _('email'))
 
             else:
                 out += """
                    <input type="radio" name="f" value="ccid" checked>%s
                    <input type="radio" name="f" value="name">%s
                    <input type="radio" name="f" value="email">%s
                    """ % ('ccid', _('name'), _('email'))
 
         else:
             out += """
                  <tr>
                    <td align="center" class="bibcirctableheader">%s
                    """ % (_("Search borrower by"))
 
             if f == 'email':
                 out += """
                    <input type="radio" name="f" value="id">%s
                    <input type="radio" name="f" value="name">%s
                    <input type="radio" name="f" value="email" checked>%s
                    """ % (_('id'), _('name'), _('email'))
 
             elif f == 'id':
                 out += """
                    <input type="radio" name="f" value="id" checked>%s
                    <input type="radio" name="f" value="name">%s
                    <input type="radio" name="f" value="email">%s
                    """ % (_('id'), _('name'), _('email'))
 
             else:
                 out += """
                    <input type="radio" name="f" value="id">%s
                    <input type="radio" name="f" value="name" checked>%s
                    <input type="radio" name="f" value="email">%s
                    """ % (_('id'), _('name'), _('email'))
 
         out += """
                     <br><br>
                     </td>
                     </tr>
                     <tr>
                         <td align="center">
                             <input type="text" size="40" id="string" name="p"
                                    value='%s'  style='border: 1px solid #cfcfcf'>
                         </td>
                     </tr>
                     <tr>
                         <td align="center">
                             <br>
                             <input type="submit" value="%s" class="formbutton">
                         </td>
                     </tr>
                    </table>
           </form>
 
         """ % (p or '', _("Search"))
 
         if result:
             out += """
             <br />
             <form name="step1_form2"
                   action="%s/admin2/bibcirculation/register_purchase_request_step3"
                   method="post" >
             <input type=hidden name=type value="%s">
             <input type=hidden name=title value="%s">
             <input type=hidden name=authors value="%s">
             <input type=hidden name=place value="%s">
             <input type=hidden name=publisher value="%s">
             <input type=hidden name=year value="%s">
             <input type=hidden name=edition value="%s">
             <input type=hidden name=this_edition_only value="%s">
             <input type=hidden name=isbn value="%s">
             <input type=hidden name=standard_number value="%s">
             <input type=hidden name=budget_code value="%s">
             <input type=hidden name=cash value="%s">
             <input type=hidden name=period_of_interest_from value="%s">
             <input type=hidden name=period_of_interest_to value="%s">
             <input type=hidden name=additional_comments value="%s">
             <table class="bibcirctable">
               <tr width="200">
                 <td align="center">
                     <select name="borrower_id" size="8"
                           style='border: 1px solid #cfcfcf'>
             """ % (CFG_SITE_URL, type, title, authors, place, publisher, year,
                    edition, this_edition_only, isbn, standard_number,
                    budget_code, cash, period_of_interest_from,
                    period_of_interest_to, additional_comments)
 
-            for (borrower_id, ccid, name, email,
-                 phone, address, mailbox) in result:
+            for borrower_info in result:
+                borrower_id = borrower_info[0]
+                name = borrower_info[2]
                 out += """
                        <option value =%s>%s</option>
                        """ % (borrower_id, name)
 
             out += """
                     </select>
                 </td>
               </tr>
             </table>
             <table class="bibcirctable">
                 <tr>
                     <td align="center">
                         <input type="submit" value='%s' class="formbutton">
                     </td>
                 </tr>
             </table>
 
             </form>
             """ % (_("Select user"))
 
         out += """
                   </td>
                 </tr>
               </table>
               <br />
               <br />
               <br />
               <br />
               </div>
               """
 
         return out
 
     def tmpl_register_ill_article_request_step1(self, infos, admin=True,
                                                 ln=CFG_SITE_LANG):
         """
         @param infos: informations
         @type infos: list
         """
 
         _ = gettext_set_language(ln)
 
         if admin:
             form_url = CFG_SITE_URL + \
                     '/admin2/bibcirculation/register_ill_article_request_step2'
             method = 'get'
         else:
             form_url = CFG_SITE_URL+'/ill/article_request_step2'
             method = 'post'
 
         out = self.tmpl_infobox(infos, ln)
         if admin:
             out += load_menu(ln)
 
         out += """
         <br />
         <br />
           <div class="bibcircbottom" align="center">
           <br />
           <br />
           <style type="text/css"> @import url("/img/tablesorter.css"); </style>
           """
         out += """
            <form name="display_ill_form" action="%s" method="%s">
                 """ % (form_url, method)
         out += """
              <table class="bibcirctable">
                   <tr align="center">
                     <td class="bibcirctableheader" width="10">%s</td>
                   </tr>
                 </table>
                 <table class="tablesorterborrower" border="0"
                        cellpadding="0" cellspacing="1">
                     <tr>
                         <th width="100">%s</th>
                         <td>
                           <input type="text" size="45" name="periodical_title"
                                  id='periodical_title'
                                  style='border: 1px solid #cfcfcf'>
                           <script language="javascript" type="text/javascript">
                             document.getElementById("periodical_title").focus();
                           </script>
                         </td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>
                           <input type="text" size="45" name="article_title"
                                  style='border: 1px solid #cfcfcf'>
                         </td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>
                           <input type="text" size="45" name="author"
                                  style='border: 1px solid #cfcfcf'>
                         </td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>
                           <input type="text" size="30" name="report_number"
                                  style='border: 1px solid #cfcfcf'>
                         </td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>
                           <input type="text" size="30" name="volume"
                                  style='border: 1px solid #cfcfcf'>
                         </td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>
                           <input type="text" size="30" name="issue"
                                  style='border: 1px solid #cfcfcf'>
                         </td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>
                           <input type="text" size="30" name="page"
                                  style='border: 1px solid #cfcfcf'>
                         </td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>
                           <input type="text" size="30" name="year"
                                  style='border: 1px solid #cfcfcf'>
                         </td>
                      </tr>
                      <!-- <tr>
                         <th width="100">%s</th>
                         <td>
                           <input type="text" size="30" name="budget_code"
                                  style='border: 1px solid #cfcfcf'>
                         </td>
                      </tr> -->
                      <tr>
                         <th width="100">%s</th>
                         <td>
                           <input type="text" size="30" name="issn"
                                  style='border: 1px solid #cfcfcf'>
                         </td>
                      </tr>
                 </table>
            <br />
 
            """ % (_("Article details"),
                    _("Periodical title"),
                    _("Article title"),
                    _("Author(s)"),
                    _("Report number"),
                    _("Volume"),
                    _("Issue"),
                    _("Page"),
                    _("Year"),
                    _("Budget code"),
                    _("ISSN"))
 
 
         #conditions_link = """<a href="http://library.web.cern.ch/library/Library/ill_faq.html" target="_blank">conditions</a>"""
 
         out += """
             <script type="text/javascript" language='JavaScript' src="%s/js/jquery/jquery.ui.datepicker.min.js"></script>
 
              <table class="bibcirctable">
                 <tr align="center">
                      <td class="bibcirctableheader">%s</td>
                 </tr>
              </table>
              <table class="tablesorterborrower" border="0" cellpadding="0" cellspacing="1">
                <tr>
                 <th width="150">%s</th>
                 <td>
                         <script type="text/javascript">
                             $(function(){
                             $("#date_picker1").datepicker({dateFormat: 'yy-mm-dd', showOn: 'button', buttonImage: "%s/img/jquery/calendar.gif", buttonImageOnly: true});
                             });
                         </script>
                         <input type="text" size="12" id="date_picker1"
                                name="period_of_interest_from" value="%s"
                                style='border: 1px solid #cfcfcf'>
                     </td>
                 </tr>
                 <tr>
                     <th width="150">%s</th>
                     <td>
                         <script type="text/javascript">
                             $(function(){
                             $("#date_picker2").datepicker({dateFormat: 'yy-mm-dd', showOn: 'button', buttonImage: "%s/img/jquery/calendar.gif", buttonImageOnly: true});
                             });
                         </script>
                         <input type="text" size="12" id="date_picker2"
                                name="period_of_interest_to" value="%s"
                                style='border: 1px solid #cfcfcf'>
                     </td>
                 </tr>
                 <tr>
                    <th valign="top" width="150">%s</th>
                     <td>
                         <textarea name='additional_comments' rows="6" cols="30"
                                   style='border: 1px solid #cfcfcf'></textarea>
                         </td>
                 </tr>
               </table>
               <br />
               <table class="bibcirctable">
                 <tr align="center">
                     <td>
                         <input type=button value="%s"
                                onClick="history.go(-1)" class="formbutton">
                         <input type="submit"
                                value="%s" class="formbutton">
                     </td>
                 </tr>
               </table>
               </form>
               <br />
               <br />
               </div>
     """ % (CFG_SITE_URL, _("ILL request details"),
         _("Period of interest - From"), CFG_SITE_URL,
         datetime.date.today().strftime('%Y-%m-%d'),
         _("Period of interest - To"), CFG_SITE_URL,
    (datetime.date.today() + datetime.timedelta(days=365)).strftime('%Y-%m-%d'),
         _("Additional comments"),
         _("Back"), _("Continue"))
 
         return out
 
     def tmpl_register_ill_article_request_step2(self, article_info,
                                     request_details, result, key, string,
                                     infos, ln=CFG_SITE_LANG):
         """
         @param article_info: information about article
         @type article_info: tuple
 
         @param request_details: details about a given ILL request
         @type request_details: tuple
 
         @param result: result with borrower's information
         @param result: list
 
         @param key: field (name, email, etc...)
         @param key: string
 
         @param string: pattern
         @type string: string
 
         @param infos: informations
         @type infos: list
         """
 
         (periodical_title, article_title, author, report_number,
          volume, issue, page, year, issn) = article_info
 
         (period_of_interest_from, period_of_interest_to, budget_code,
          additional_comments)= request_details
 
         _ = gettext_set_language(ln)
 
         out = self.tmpl_infobox(infos, ln)
 
         out += load_menu(ln)
 
         out += """
         <style type="text/css"> @import url("/img/tablesorter.css"); </style>
         <div class="bibcircbottom">
          <form name="step1_form1"
                action="%s/admin2/bibcirculation/register_ill_article_request_step2"
                method="get" >
         <br />
           <table class="bibcirctable">
                   <tr>
                      <td class="bibcirctableheader" width="10">%s</td>
                   </tr>
                 </table>
                 <table class="bibcirctable">
                   <tr>
                     <td width="500" valign='top'>
                       <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=periodical_title value="%s">
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=article_title value="%s">
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=author value="%s">
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=report_number value="%s">
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=volume value="%s">
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=issue value="%s">
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=page value="%s">
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=year value="%s">
                         </tr>
                         <!-- <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=budget_code value="%s">
                         </tr> -->
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=issn value="%s">
                         </tr>
                       </table>
                       <table>
                          <tr>
                            <td class="bibcirctableheader">%s</td>
                         </tr>
                        </table>
                        <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=period_of_interest_from value="%s">
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=period_of_interest_to value="%s">
                         </tr>
                         <tr>
                           <th width="100">%s</th>
                           <td>%s</td><input type=hidden name=additional_comments value="%s">
                         </tr>
                       </table>
                      </td>
                      <td width="200" align='center' valign='top'>
                      </td>
         """ % (CFG_SITE_URL,
             _("Item details"),
             _("Periodical title"), periodical_title, periodical_title,
             _("Article title"), article_title, article_title,
             _("Author(s)"), author, author,
             _("Report number"), report_number, report_number,
             _("Volume"), volume, volume,
             _("Issue"), issue, issue,
             _("Page"), page, page,
             _("Year"), year, year,
             _("Budget code"), budget_code, budget_code,
             _("ISSN"), issn, issn,
             _("ILL request details"),
             _("Period of interest - From"),
             period_of_interest_from, period_of_interest_from,
             _("Period of interest - To"),
             period_of_interest_to, period_of_interest_to,
             _("Additional comments"),
             additional_comments, additional_comments)
 
         out += """
         <td valign='top' align='center'>
          <table>
 
             """
 
         if CFG_CERN_SITE == 1:
             out += """
                 <tr>
                    <td class="bibcirctableheader" align="center">%s
                    """ % (_("Search user by"))
 
             if key == 'email':
                 out += """
                    <input type="radio" name="key" value="ccid">%s
                    <input type="radio" name="key" value="name">%s
                    <input type="radio" name="key" value="email" checked>%s
                    """ % ('ccid', _('name'), _('email'))
 
             elif key == 'name':
                 out += """
                    <input type="radio" name="key" value="ccid">%s
                    <input type="radio" name="key" value="name" checked>%s
                    <input type="radio" name="key" value="email">%s
                    """ % ('ccid', _('name'), _('email'))
 
             else:
                 out += """
                    <input type="radio" name="key" value="ccid" checked>%s
                    <input type="radio" name="key" value="name">%s
                    <input type="radio" name="key" value="email">%s
                    """ % ('ccid', _('name'), _('email'))
 
         else:
             out += """
                  <tr>
                    <td align="center" class="bibcirctableheader">%s
                    """ % (_("Search borrower by"))
 
             if key == 'email':
                 out += """
                    <input type="radio" name="key" value="id">%s
                    <input type="radio" name="key" value="name">%s
                    <input type="radio" name="key" value="email" checked>%s
                    """ % (_('id'), _('name'), _('email'))
 
             elif key == 'id':
                 out += """
                    <input type="radio" name="key" value="id" checked>%s
                    <input type="radio" name="key" value="name">%s
                    <input type="radio" name="key" value="email">%s
                    """ % (_('id'), _('name'), _('email'))
 
             else:
                 out += """
                    <input type="radio" name="key" value="id">%s
                    <input type="radio" name="key" value="name" checked>%s
                    <input type="radio" name="key" value="email">%s
                    """ % (_('id'), _('name'), _('email'))
 
         out += """
                     <br><br>
                     </td>
                     </tr>
                     <tr>
                     <td align="center">
                     <input type="text" size="40" id="string" name="string"
                            value='%s' style='border: 1px solid #cfcfcf'>
                     </td>
                     </tr>
                     <tr>
                     <td align="center">
                     <br>
                     <input type="submit" value="%s" class="formbutton">
                     </td>
                     </tr>
                    </table>
           </form>
 
         """ % (string or '', _("Search"))
 
         if result:
             out += """
             <br />
             <form name="step1_form2"
                   action="%s/admin2/bibcirculation/register_ill_article_request_step3"
                   method="post" >
             <input type=hidden name=periodical_title value="%s">
             <input type=hidden name=article_title value="%s">
             <input type=hidden name=author value="%s">
             <input type=hidden name=report_number value="%s">
             <input type=hidden name=volume value="%s">
             <input type=hidden name=issue value="%s">
             <input type=hidden name=page value="%s">
             <input type=hidden name=year value="%s">
             <input type=hidden name=issn value="%s">
             <table class="bibcirctable">
               <tr width="200">
                 <td align="center">
                   <select name="user_info" size="8"
                           style='border: 1px solid #cfcfcf; width:40%%'>
             """ % (CFG_SITE_URL, periodical_title, article_title,
                    author, report_number, volume, issue, page, year, issn)
             #article_info)
 
             for (borrower_id, ccid, name, email,
                  phone, address, mailbox) in result:
                 out += """
                        <option value ='%s,%s,%s,%s,%s,%s,%s'>%s
                        """ % (borrower_id, ccid, name, email,
                               phone, address, mailbox, name)
 
             out += """
                     </select>
                     </td>
                     </tr>
                     </table>
                     <table class="bibcirctable">
                     <tr>
                         <td align="center">
                         <input type="submit" value='%s' class="formbutton">
                         </td>
                     </tr>
                     </table>
                     <input type=hidden name=period_of_interest_from value="%s">
                     <input type=hidden name=period_of_interest_to value="%s">
                     <input type=hidden name=budget_code value="%s">
                     <input type=hidden name=additional_comments value="%s">
                     </form>
                     """ % (_("Select user"),
                            period_of_interest_from, period_of_interest_to,
                            budget_code, additional_comments)
          #request_details)
 
         out += """
                   </td>
                 </tr>
               </table>
               <br />
               <br />
               <br />
               <br />
               </div>
               """
 
         return out
 
     def tmpl_ill_search(self, infos, ln=CFG_SITE_LANG):
         """
         Display form for ILL search
 
         @param infos: informations
         @type infos: list
 
         @param ln: language of the page
         """
         _ = gettext_set_language(ln)
 
         out = self.tmpl_infobox(infos, ln)
 
         out += load_menu(ln)
 
         out += """
         <div class="bibcircbottom">
         <link rel=\"stylesheet\" href=\"%(site_url)s/img/jquery-ui.css\" type=\"text/css\" />
         <script type="text/javascript" language='JavaScript'
                 src="%(site_url)s/js/ui.datepicker.min.js"></script>
         <form name="search_form"
               action="%(site_url)s/admin2/bibcirculation/ill_search_result"
               method="get" >
         <br />
         <br />
         <br />
         """ % {'site_url': CFG_SITE_URL}
 
         out += """
         <table class="bibcirctable">
           <tr align="center">
             <td class="bibcirctableheader">%s
               <input type="radio" name="f" value="title" checked>%s
               <input type="radio" name="f" value="ILL_request_ID">%s
               <input type="radio" name="f" value="cost">%s
               <input type="radio" name="f" value="notes">%s
             </td>
           </tr>
         </table>
 
         <br />
         <table class="bibcirctable">
             <tr align="center" width=10>
                 <td width=10>
                     <input type="text" size="50" name="p" id='p'
                            style='border: 1px solid #cfcfcf'>
                     <script language="javascript" type="text/javascript">
                         document.getElementById("p").focus();
                     </script>
                 </td>
             </tr>
         </table>
         """ % (_("Search ILL request by"), _("title"),
                _("ILL request id"), _("cost"), _("notes"))
 
         out += """
         <br />
         <table align="center">
 
             <tr align="center">
                 <td class="bibcirctableheader" align="right">%s:    </td>
                 <td class="bibcirctableheader" align="right">%s</td>
                 <td align="left">
                 <script type="text/javascript">
                     $(function(){
                         $("#date_picker1").datepicker({dateFormat: 'yy-mm-dd',
                         showOn: 'button', buttonImage: "%s/img/calendar.gif",
                         buttonImageOnly: true});
                     });
                 </script>
                 <input type="text" size="12" id="date_picker1" name="date_from"
                         value="%s" style='border: 1px solid #cfcfcf'>
                 </td>
             </tr>
 
             <tr align="center">
                 <td class="bibcirctableheader" align="right"></td>
                 <td class="bibcirctableheader" align="right">%s</td>
                 <td align="left">
                     <script type="text/javascript">
                         $(function(){
                             $("#date_picker2").datepicker({dateFormat: 'yy-mm-dd',
                             showOn: 'button', buttonImage: "%s/img/calendar.gif",
                             buttonImageOnly: true});
                         });
                     </script>
                     <input type="text" size="12" id="date_picker2" name="date_to"
                             value="%s" style='border: 1px solid #cfcfcf'>
                 </td>
             </tr>
         </table>
 
         """ % (_("date restriction"),
                _("From"), CFG_SITE_URL, _("the beginning"),
                _("To"), CFG_SITE_URL, _("now"))
 
         out += """
         <br />
         <table class="bibcirctable">
           <tr align="center">
             <td>
 
               <input type=button value='%s'
               onClick="history.go(-1)" class="formbutton">
               <input type="submit" value='%s' class="formbutton">
 
             </td>
           </tr>
         </table>
         <br />
         <br />
         <br />
         <br />
         </div>
         <form>
 
         """ % (_("Back"), _("Search"))
 
         return out
 
     def tmpl_delete_copy_step1(self, barcode_to_delete, recid, result,
                                infos, ln=CFG_SITE_LANG):
         """
         @param ln: language of the page
         """
 
         _ = gettext_set_language(ln)
 
         record_is_periodical = is_periodical(recid)
 
         #out = self.tmpl_infobox(infos, ln)
 
         out = load_menu(ln)
 
         (book_title, book_year, book_author,
           book_isbn, book_editor) = book_information_from_MARC(recid)
 
         if book_isbn:
             book_cover = get_book_cover(book_isbn)
         else:
             book_cover = "%s/img/book_cover_placeholder.gif" % (CFG_SITE_URL)
 
 
         out += """
             <style type="text/css">
                 @import url("/img/tablesorter.css");
             </style>
             <script src="/js/jquery/jquery.min.js" type="text/javascript"></script>
             <script src="/js/tablesorter/jquery.tablesorter.js" type="text/javascript"></script>
 
             <style type="text/css">
                 @import url("/js/tablesorter/themes/blue/style.css");
             </style>
             <style type="text/css">
                 @import url("/js/tablesorter/addons/pager/jquery.tablesorter.pager.css");
             </style>
 
             <script src="/js/jquery/jquery.min.js" type="text/javascript"></script>
             <script src="/js/tablesorter/jquery.tablesorter.js" type="text/javascript"></script>
             <script src="/js/tablesorter/addons/pager/jquery.tablesorter.pager.js"
                     type="text/javascript"></script>
             """
 
         if record_is_periodical:
             out += """
             <script type="text/javascript">
                 $(document).ready(function(){
                     $("#table_copies")
                       .tablesorter({sortList: [[6,1]],widthFixed: true, widgets: ['zebra']})
                       .bind("sortStart",function(){$("#overlay").show();})
                       .bind("sortEnd",function(){$("#overlay").hide()})
                       .tablesorterPager({container: $("#pager"), positionFixed: false});
                 });
             </script>
             """
         else:
             out += """
             <script type="text/javascript">
                 $(document).ready(function() {
                     $('#table_copies').tablesorter({widthFixed: true, widgets: ['zebra']})
                 });
             </script>
             """
 
         out += """
            <form name="delete_copy_step2_form"
                  action="%s/admin2/bibcirculation/delete_copy_step2"
                  method="get">
            <div class="bibcircbottom">
                 <br />
                      <table class="bibcirctable">
                           <tr>
                                <td class="bibcirctableheader" width="10">%s</td>
                           </tr>
                 </table>
                 <table class="bibcirctable">
                  <tr valign='top'>
                     <td width="400">
                     <table class="tablesorter" border="0" cellpadding="0" cellspacing="1">
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      <tr>
                         <th width="100">%s</th>
                         <td>%s</td>
                      </tr>
                      </table>
                      </td>
                      <td class="bibcirccontent">
                         <img style='border: 1px solid #cfcfcf'
                              src="%s" alt="Book Cover"/>
                      </td>
                      </tr>
               </table>
 
            <br />
            <table class="bibcirctable">
                 <tr>
                      <td class="bibcirctableheader">%s</td>
                 </tr>
            </table>
 
            """ % (CFG_SITE_URL,
                    _("Item details"),
                    _("Name"),
                    book_title,
                    _("Author(s)"),
                    book_author,
                    _("Year"),
                    book_year,
                    _("Publisher"),
                    book_editor,
                    _("ISBN"),
                    book_isbn,
                    str(book_cover),
                    _("Copies of %s" % book_title))
 
 
         out += """
                   <table class="tablesorter" id="table_copies" border="0"
                          cellpadding="0" cellspacing="1">
                   <thead>
                     <tr>
                       <th>%s</th>
                       <th>%s</th>
                       <th>%s</th>
                       <th>%s</th>
                 """ % (_("Barcode"),
                        _("Status"),
                        _("Due date"),
                        _("Library"))
 
         if not record_is_periodical:
             out += """
                       <th>%s</th>
                    """ % (_("Location"))
 
         out += """
                       <th>%s</th>
                       <th>%s</th>
                 """ % (_("Loan period"),
                        _("No of loans"))
 
         if not record_is_periodical:
             out += """
                       <th>%s</th>
                    """ % (_("Collection"))
 
         out += """
                       <th>%s</th>
                     </tr>
                   </thead>
                   <tboby>
                     """ % (_("Description"))
 
         for (barcode, loan_period, lib_name, libid, location, nb_requests,
              status, collection, description, due_date) in result:
 
             library_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_library_details',
                                 {'library_id': libid, 'ln': ln}, (lib_name))
 
             out += """
                  <tr>
                      <td>%s</td>
                      <td>%s</td>
                      <td>%s</td>
                      <td>%s</td>
                      """ % (barcode, status, due_date or '-', library_link)
 
             if not record_is_periodical:
                 out += """
                      <td>%s</td>
                      """ % (location)
 
             out += """
                      <td>%s</td>
                      <td>%s</td>
                      """ % (loan_period, nb_requests)
 
             if not record_is_periodical:
                 out += """
                      <td>%s</td>
                      """ % (collection or '-')
 
             out += """
                      <td>%s</td>
                      """ % (description or '-')
 
 
         out += """ </tbody>
                   </table>
                 """
 
         if record_is_periodical:
             out += """
             <div id="pager" class="pager">
                         <form>
                             <img src="/img/sb.gif" class="first" />
                             <img src="/img/sp.gif" class="prev" />
                             <input type="text" class="pagedisplay" />
                             <img src="/img/sn.gif" class="next" />
                             <img src="/img/se.gif" class="last" />
                             <select class="pagesize">
                                 <option value="10" selected="selected">10</option>
                                 <option value="20">20</option>
                                 <option value="30">30</option>
                                 <option value="40">40</option>
                             </select>
                         </form>
             </div>
             </br>
             """
 
         out += self.tmpl_infobox(infos, ln)
 
         out += """<table id="table_copies" class="tablesorter"
                          border="0" cellpadding="0" cellspacing="1">
           <thead>
             <tr>
               <th>%s</th>
               <th>%s</th>
               <th>%s</th>
               <th>%s</th>
               <th>%s</th>
               <th>%s</th>
               <th>%s</th>
               <th>%s</th>
               <th>%s</th>
             </tr>
             </thead>
             <tbody>""" % (_("Barcode"),
                         _("Status"),
                         _("Due date"),
                         _("Library"),
                         _("Location"),
                         _("Loan period"),
                         _("No of loans"),
                         _("Collection"),
                         _("Description"))
 
         for (barcode, loan_period, lib_name, libid, location, nb_requests,
              status, collection, description, due_date) in result:
             if barcode == barcode_to_delete:
                 library_link = create_html_link(CFG_SITE_URL +
                                 '/admin2/bibcirculation/get_library_details',
                                 {'library_id': libid, 'ln': ln}, (lib_name))
 
                 out += """
                      <tr>
                          <td>%s</td>
                          <td>%s</td>
                          <td>%s</td>
                          <td>%s</td>
                          <td>%s</td>
                          <td>%s</td>
                          <td>%s</td>
                          <td>%s</td>
                          <td>%s</td>
                      </tr>
                      """ % (barcode, status, due_date, library_link, location,
                             loan_period, nb_requests, collection or '-',
                             description or '-')
 
         out += """ </tbody>
                   </table>
                 """
         out += """<input type=hidden name=barcode value="%s">
                 """ % (str(barcode_to_delete))
         out += """<input type=button value="%s" onClick="history.go(-1)"
                          class="formbutton">
                """ % (_("Back"))
         out += """<input type="submit" value='%s' class="formbutton">
                """ % (_("Delete"))
 
         out += """</div></form>"""
 
         return out
diff --git a/modules/bibcirculation/lib/bibcirculation_utils.py b/modules/bibcirculation/lib/bibcirculation_utils.py
index ff10911ac..433d6d785 100644
--- a/modules/bibcirculation/lib/bibcirculation_utils.py
+++ b/modules/bibcirculation/lib/bibcirculation_utils.py
@@ -1,935 +1,934 @@
 # -*- coding: utf-8 -*-
 ##
 ## This file is part of Invenio.
 ## Copyright (C) 2008, 2009, 2010, 2011 CERN.
 ##
 ## Invenio is free software; you can redistribute it and/or
 ## modify it under the terms of the GNU General Public License as
 ## published by the Free Software Foundation; either version 2 of the
 ## License, or (at your option) any later version.
 ##
 ## Invenio is distributed in the hope that it will be useful, but
 ## WITHOUT ANY WARRANTY; without even the implied warranty of
 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 ## General Public License for more details.
 ##
 ## You should have received a copy of the GNU General Public License
 ## along with Invenio; if not, write to the Free Software Foundation, Inc.,
 ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 
 """BibCirculation Utils: Auxiliary methods of BibCirculation """
 
 __revision__ = "$Id$"
 
 from invenio.search_engine_utils import get_fieldvalues
 import invenio.bibcirculation_dblayer as db
 from invenio.search_engine import get_field_tags
 from invenio.bibtask import task_low_level_submission
 from invenio.textutils import encode_for_xml
 from invenio.config import CFG_SITE_URL, CFG_TMPDIR, CFG_SITE_LANG
 
 from invenio.bibcirculation_config import \
                                 CFG_BIBCIRCULATION_AMAZON_ACCESS_KEY, \
                                 CFG_BIBCIRCULATION_WORKING_DAYS, \
                                 CFG_BIBCIRCULATION_HOLIDAYS, \
                                 CFG_CERN_SITE, \
                                 CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN, \
                                 CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF, \
                                 CFG_BIBCIRCULATION_ITEM_STATUS_IN_PROCESS, \
                                 CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING, \
                                 CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING, \
                                 CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN, \
                                 CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED, \
                                 CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED
 
 
 from invenio.messages import gettext_set_language
 import datetime, time, random
 
 def search_user(column, string):
     if string is not None:
         string = string.strip()
 
     if CFG_CERN_SITE == 1:
         if column == 'name':
             result = db.search_borrower_by_name(string)
         else:
             if column == 'email':
                 try:
                     result = db.search_borrower_by_email(string)
                 except:
                     result = ()
             else:
                 try:
                     result = db.search_borrower_by_ccid(string)
                 except:
                     result = ()
 
             if result == ():
                 from invenio.bibcirculation_cern_ldap \
                      import get_user_info_from_ldap
 
                 ldap_info = 'busy'
                 while ldap_info == 'busy':
                     time.sleep(1)
                     if column == 'id' or column == 'ccid':
                         ldap_info = get_user_info_from_ldap(ccid=string)
                     elif column == 'email':
                         ldap_info = get_user_info_from_ldap(email=string)
                     else:
                         ldap_info = get_user_info_from_ldap(nickname=string)
 
                 if len(ldap_info) == 0:
                     result = ()
                 else:
                     try:
                         name = ldap_info['displayName'][0]
                     except KeyError:
                         name = ""
                     try:
                         email = ldap_info['mail'][0]
                     except KeyError:
                         email = ""
                     try:
                         phone = ldap_info['telephoneNumber'][0]
                     except KeyError:
                         phone = ""
                     try:
                         address = ldap_info['physicalDeliveryOfficeName'][0]
                     except KeyError:
                         address = ""
                     try:
                         mailbox = ldap_info['postOfficeBox'][0]
                     except KeyError:
                         mailbox = ""
                     try:
                         ccid = ldap_info['employeeID'][0]
                     except KeyError:
                         ccid = ""
 
                     try:
                         db.new_borrower(ccid, name, email, phone,
                                     address, mailbox, '')
                     except:
                         pass
                     result = db.search_borrower_by_ccid(int(ccid))
 
     else:
         if column == 'name':
             result = db.search_borrower_by_name(string)
         elif column == 'email':
             result = db.search_borrower_by_email(string)
         else:
             result = db.search_borrower_by_id(string)
 
     return result
 
 def update_user_info_from_ldap(user_id):
     from invenio.bibcirculation_cern_ldap import get_user_info_from_ldap
     ccid = db.get_borrower_ccid(user_id)
     ldap_info = 'busy'
     while ldap_info == 'busy':
         time.sleep(1)
         ldap_info = get_user_info_from_ldap(ccid=ccid)
     if len(ldap_info) == 0:
         result = ()
     else:
         try:
             name    = ldap_info['displayName'][0]
         except KeyError:
             name    = ""
         try:
             email   = ldap_info['mail'][0]
         except KeyError:
             email   = ""
         try:
             phone   = ldap_info['telephoneNumber'][0]
         except KeyError:
             phone   = ""
         try:
             address = ldap_info['physicalDeliveryOfficeName'][0]
         except KeyError:
             address = ""
         try:
             mailbox = ldap_info['postOfficeBox'][0]
         except KeyError:
             mailbox = ""
         db.update_borrower(user_id, name, email, phone, address, mailbox)
         result = db.search_borrower_by_ccid(int(ccid))
     return result
 
 def get_book_cover(isbn):
     """
     Retrieve book cover using Amazon web services.
 
     @param isbn: book's isbn
     @type isbn: string
 
     @return book cover
     """
 
     from xml.dom import minidom
     import urllib
 
     # connect to AWS
     cover_xml = urllib.urlopen('http://ecs.amazonaws.com/onca/xml' \
                                '?Service=AWSECommerceService&AWSAccessKeyId=' \
                                + CFG_BIBCIRCULATION_AMAZON_ACCESS_KEY + \
                                '&Operation=ItemSearch&Condition=All&' \
                                'ResponseGroup=Images&SearchIndex=Books&' \
                                'Keywords=' + isbn)
 
     # parse XML
 
     try:
         xml_img = minidom.parse(cover_xml)
         retrieve_book_cover = xml_img.getElementsByTagName('MediumImage')
         book_cover = retrieve_book_cover.item(0).firstChild.firstChild.data
     except:
         book_cover = "%s/img/book_cover_placeholder.gif" % (CFG_SITE_URL)
 
     return book_cover
 
 def book_information_from_MARC(recid):
     """
     Retrieve book's information from MARC
 
     @param recid: identify the record. Primary key of bibrec.
     @type recid: int
 
     @return tuple with title, year, author, isbn and editor.
     """
     # FIXME do the same that book_title_from_MARC
 
     book_title  = book_title_from_MARC(recid)
 
     book_year   =   ''.join(get_fieldvalues(recid, "260__c"))
 
 
     author_tags = ['100__a', '700__a', '721__a']
     book_author = ''
 
     for tag in author_tags:
         l = get_fieldvalues(recid, tag)
         for c in l:
             book_author += c + '; '
     book_author = book_author[:-2]
 
     l = get_fieldvalues(recid, "020__a")
     book_isbn = ''
     for isbn in l:
         book_isbn += isbn + ', '
     book_isbn = book_isbn[:-2]
 
     book_editor = ', '.join(get_fieldvalues(recid, "260__a") + \
                             get_fieldvalues(recid, "260__b"))
 
     return (book_title, book_year, book_author, book_isbn, book_editor)
 
 def book_title_from_MARC(recid):
     """
     Retrieve book's title from MARC
 
     @param recid: identify the record. Primary key of bibrec.
     @type recid: int
 
     @return book's title
     """
 
     title_tags = get_field_tags('title')
 
     book_title = ''
     i = 0
     while book_title == '' and i < len(title_tags):
         l = get_fieldvalues(recid, title_tags[i])
         for candidate in l:
             book_title = book_title + candidate + ': '
         i += 1
 
     book_title = book_title[:-2]
 
     return book_title
 
 def update_status_if_expired(loan_id):
     """
     Update the loan's status if status is 'expired'.
 
     @param loan_id: identify the loan. Primary key of crcLOAN.
     @type loan_id: int
     """
 
     loan_status = db.get_loan_status(loan_id)
 
     if loan_status == CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED:
         db.update_loan_status(CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN, loan_id)
 
     return
 
 def get_next_day(date_string):
     """
     Get the next day
 
     @param date_string: date
     @type date_string: string
 
     return next day
     """
 
     # add 1 day
     more_1_day = datetime.timedelta(days=1)
 
     # convert date_string to datetime format
     tmp_date = time.strptime(date_string, '%Y-%m-%d')
 
     # calculate the new date (next day)
     next_day = datetime.datetime(tmp_date[0], tmp_date[1], tmp_date[2]) \
                                                                 + more_1_day
 
     return next_day
 
 def generate_new_due_date(days):
     """
     Generate a new due date (today + X days = new due date).
 
     @param days: number of days
     @type days: string
 
     @return new due date
     """
 
     today = datetime.date.today()
 
     more_X_days = datetime.timedelta(days=days)
 
     tmp_date = today + more_X_days
 
     week_day = tmp_date.strftime('%A')
     due_date = tmp_date.strftime('%Y-%m-%d')
 
     due_date_validated = False
 
     while not due_date_validated:
         if week_day in CFG_BIBCIRCULATION_WORKING_DAYS \
            and due_date not in CFG_BIBCIRCULATION_HOLIDAYS:
             due_date_validated = True
 
         else:
             next_day = get_next_day(due_date)
             due_date = next_day.strftime('%Y-%m-%d')
             week_day = next_day.strftime('%A')
 
     return due_date
 
 def renew_loan_for_X_days(barcode):
     """
     Renew a loan based on its loan period
 
     @param barcode: identify the item. Primary key of crcITEM.
     @type barcode: string
 
     @return new due date
     """
 
     loan_period = db.get_loan_period(barcode)
 
     if loan_period == '4 weeks':
         due_date = generate_new_due_date(30)
     else:
         due_date = generate_new_due_date(7)
 
     return due_date
 
 def make_copy_available(request_id):
     """
     Change the status of a copy for
     CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF when
     an hold request was cancelled.
 
     @param request_id: identify the request: Primary key of crcLOANREQUEST
     @type request_id: int
     """
 
     barcode_requested = db.get_requested_barcode(request_id)
     db.update_item_status(CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF, barcode_requested)
     update_requests_statuses(barcode_requested)
 
 
 def print_new_loan_information(req, ln=CFG_SITE_LANG):
     """
     Create a printable format with the information of the last
     loan who has been registered on the table crcLOAN.
     """
 
     _ = gettext_set_language(ln)
 
     # get the last loan from crcLOAN
     (recid, borrower_id, due_date) = db.get_last_loan()
 
     # get book's information
     (book_title, book_year, book_author,
                  book_isbn, book_editor) = book_information_from_MARC(recid)
 
     # get borrower's data/information (name, address, email)
     (borrower_name, borrower_address,
      borrower_mailbox, borrower_email) = db.get_borrower_data(borrower_id)
 
     # Generate printable format
     req.content_type = "text/html"
     req.send_http_header()
 
     out = """<table style='width:95%; margin:auto; max-width: 600px;'>"""
     out += """
            <tr>
                      <td><img src="%s/img/CERN_CDS_logo.png"></td>
                    </tr>
                   </table><br />""" % (CFG_SITE_URL)
 
     out += """<table style='color: #79d; font-size: 82%; width:95%;
                             margin:auto; max-width: 400px;'>"""
 
     out += """  <tr>
                     <td align="center">
                         <h2><strong>%s</strong></h2>
                     </td>
                 </tr>""" % (_("Loan information"))
 
     out += """  <tr>
                     <td align="center"><strong>%s</strong></td>
                 </tr>""" % (_("This book has been sent to you:"))
 
     out += """</table><br />"""
     out += """<table style='color: #79d; font-size: 82%; width:95%;
                             margin:auto; max-width: 400px;'>"""
     out += """  <tr>
                     <td width="70"><strong>%s</strong></td>
                     <td style='color: black;'>%s</td>
                 </tr>
                 <tr>
                     <td width="70"><strong>%s</strong></td>
                     <td style='color: black;'>%s</td>
                 </tr>
                 <tr>
                     <td width="70"><strong>%s</strong></td>
                     <td style='color: black;'>%s</td>
                 </tr>
                 <tr>
                     <td width="70"><strong>%s</strong></td>
                     <td style='color: black;'>%s</td>
                 </tr>
                 <tr>
                     <td width="70"><strong>%s</strong></td>
                     <td style='color: black;'>%s</td>
                 </tr>
                   """ % (_("Title"),  book_title,
                          _("Author"), book_author,
                          _("Editor"), book_editor,
                          _("ISBN"),   book_isbn,
                          _("Year"),   book_year)
 
     out += """</table><br />"""
 
     out += """<table style='color: #79d; font-size: 82%; width:95%;
                             margin:auto; max-width: 400px;'>"""
     out += """  <tr>
                     <td width="70"><strong>%s</strong></td>
                     <td style='color: black;'>%s</td>
                 </tr>
                 <tr>
                     <td width="70"><strong>%s</strong></td>
                     <td style='color: black;'>%s</td>
                 </tr>
                 <tr>
                     <td width="70"><strong>%s</strong></td>
                     <td style='color: black;'>%s</td>
                 </tr>
                 <tr>
                     <td width="70"><strong>%s</strong></td>
                     <td style='color: black;'>%s</td>
                 </tr>
            """ % (_("Name"),    borrower_name,
                   _("Mailbox"), borrower_mailbox,
                   _("Address"), borrower_address,
                   _("Email"),   borrower_email)
 
     out += """</table>
               <br />"""
 
     out += """<table style='color: #79d; font-size: 82%; width:95%;
                             margin:auto; max-width: 400px;'>"""
 
     out += """  <tr>
                     <td align="center"><h2><strong>%s: %s</strong></h2></td>
                 </tr>""" % (_("Due date"), due_date)
 
     out += """</table>"""
 
     out += """<table style='color: #79d; font-size: 82%; width:95%;
                             margin:auto; max-width: 800px;'>
                 <tr>
                     <td>
                         <input type="button" onClick='window.print()'
                                value='Print' style='color: #fff;
                                background: #36c; font-weight: bold;'>
                     </td>
                 </tr>
               </table>
            """
 
     req.write("<html>")
     req.write(out)
     req.write("</html>")
 
     return "\n"
 
 def print_pending_hold_requests_information(req, ln):
     """
     Create a printable format with all the information about all
     pending hold requests.
     """
 
     _ = gettext_set_language(ln)
 
     requests = db.get_pdf_request_data(CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING)
 
     req.content_type = "text/html"
     req.send_http_header()
 
     out = """<table style='width:100%; margin:auto; max-width: 1024px;'>"""
     out += """
                    <tr>
                      <td><img src="%s/img/CERN_CDS_logo.png"></td>
                    </tr>
                   </table><br />""" % (CFG_SITE_URL)
     out += """<table style='color: #79d; font-size: 82%;
                      width:95%; margin:auto; max-width: 1024px;'>"""
 
     out += """  <tr>
                     <td align="center"><h2><strong>%s</strong></h2></td>
                 </tr>""" % (_("List of pending hold requests"))
 
     out += """  <tr>
                     <td align="center"><strong>%s</strong></td>
                 </tr>""" % (time.ctime())
 
     out += """</table><br/>"""
 
     out += """<table style='color: #79d; font-size: 82%;
                      width:95%; margin:auto; max-width: 1024px;'>"""
 
     out += """<tr>
                        <td><strong>%s</strong></td>
                        <td><strong>%s</strong></td>
                        <td><strong>%s</strong></td>
                        <td><strong>%s</strong></td>
                        <td><strong>%s</strong></td>
                        <td><strong>%s</strong></td>
                        <td><strong>%s</strong></td>
                   </tr>
                        """ % (_("Borrower"),
                               _("Item"),
                               _("Library"),
                               _("Location"),
                               _("From"),
                               _("To"),
                               _("Request date"))
 
     for (recid, borrower_name, library_name, location,
          date_from, date_to, request_date) in requests:
 
         out += """<tr style='color: black;'>
                          <td class="bibcirccontent">%s</td>
                          <td class="bibcirccontent">%s</td>
                          <td class="bibcirccontent">%s</td>
                          <td class="bibcirccontent">%s</td>
                          <td class="bibcirccontent">%s</td>
                          <td class="bibcirccontent">%s</td>
                          <td class="bibcirccontent">%s</td>
                       </tr>
                          """ % (borrower_name, book_title_from_MARC(recid),
                                 library_name, location, date_from, date_to,
                                 request_date)
 
     out += """</table>
               <br />
               <br />
                   <table style='color: #79d; font-size: 82%;
                   width:95%; margin:auto; max-width: 1024px;'>
                   <tr>
                     <td>
                       <input type=button value='Back' onClick="history.go(-1)"
                              style='color: #fff; background: #36c;
                              font-weight: bold;'>
 
                       <input type="button" onClick='window.print()'
                       value='Print' style='color: #fff;
                                 background: #36c; font-weight: bold;'>
                     </td>
                   </tr>
                   </table>"""
 
     req.write("<html>")
     req.write(out)
     req.write("</html>")
 
     return "\n"
 
 def get_item_info_for_search_result(recid):
     """
     Get the item's info from MARC in order to create a
     search result with more details
 
     @param recid: identify the record. Primary key of bibrec.
     @type recid: int
 
     @return book's informations (author, editor and number of copies)
     """
 
     book_author = '  '.join(get_fieldvalues(recid, "100__a") + \
                             get_fieldvalues(recid, "100__u"))
 
     book_editor = ' , '.join(get_fieldvalues(recid, "260__a") + \
                              get_fieldvalues(recid, "260__b") + \
                              get_fieldvalues(recid, "260__c"))
 
     book_copies = '  '.join(get_fieldvalues(recid, "964__a"))
 
     book_infos = (book_author, book_editor, book_copies)
 
     return book_infos
 
 
 def update_request_data(request_id):
     """
     Update the status of a given request.
 
     @param request_id: identify the request: Primary key of crcLOANREQUEST
     @type request_id: int
     """
 
     barcode = db.get_request_barcode(request_id)
     is_on_loan = db.is_item_on_loan(barcode)
 
     if is_on_loan is not None:
         db.update_item_status(CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN, barcode)
     else:
         db.update_item_status(CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF, barcode)
 
     update_requests_statuses(barcode)
 
 
     return True
 
 
 def compare_dates(date):
     """
     Compare given date with today
 
     @param date: given date
     @type date: string
 
     @return boolean
     """
 
     if date < time.strftime("%Y-%m-%d"):
         return False
     else:
         return True
 
 def validate_date_format(date):
     """
     Verify the date format
 
     @param date: given date
     @type date: string
 
     @return boolean
     """
 
     try:
         if time.strptime(date, "%Y-%m-%d"):
             if compare_dates(date):
                 return True
         else:
             return False
     except ValueError:
         return False
 
 def create_ill_record(book_info):
     """
     Create a new ILL record
 
     @param book_info: book's information
     @type book_info: tuple
 
     @return MARC record
     """
 
     (title, author, place, publisher, year, edition, isbn) = book_info
 
     ill_record = """
         <record>
             <datafield tag="020" ind1=" " ind2=" ">
                 <subfield code="a">%(isbn)s</subfield>
             </datafield>
             <datafield tag="100" ind1=" " ind2=" ">
                 <subfield code="a">%(author)s</subfield>
             </datafield>
             <datafield tag="245" ind1=" " ind2=" ">
                 <subfield code="a">%(title)s</subfield>
             </datafield>
             <datafield tag="250" ind1=" " ind2=" ">
                 <subfield code="a">%(edition)s</subfield>
             </datafield>
             <datafield tag="260" ind1=" " ind2=" ">
                 <subfield code="a">%(place)s</subfield>
                 <subfield code="b">%(publisher)s</subfield>
                 <subfield code="c">%(year)s</subfield>
             </datafield>
             <datafield tag="980" ind1=" " ind2=" ">
                 <subfield code="a">ILLBOOK</subfield>
             </datafield>
         </record>
   """ % {'isbn':      encode_for_xml(isbn),
          'author':    encode_for_xml(author),
          'title':     encode_for_xml(title),
          'edition':   encode_for_xml(edition),
          'place':     encode_for_xml(place),
          'publisher': encode_for_xml(publisher),
          'year':      encode_for_xml(year)}
 
     file_path = '%s/%s_%s.xml' % (CFG_TMPDIR, 'bibcirculation_ill_book',
                                   time.strftime("%Y%m%d_%H%M%S"))
 
     xml_file = open(file_path, 'w')
     xml_file.write(ill_record)
     xml_file.close()
 
     # Pass XML file to BibUpload.
     task_low_level_submission('bibupload', 'bibcirculation',
                               '-P', '5', '-i', file_path)
 
     return ill_record
 
 
 def wash_recid_from_ILL_request(ill_request_id):
     """
     Get dictionnary and wash recid values.
 
     @param ill_request_id: identify the ILL request. Primray key of crcILLREQUEST
     @type ill_request_id: int
 
     @return recid
     """
 
     book_info = db.get_ill_book_info(ill_request_id)
     book_info = eval(book_info)
 
     try:
         recid = int(book_info['recid'])
     except KeyError:
         recid = None
 
     return recid
 
 def all_copies_are_missing(recid):
     """
     Verify if all copies of an item are missing
 
     @param recid: identify the record. Primary key of bibrec
     @type recid: int
 
     @return boolean
     """
 
     copies_status = db.get_copies_status(recid)
     number_of_missing = 0
     if copies_status == None:
         return True
     else:
         for (status) in copies_status:
             if status == 'missing':
                 number_of_missing += 1
 
         if number_of_missing == len(copies_status):
             return True
         else:
             return False
 
 #def has_copies(recid):
 #    """
 #    Verify if a recid is item (has copies)
 #
 #    @param recid: identify the record. Primary key of bibrec
 #    @type recid: int
 #
 #    @return boolean
 #    """
 #
 #    copies_status = db.get_copies_status(recid)
 #
 #    if copies_status is None:
 #        return False
 #    else:
 #        if len(copies_status) == 0:
 #            return False
 #        else:
 #            return True
 
 def generate_email_body(template, loan_id):
     """
     Generate the body of an email for loan recalls.
 
     @param template: email template
     @type template: string
 
     @param loan_id: identify the loan. Primary key of crcLOAN.
     @type loan_id: int
 
     @return email(body)
     """
 
     recid = db.get_loan_recid(loan_id)
     (book_title, book_year, book_author,
      book_isbn, book_editor) = book_information_from_MARC(int(recid))
 
     out = template % (book_title, book_year, book_author,
                       book_isbn, book_editor)
 
     return out
 
 def create_item_details_url(recid, ln):
     url = '/admin2/bibcirculation/get_item_details?ln=%s&recid=%s' % (ln,
                                                                     str(recid))
     return CFG_SITE_URL + url
 
 def tag_all_requests_as_done(barcode, user_id):
     recid = db.get_recid(barcode)
     list_of_barcodes = db.get_barcodes(recid)
     for bc in list_of_barcodes:
         db.tag_requests_as_done(bc, user_id)
 
 def update_requests_statuses(barcode, recid=None):
     if recid == None:
         recid = db.get_recid(barcode)
     list_of_pending_requests = db.get_requests(recid,
                                     CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING)
     some_copy_available = False
     copies_status = db.get_copies_status(recid)
     if copies_status is not None:
         for status in copies_status:
             if status in (CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF,
                           CFG_BIBCIRCULATION_ITEM_STATUS_IN_PROCESS):
                 some_copy_available = True
 
     if len(list_of_pending_requests) == 1:
         if not some_copy_available:
             db.update_loan_request_status(list_of_pending_requests[0][0],
                                     CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING)
         else:
             return list_of_pending_requests[0][0]
 
     elif len(list_of_pending_requests) == 0:
         if some_copy_available:
             list_of_waiting_requests = db.get_requests(recid,
                                     CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING)
             if len(list_of_waiting_requests) > 0:
                 db.update_loan_request_status(list_of_waiting_requests[0][0],
                                     CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING)
                 return list_of_waiting_requests[0][0]
 
     elif len(list_of_pending_requests) > 1:
         for request in list_of_pending_requests:
             db.update_loan_request_status(request[0],
                                     CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING)
         list_of_waiting_requests = db.get_requests(recid,
                                     CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING)
         if some_copy_available:
             db.update_loan_request_status(list_of_waiting_requests[0][0],
                                     CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING)
             return list_of_waiting_requests[0][0]
 
     return None
 
 def is_periodical(recid):
     rec_type = get_fieldvalues(recid, "690C_a")
     if len(rec_type) > 0:
         for value in rec_type:
             if value == 'PERI':
                 return True
 
     return False
 
 def has_date_format(date):
 
     if type(date) is not str:
         return False
 
     date = date.strip()
 
     if len(date) is not 10:
         return False
     elif date[4] is not '-' and date[7] is not '-':
         return False
     else:
         year = date[:4]
         month = date[5:7]
         day = date[8:]
 
         return year.isdigit() and month.isdigit() and day.isdigit()
 
 def generate_tmp_barcode():
 
     tmp_barcode = 'tmp-' + str(random.random())[-8:]
 
     while(db.barcode_in_use(tmp_barcode)):
-        random_number = generate
         tmp_barcode = 'tmp-' + str(random.random())[-8:]
 
     return tmp_barcode
 
 
 def check_database():
 
     from invenio.dbquery import run_sql
 
     r1 = run_sql(""" SELECT it.barcode, it.status, ln.status
                        FROM crcITEM it, crcLOAN ln
                       WHERE ln.barcode=it.barcode
                         AND it.status=%s
                         AND ln.status!=%s
                         AND ln.status!=%s
                         AND ln.status!=%s
                  """, (CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN,
                         CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN,
                         CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED,
                         CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED))
 
     r2 = run_sql(""" SELECT it.barcode
                        FROM crcITEM it, crcLOAN ln
                       WHERE ln.barcode=it.barcode
                         AND it.status=%s
                         AND (ln.status=%s or ln.status=%s)
                  """, (CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF,
                         CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN,
                         CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED))
 
     r3 = run_sql(""" SELECT l1.barcode, l1.id,
                             DATE_FORMAT(l1.loaned_on,'%%Y-%%m-%%d %%H:%%i:%%s'),
                             DATE_FORMAT(l2.loaned_on,'%%Y-%%m-%%d %%H:%%i:%%s')
                        FROM crcLOAN l1,
                             crcLOAN l2
                       WHERE l1.id!=l2.id
                         AND l1.status!=%s
                         AND l1.status=l2.status
                         AND l1.barcode=l2.barcode
                    ORDER BY l1.loaned_on
                  """, (CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED, ))
 
     r4 = run_sql(""" SELECT id, id_crcBORROWER, barcode,
                             due_date, number_of_renewals
                        FROM crcLOAN
                       WHERE status=%s
                         AND due_date>NOW()
                  """, (CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED, ))
 
     return (len(r1), len(r2), len(r3), len(r4))
diff --git a/modules/bibcirculation/lib/bibcirculation_webinterface.py b/modules/bibcirculation/lib/bibcirculation_webinterface.py
index d39af3a4a..0e4e9381a 100644
--- a/modules/bibcirculation/lib/bibcirculation_webinterface.py
+++ b/modules/bibcirculation/lib/bibcirculation_webinterface.py
@@ -1,1266 +1,1260 @@
 # -*- coding: utf-8 -*-
 ##
 ## This file is part of Invenio.
 ## Copyright (C) 2008, 2009, 2010, 2011 CERN.
 ##
 ## Invenio is free software; you can redistribute it and/or
 ## modify it under the terms of the GNU General Public License as
 ## published by the Free Software Foundation; either version 2 of the
 ## License, or (at your option) any later version.
 ##
 ## Invenio is distributed in the hope that it will be useful, but
 ## WITHOUT ANY WARRANTY; without even the implied warranty of
 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 ## General Public License for more details.
 ##
 ## You should have received a copy of the GNU General Public License
 ## along with Invenio; if not, write to the Free Software Foundation, Inc.,
 ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 
 
 """ Bibcirculation web interface """
 
 __revision__ = "$Id$"
 
 __lastupdated__ = """$Date$"""
 
 # others invenio imports
 from invenio.config import CFG_SITE_LANG, \
                            CFG_SITE_SECURE_URL, \
                            CFG_ACCESS_CONTROL_LEVEL_SITE, \
                            CFG_WEBSESSION_DIFFERENTIATE_BETWEEN_GUESTS, \
                            CFG_SITE_RECORD, \
                            CFG_CERN_SITE
 
 from invenio.webuser import getUid, page_not_authorized, isGuestUser, \
                             collect_user_info
 from invenio.webpage import page, pageheaderonly, pagefooteronly
 from invenio.search_engine import create_navtrail_links, \
      guess_primary_collection_of_a_record, \
      get_colID, check_user_can_view_record, \
      record_exists
 from invenio.urlutils import redirect_to_url, \
                              make_canonical_urlargd
 
 from invenio.messages import gettext_set_language
 from invenio.webinterface_handler import wash_urlargd, WebInterfaceDirectory
 from invenio.websearchadminlib import get_detailed_page_tabs
 from invenio.access_control_config import VIEWRESTRCOLL
 from invenio.access_control_mailcookie import mail_cookie_create_authorize_action
 import invenio.template
 webstyle_templates = invenio.template.load('webstyle')
 websearch_templates = invenio.template.load('websearch')
 
 # bibcirculation imports
 bc_templates = invenio.template.load('bibcirculation')
 import invenio.bibcirculation_dblayer as db
 
 from invenio.bibcirculation_utils import search_user
 from invenio.bibcirculation import perform_new_request, \
                                    perform_new_request_send, \
                                    perform_get_holdings_information, \
                                    perform_borrower_loans, \
                                    perform_loanshistoricaloverview, \
                                    ill_register_request, \
                                    ill_request_with_recid, \
                                    ill_register_request_with_recid
 from invenio.bibcirculation_config import CFG_BIBCIRCULATION_ILL_STATUS_NEW, \
                                           CFG_BIBCIRCULATION_ACQ_STATUS_NEW
 import time
 
 class WebInterfaceYourLoansPages(WebInterfaceDirectory):
     """Defines the set of /yourloans pages."""
 
     _exports = ['', 'display', 'loanshistoricaloverview']
 
     def __init__(self, recid=-1):
         self.recid = recid
 
     def index(self, req, form):
         """ The function called by default
         """
         redirect_to_url(req, "%s/yourloans/display?%s" % (CFG_SITE_SECURE_URL,
                                                           req.args))
 
     def display(self, req, form):
         """
         Displays all loans of a given user
         @param ln:  language
         @return the page for inbox
         """
 
         argd = wash_urlargd(form, {'barcode': (str, ""),
                                    'borrower_id': (int, 0),
                                    'request_id': (int, 0),
                                    'action': (str, "")})
 
         # Check if user is logged
         uid = getUid(req)
         if CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
             return page_not_authorized(req, "%s/yourloans/display" % \
                                        (CFG_SITE_SECURE_URL,),
                                        navmenuid="yourloans")
         elif uid == -1 or isGuestUser(uid):
             return redirect_to_url(req, "%s/youraccount/login%s" % (
                 CFG_SITE_SECURE_URL,
                 make_canonical_urlargd({
                     'referer' : "%s/yourloans/display%s" % (
                         CFG_SITE_SECURE_URL,
                         make_canonical_urlargd(argd, {})),
                     "ln" : argd['ln']}, {})), norobot=True)
 
         _ = gettext_set_language(argd['ln'])
 
         user_info = collect_user_info(req)
         if not user_info['precached_useloans']:
             return page_not_authorized(req, "../", \
                                        text = _("You are not authorized to use loans."))
 
         body = perform_borrower_loans(uid=uid,
                                       barcode=argd['barcode'],
                                       borrower_id=argd['borrower_id'],
                                       request_id=argd['request_id'],
                                       action=argd['action'],
                                       ln=argd['ln'])
 
         return page(title       = _("Your Loans"),
                     body        = body,
                     uid         = uid,
                     lastupdated = __lastupdated__,
                     req         = req,
                     language    = argd['ln'],
                     navmenuid   = "yourloans",
                     secure_page_p=1)
 
     def loanshistoricaloverview(self, req, form):
         """
         Show loans historical overview.
         """
 
         argd = wash_urlargd(form, {})
 
         # Check if user is logged
         uid = getUid(req)
         if CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
             return page_not_authorized(req, "%s/yourloans/loanshistoricaloverview" % \
                                        (CFG_SITE_SECURE_URL,),
                                        navmenuid="yourloans")
         elif uid == -1 or isGuestUser(uid):
             return redirect_to_url(req, "%s/youraccount/login%s" % (
                 CFG_SITE_SECURE_URL,
                 make_canonical_urlargd({
                     'referer' : "%s/yourloans/loanshistoricaloverview%s" % (
                         CFG_SITE_SECURE_URL,
                         make_canonical_urlargd(argd, {})),
                     "ln" : argd['ln']}, {})), norobot=True)
 
         _ = gettext_set_language(argd['ln'])
 
         user_info = collect_user_info(req)
         if not user_info['precached_useloans']:
             return page_not_authorized(req, "../", \
                             text = _("You are not authorized to use loans."))
 
         body = perform_loanshistoricaloverview(uid=uid,
                                                ln=argd['ln'])
 
         return page(title       = _("Loans - historical overview"),
                     body        = body,
                     uid         = uid,
                     lastupdated = __lastupdated__,
                     req         = req,
                     language    = argd['ln'],
                     navmenuid   = "yourloans",
                     secure_page_p=1)
 
 
 class WebInterfaceILLPages(WebInterfaceDirectory):
     """Defines the set of /ill pages."""
 
 
     _exports = ['', 'register_request', 'book_request_step1',
                 'book_request_step2','book_request_step3',
                 'article_request_step1', 'article_request_step2',
                 'article_request_step3', 'acq_request_step1',
                 'acq_request_step2']
 
     def index(self, req, form):
         """ The function called by default
         """
         redirect_to_url(req, "%s/ill/display?%s" % (CFG_SITE_SECURE_URL,
                                                           req.args))
 
     def book_request_step1(self, req, form):
         """
         Displays all loans of a given user
         @param ln:  language
         @return the page for inbox
         """
 
         argd = wash_urlargd(form, {})
 
         # Check if user is logged
         uid = getUid(req)
         if CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
             return page_not_authorized(req, "%s/ill/display" % \
                                        (CFG_SITE_SECURE_URL,),
                                        navmenuid="ill")
         elif uid == -1 or isGuestUser(uid):
             return redirect_to_url(req, "%s/youraccount/login%s" % (
                 CFG_SITE_SECURE_URL,
                 make_canonical_urlargd({
                     'referer' : "%s/ill/display%s" % (
                         CFG_SITE_SECURE_URL,
                         make_canonical_urlargd(argd, {})),
                     "ln" : argd['ln']}, {})), norobot=True)
 
         _ = gettext_set_language(argd['ln'])
 
         user_info = collect_user_info(req)
         if not user_info['precached_useloans']:
             return page_not_authorized(req, "../", \
                                        text = _("You are not authorized to use ill."))
 
         ### get borrower_id ###
         borrower_id = search_user('email', user_info['email'])
         if borrower_id == ():
             body = "wrong user id"
         else:
             body = bc_templates.tmpl_register_ill_request_with_no_recid_step1([], None, False, argd['ln'])
         #body = display_ill_form(ln=argd['ln'])
 
         return page(title       = _("Interlibrary loan request for books"),
                     body        = body,
                     uid         = uid,
                     lastupdated = __lastupdated__,
                     req         = req,
                     language    = argd['ln'],
                     navmenuid   = "ill")
 
     def book_request_step2(self, req, form):
         """
         Displays all loans of a given user
         @param ln:  language
         @return the page for inbox
         """
 
         argd = wash_urlargd(form, {'title': (str, None), 'authors': (str, None),
             'place': (str, None), 'publisher': (str, None), 'year': (str, None),
             'edition': (str, None), 'isbn': (str, None), 'budget_code': (str, ''),
             'period_of_interest_from': (str, None), 'period_of_interest_to': (str, None),
             'additional_comments': (str, None), 'only_edition': (str, 'No'),'ln': (str, "en")})
 
         title = argd['title']
         authors = argd['authors']
         place = argd['place']
         publisher = argd['publisher']
         year = argd['year']
         edition = argd['edition']
         isbn = argd['isbn']
         budget_code = argd['budget_code']
         period_of_interest_from = argd['period_of_interest_from']
         period_of_interest_to = argd['period_of_interest_to']
         additional_comments = argd['additional_comments']
         only_edition = argd['only_edition']
         #key = argd['key']
         #string = argd['string']
         #borrower_id = argd['borrower_id']
         ln = argd['ln']
 
         #if borrower_id == 'None':
         #    borrower_id = None
         #else:
         #    borrower_id = borrower_id.strip()
 
         if title is not None:
             title = title.strip()
         if authors is not None:
             authors = authors.strip()
         if place is not None:
             place = place.strip()
         if publisher is not None:
             publisher = publisher.strip()
         if year is not None:
             year = year.strip()
         if edition is not None:
             edition =  edition.strip()
         if isbn is not None:
             isbn = isbn.strip()
         if budget_code is not None:
             budget_code = budget_code.strip()
         if period_of_interest_from is not None:
             period_of_interest_from = period_of_interest_from.strip()
         if period_of_interest_to is not None:
             period_of_interest_to = period_of_interest_to.strip()
         #string = string.strip()
 
         # Check if user is logged
         uid = getUid(req)
         if CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
             return page_not_authorized(req, "%s/ill/book_request_step2" % \
                                        (CFG_SITE_URL,),
                                        navmenuid="ill")
         elif uid == -1 or isGuestUser(uid):
             return redirect_to_url(req, "%s/youraccount/login%s" % (
                 CFG_SITE_SECURE_URL,
                 make_canonical_urlargd({
                     'referer' : "%s/ill/book_request_step2%s" % (
                         CFG_SITE_URL,
                         make_canonical_urlargd(argd, {})),
                     "ln" : ln}, {})), norobot=True)
 
         _ = gettext_set_language(ln)
 
         user_info = collect_user_info(req)
         if not user_info['precached_useloans']:
             return page_not_authorized(req, "../", \
                                        text = _("You are not authorized to use ill."))
 
         if CFG_CERN_SITE:
             borrower_id = search_user('ccid', user_info['external_hidden_personid'])
         else:
             borrower_id = search_user('email', user_info['email'])
 
         if borrower_id != ():
             borrower_id = borrower_id[0][0]
 
             book_info = (title, authors, place, publisher,
                          year, edition, isbn)
             user_info = db.get_borrower_data_by_id(borrower_id)
 
             request_details = (budget_code, period_of_interest_from,
                                period_of_interest_to, additional_comments,
                                only_edition)
             body = bc_templates.tmpl_register_ill_request_with_no_recid_step3(
                                         book_info, user_info, request_details, False, ln)
 
         else:
             body = "wrong user id"
 
         return page(title       = _("Interlibrary loan request for books"),
                     body        = body,
                     uid         = uid,
                     lastupdated = __lastupdated__,
                     req         = req,
                     language    = ln,
                     navmenuid   = "ill")
 
     def book_request_step3(self, req, form):
         """
         Displays all loans of a given user
         @param ln:  language
         @return the page for inbox
         """
 
         argd = wash_urlargd(form, {'title': (str, None), 'authors': (str, None),
             'place': (str, None), 'publisher': (str, None), 'year': (str, None),
             'edition': (str, None), 'isbn': (str, None), 'borrower_id': (str, None),
             'budget_code': (str, ''), 'period_of_interest_from': (str, None),
             'period_of_interest_to': (str, None), 'additional_comments': (str, None),
             'only_edition': (str, None), 'ln': (str, "en")})
 
         title = argd['title']
         authors = argd['authors']
         place = argd['place']
         publisher = argd['publisher']
         year = argd['year']
         edition = argd['edition']
         isbn = argd['isbn']
 
         borrower_id = argd['borrower_id']
 
         budget_code = argd['budget_code']
         period_of_interest_from = argd['period_of_interest_from']
         period_of_interest_to = argd['period_of_interest_to']
         library_notes = argd['additional_comments']
         only_edition = argd['only_edition']
 
         ln = argd['ln']
 
         book_info = (title, authors, place, publisher, year, edition, isbn)
         #request_details = (budget_code, period_of_interest_from, period_of_interest_to,
         #                    library_notes, only_edition)
 
         # Check if user is logged
         uid = getUid(req)
         if CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
             return page_not_authorized(req, "%s/ill/book_request_step2" % \
                                        (CFG_SITE_URL,),
                                        navmenuid="ill")
         elif uid == -1 or isGuestUser(uid):
             return redirect_to_url(req, "%s/youraccount/login%s" % (
                 CFG_SITE_SECURE_URL,
                 make_canonical_urlargd({
                     'referer' : "%s/ill/book_request_step2%s" % (
                         CFG_SITE_URL,
                         make_canonical_urlargd(argd, {})),
                     "ln" : argd['ln']}, {})), norobot=True)
 
         _ = gettext_set_language(argd['ln'])
 
         user_info = collect_user_info(req)
         if not user_info['precached_useloans']:
             return page_not_authorized(req, "../", \
                                        text = _("You are not authorized to use ill."))
 
         book_info = {'title': title, 'authors': authors, 'place': place,
                      'publisher': publisher, 'year' : year,
                      'edition': edition, 'isbn' : isbn}
 
         ill_request_notes = {}
         if library_notes:
             ill_request_notes[time.strftime("%Y-%m-%d %H:%M:%S")] = str(library_notes)
 
         ### budget_code ###
         db.ill_register_request_on_desk(borrower_id, book_info,
                                         period_of_interest_from,
                                         period_of_interest_to,
                                         CFG_BIBCIRCULATION_ILL_STATUS_NEW,
                                         str(ill_request_notes), only_edition,
                                         'book', budget_code)
 
         infos = []
         infos.append('Interlibrary loan request done.')
         body = bc_templates.tmpl_infobox(infos, ln)
 
         return page(title       = _("Interlibrary loan request for books"),
                     body        = body,
                     uid         = uid,
                     lastupdated = __lastupdated__,
                     req         = req,
                     language    = argd['ln'],
                     navmenuid   = "ill")
 
     def acq_request_step1(self, req, form):
         """
         Displays all loans of a given user
         @param ln:  language
         @return the page for inbox
         """
 
         argd = wash_urlargd(form, {'type': (str, 'acq-book'),
                 'title': (str, ''), 'authors': (str, ''), 'place': (str, ''),
                 'publisher': (str, ''), 'year': (str, ''), 'edition': (str, ''),
                 'this_edition_only': (str, 'No'),
                 'isbn': (str, ''), 'standard_number': (str, ''),
                 'budget_code': (str, ''), 'cash': (str, 'No'),
                 'period_of_interest_from': (str, ''),
                 'period_of_interest_to': (str, ''),
                 'additional_comments': (str, ''), 'ln': (str, "en")})
 
-        type = argd['type'].strip()
+        request_type = argd['type'].strip()
         title = argd['title'].strip()
         authors = argd['authors'].strip()
         place = argd['place'].strip()
         publisher = argd['publisher'].strip()
         year = argd['year'].strip()
         edition = argd['edition'].strip()
         this_edition_only = argd['this_edition_only'].strip()
         isbn = argd['isbn'].strip()
         standard_number = argd['standard_number'].strip()
         budget_code = argd['budget_code'].strip()
         cash = argd['cash'] == 'Yes'
         period_of_interest_from = argd['period_of_interest_from'].strip()
         period_of_interest_to = argd['period_of_interest_to'].strip()
         additional_comments = argd['additional_comments'].strip()
         ln = argd['ln']
 
-        fields = (type, title, authors, place, publisher, year, edition,
+        fields = (request_type, title, authors, place, publisher, year, edition,
                   this_edition_only, isbn, standard_number, budget_code,
                   cash, period_of_interest_from, period_of_interest_to,
                   additional_comments)
 
         # Check if user is logged
         uid = getUid(req)
         if CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
             return page_not_authorized(req, "%s/ill/acq_request_step1" % \
                                        (CFG_SITE_URL,),
                                        navmenuid="ill")
         elif uid == -1 or isGuestUser(uid):
             return redirect_to_url(req, "%s/youraccount/login%s" % (
                 CFG_SITE_SECURE_URL,
                 make_canonical_urlargd({
                     'referer' : "%s/ill/acq_request_step1%s" % (
                         CFG_SITE_URL,
                         make_canonical_urlargd(argd, {})),
                     "ln" : argd['ln']}, {})), norobot=True)
 
         _ = gettext_set_language(argd['ln'])
 
         user_info = collect_user_info(req)
         if not user_info['precached_useloans']:
             return page_not_authorized(req, "../", \
                                 text = _("You are not authorized to use ill."))
 
         ### get borrower_id ###
         borrower_id = search_user('email', user_info['email'])
         if borrower_id == ():
             body = "wrong user id"
         else:
             body = bc_templates.tmpl_register_purchase_request_step1([], fields,
-                                                            False, argd['ln'])
+                                                            False, ln)
 
         return page(title       = _("Purchase request"),
                     body        = body,
                     uid         = uid,
                     lastupdated = __lastupdated__,
                     req         = req,
                     language    = argd['ln'],
                     navmenuid   = "ill")
 
     def acq_request_step2(self, req, form):
 
         argd = wash_urlargd(form, {'type': (str, 'acq-book'),
                 'title': (str, ''), 'authors': (str, ''), 'place': (str, ''),
                 'publisher': (str, ''), 'year': (str, ''), 'edition': (str, ''),
                 'this_edition_only': (str, 'No'),
                 'isbn': (str, ''), 'standard_number': (str, ''),
                 'budget_code': (str, ''), 'cash': (str, 'No'),
                 'period_of_interest_from': (str, ''),
                 'period_of_interest_to': (str, ''),
                 'additional_comments': (str, ''), 'ln': (str, "en")})
 
-        type = argd['type'].strip()
+        request_type = argd['type'].strip()
         title = argd['title'].strip()
         authors = argd['authors'].strip()
         place = argd['place'].strip()
         publisher = argd['publisher'].strip()
         year = argd['year'].strip()
         edition = argd['edition'].strip()
         this_edition_only = argd['this_edition_only'].strip()
         isbn = argd['isbn'].strip()
         standard_number = argd['standard_number'].strip()
         budget_code = argd['budget_code'].strip()
         cash = argd['cash'] == 'Yes'
         period_of_interest_from = argd['period_of_interest_from'].strip()
         period_of_interest_to = argd['period_of_interest_to'].strip()
         additional_comments = argd['additional_comments'].strip()
         ln = argd['ln']
 
-        fields = (type, title, authors, place, publisher, year, edition,
+        fields = (request_type, title, authors, place, publisher, year, edition,
                   this_edition_only, isbn, standard_number, budget_code,
                   cash, period_of_interest_from, period_of_interest_to,
                   additional_comments)
 
         # Check if user is logged
         uid = getUid(req)
         if CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
             return page_not_authorized(req, "%s/ill/acq_request_step1" % \
                                        (CFG_SITE_URL,),
                                        navmenuid="ill")
         elif uid == -1 or isGuestUser(uid):
             return redirect_to_url(req, "%s/youraccount/login%s" % (
                 CFG_SITE_SECURE_URL,
                 make_canonical_urlargd({
                     'referer' : "%s/ill/acq_request_step2%s" % (
                         CFG_SITE_URL,
                         make_canonical_urlargd(argd, {})),
                     "ln" : argd['ln']}, {})), norobot=True)
 
         _ = gettext_set_language(argd['ln'])
 
         user_info = collect_user_info(req)
         if not user_info['precached_useloans']:
             return page_not_authorized(req, "../", \
                                 text = _("You are not authorized to use ill."))
 
         infos = []
 
         if budget_code == '' and not cash:
             infos.append(_("Payment method information is mandatory. Please, type your budget code or tick the 'cash' checkbox."))
             body = bc_templates.tmpl_register_purchase_request_step1(infos=infos,
-                                    fields=(type, title, authors, place, publisher,
-                                            year, edition, this_edition_only,
-                                            isbn, standard_number,
-                                            budget_code, cash,
-                                            period_of_interest_from,
-                                            period_of_interest_to,
-                                            additional_comments),
-                                    ln=ln)
+                                                                fields=fields,
+                                                                ln=ln)
         else:
             borrower_id = db.get_borrower_id_by_email(\
                                             db.get_invenio_user_email(uid))
 
             item_info = {'title': title, 'authors': authors, 'place': place,
                          'publisher': publisher, 'year' : year,
                          'edition': edition, 'isbn' : isbn,
                          'standard_number': standard_number}
 
             ill_request_notes = {}
             if additional_comments:
                 ill_request_notes[time.strftime("%Y-%m-%d %H:%M:%S")] \
                                                       = str(additional_comments)
 
             if cash and budget_code == '':
                 budget_code = 'cash'
 
             db.ill_register_request_on_desk(borrower_id, item_info,
                                             period_of_interest_from,
                                             period_of_interest_to,
                                             CFG_BIBCIRCULATION_ACQ_STATUS_NEW,
                                             str(ill_request_notes),
-                                            this_edition_only, type,
+                                            this_edition_only, request_type,
                                             budget_code)
 
             body = bc_templates.tmpl_message_purchase_request_send_ok_other(ln=ln)
 
         return page(title=_("Register purchase request"),
                     uid=uid,
                     req=req,
                     body=body,
                     language=ln,
                     metaheaderadd='<link rel="stylesheet" ' \
                                         'href="%s/img/jquery-ui.css" ' \
                                         'type="text/css" />' % CFG_SITE_URL,
                     lastupdated=__lastupdated__)
 
     def article_request_step1(self, req, form):
         """
         Displays all loans of a given user
         @param ln:  language
         @return the page for inbox
         """
 
         argd = wash_urlargd(form, {})
 
         # Check if user is logged
         uid = getUid(req)
         if CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
             return page_not_authorized(req, "%s/ill/article_request_step1" % \
                                        (CFG_SITE_URL,),
                                        navmenuid="ill")
         elif uid == -1 or isGuestUser(uid):
             return redirect_to_url(req, "%s/youraccount/login%s" % (
                 CFG_SITE_SECURE_URL,
                 make_canonical_urlargd({
                     'referer' : "%s/ill/article_request_step1%s" % (
                         CFG_SITE_URL,
                         make_canonical_urlargd(argd, {})),
                     "ln" : argd['ln']}, {})), norobot=True)
 
         _ = gettext_set_language(argd['ln'])
 
         user_info = collect_user_info(req)
         if not user_info['precached_useloans']:
             return page_not_authorized(req, "../", \
                                        text = _("You are not authorized to use ill."))
 
         ### get borrower_id ###
         borrower_id = search_user('email', user_info['email'])
         if borrower_id == ():
             body = "Wrong user id"
         else:
             body = bc_templates.tmpl_register_ill_article_request_step1([], False, argd['ln'])
 
         return page(title       = _("Interlibrary loan request for articles"),
                     body        = body,
                     uid         = uid,
                     lastupdated = __lastupdated__,
                     req         = req,
                     language    = argd['ln'],
                     navmenuid   = "ill")
 
     def article_request_step2(self, req, form):
         """
         Displays all loans of a given user
         @param ln:  language
         @return the page for inbox
         """
 
         argd = wash_urlargd(form, {'periodical_title': (str, None), 'article_title': (str, None),
             'author': (str, None), 'report_number': (str, None), 'volume': (str, None),
             'issue': (str, None), 'page': (str, None), 'year': (str, None),
             'budget_code': (str, ''), 'issn': (str, None),
             'period_of_interest_from': (str, None), 'period_of_interest_to': (str, None),
             'additional_comments': (str, None), 'key': (str, None), 'string': (str, None),
             'ln': (str, "en")})
 
         # Check if user is logged
         uid = getUid(req)
         if CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
             return page_not_authorized(req, "%s/ill/article_request_step2" % \
                                        (CFG_SITE_URL,),
                                        navmenuid="ill")
         elif uid == -1 or isGuestUser(uid):
             return redirect_to_url(req, "%s/youraccount/login%s" % (
                 CFG_SITE_SECURE_URL,
                 make_canonical_urlargd({
                     'referer' : "%s/ill/article_request_step2%s" % (
                         CFG_SITE_URL,
                         make_canonical_urlargd(argd, {})),
                     "ln" : argd['ln']}, {})), norobot=True)
 
         _ = gettext_set_language(argd['ln'])
 
         user_info = collect_user_info(req)
         if not user_info['precached_useloans']:
             return page_not_authorized(req, "../", \
                                 text = _("You are not authorized to use ill."))
 
         borrower_id = search_user('email', user_info['email'])
         if borrower_id != ():
             borrower_id = borrower_id[0][0]
             notes = argd['additional_comments']
             ill_request_notes = {}
             if notes:
                 ill_request_notes[time.strftime("%Y-%m-%d %H:%M:%S")] = str(notes)
 
             item_info = {'periodical_title': argd['periodical_title'],
                 'title': argd['article_title'], 'authors': argd['author'],
                 'place': "", 'publisher': "", 'year' : argd['year'],
                 'edition': "", 'issn' : argd['issn'], 'volume': argd['volume'],
                 'page': argd['page'], 'issue': argd['issue'] }
 
             ### budget_code ###
             db.ill_register_request_on_desk(borrower_id, item_info,
                                     argd['period_of_interest_from'],
                                     argd['period_of_interest_to'],
                                     CFG_BIBCIRCULATION_ILL_STATUS_NEW,
                                     str(ill_request_notes), 'No', 'article',
                                     argd['budget_code'])
 
             infos = []
             infos.append('Interlibrary loan request done.')
             body = bc_templates.tmpl_infobox(infos, argd['ln'])
 
         else:
             body = _("Wrong user id")
 
         return page(title       = _("Interlibrary loan request for books"),
                     body        = body,
                     uid         = uid,
                     lastupdated = __lastupdated__,
                     req         = req,
                     language    = argd['ln'],
                     navmenuid   = "ill")
 
 
     def register_request(self, req, form):
         """
         Displays all loans of a given user
         @param ln:  language
         @return the page for inbox
         """
 
         argd = wash_urlargd(form, {'ln': (str, ""),
                                    'title': (str, ""),
                                    'authors': (str, ""),
                                    'place': (str, ""),
                                    'publisher': (str, ""),
                                    'year': (str, ""),
                                    'edition': (str, ""),
                                    'isbn': (str, ""),
                                    'period_of_interest_from': (str, ""),
                                    'period_of_interest_to': (str, ""),
                                    'additional_comments': (str, ""),
                                    'conditions': (str, ""),
                                    'only_edition': (str, ""),
                                    })
 
         # Check if user is logged
         uid = getUid(req)
         if CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
             return page_not_authorized(req, "%s/ill/register_request" % \
                                        (CFG_SITE_SECURE_URL,),
                                        navmenuid="ill")
         elif uid == -1 or isGuestUser(uid):
             return redirect_to_url(req, "%s/youraccount/login%s" % (
                 CFG_SITE_SECURE_URL,
                 make_canonical_urlargd({
                     'referer' : "%s/ill/register_request%s" % (
                         CFG_SITE_SECURE_URL,
                         make_canonical_urlargd(argd, {})),
                     "ln" : argd['ln']}, {})), norobot=True)
 
         _ = gettext_set_language(argd['ln'])
 
         user_info = collect_user_info(req)
         if not user_info['precached_useloans']:
             return page_not_authorized(req, "../", \
                                 text = _("You are not authorized to use ill."))
 
         body = ill_register_request(uid=uid,
                         title=argd['title'],
                         authors=argd['authors'],
                         place=argd['place'],
                         publisher=argd['publisher'],
                         year=argd['year'],
                         edition=argd['edition'],
                         isbn=argd['isbn'],
                         period_of_interest_from=argd['period_of_interest_from'],
                         period_of_interest_to=argd['period_of_interest_to'],
                         additional_comments=argd['additional_comments'],
                         conditions=argd['conditions'],
                         only_edition=argd['only_edition'],
                         request_type='book',
                         ln=argd['ln'])
 
         return page(title       = _("Interlibrary loan request for books"),
                     body        = body,
                     uid         = uid,
                     lastupdated = __lastupdated__,
                     req         = req,
                     language    = argd['ln'],
                     navmenuid   = "ill")
 
 
 
 class WebInterfaceHoldingsPages(WebInterfaceDirectory):
     """Defines the set of /holdings pages."""
 
     _exports = ['', 'display', 'request', 'send', 'ill_request_with_recid',
                 'ill_register_request_with_recid']
 
     def __init__(self, recid=-1):
         self.recid = recid
 
 
     def index(self, req, form):
         """
         Redirects to display function
         """
 
         return self.display(req, form)
 
     def display(self, req, form):
         """
         Show the tab 'holdings'.
         """
 
         argd = wash_urlargd(form, {'do': (str, "od"),
                                    'ds': (str, "all"),
                                    'nb': (int, 100),
                                    'p' : (int, 1),
                                    'voted': (int, -1),
                                    'reported': (int, -1),
                                    })
 
         _ = gettext_set_language(argd['ln'])
 
         record_exists_p = record_exists(self.recid)
         if record_exists_p != 1:
             if record_exists_p == -1:
                 msg = _("The record has been deleted.")
             else:
                 msg = _("Requested record does not seem to exist.")
             msg = '<span class="quicknote">' + msg + '</span>'
             title, description, keywords = \
                 websearch_templates.tmpl_record_page_header_content(req,
                                                                     self.recid,
                                                                     argd['ln'])
             return page(title = title,
                         show_title_p = False,
                         body = msg,
                         description = description,
                         keywords = keywords,
                         uid = getUid(req),
                         language = argd['ln'],
                         req = req,
                         navmenuid='search')
 
         body = perform_get_holdings_information(self.recid, req, argd['ln'])
 
         uid = getUid(req)
 
         user_info = collect_user_info(req)
         (auth_code, auth_msg) = check_user_can_view_record(user_info, self.recid)
         if auth_code and user_info['email'] == 'guest':
             cookie = mail_cookie_create_authorize_action(VIEWRESTRCOLL,
                                 {'collection': guess_primary_collection_of_a_record(self.recid)})
             target = '/youraccount/login' + \
                 make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \
                 CFG_SITE_SECURE_URL + user_info['uri']}, {})
             return redirect_to_url(req, target, norobot=True)
         elif auth_code:
             return page_not_authorized(req, "../", text=auth_msg)
 
 
         unordered_tabs = get_detailed_page_tabs(get_colID(\
                     guess_primary_collection_of_a_record(self.recid)),
                     self.recid, ln=argd['ln'])
         ordered_tabs_id = [(tab_id, values['order']) for (tab_id, values) in unordered_tabs.iteritems()]
         ordered_tabs_id.sort(lambda x, y: cmp(x[1], y[1]))
         link_ln = ''
         if argd['ln'] != CFG_SITE_LANG:
             link_ln = '?ln=%s' % argd['ln']
         tabs = [(unordered_tabs[tab_id]['label'], \
                  '%s/%s/%s/%s%s' % (CFG_SITE_SECURE_URL, CFG_SITE_RECORD, self.recid, tab_id, link_ln), \
                  tab_id in ['holdings'],
                  unordered_tabs[tab_id]['enabled']) \
                 for (tab_id, _order) in ordered_tabs_id
                 if unordered_tabs[tab_id]['visible'] == True]
         top = webstyle_templates.detailed_record_container_top(self.recid,
                                                                tabs,
                                                                argd['ln'])
         bottom = webstyle_templates.detailed_record_container_bottom(self.recid,
                                                                      tabs,
                                                                      argd['ln'])
 
         title = websearch_templates.tmpl_record_page_header_content(req, self.recid, argd['ln'])[0]
         navtrail = create_navtrail_links(cc=guess_primary_collection_of_a_record(self.recid), ln=argd['ln'])
         navtrail += ' &gt; <a class="navtrail" href="%s/%s/%s?ln=%s">'% (CFG_SITE_SECURE_URL, CFG_SITE_RECORD, self.recid, argd['ln'])
         navtrail += title
         navtrail += '</a>'
 
         return pageheaderonly(title=title,
                               navtrail=navtrail,
                               uid=uid,
                               verbose=1,
                               req=req,
                               metaheaderadd = "<link rel=\"stylesheet\" href=\"%s/img/jquery/jquery-ui.css\" type=\"text/css\" />" % CFG_SITE_SECURE_URL,
                               language=argd['ln'],
                               navmenuid='search',
                               navtrail_append_title_p=0) + \
                               websearch_templates.tmpl_search_pagestart(argd['ln']) + \
                               top + body + bottom + \
                               websearch_templates.tmpl_search_pageend(argd['ln']) + \
                               pagefooteronly(lastupdated=__lastupdated__, language=argd['ln'], req=req)
 
     # Return the same page wether we ask for /CFG_SITE_RECORD/123 or /CFG_SITE_RECORD/123/
     __call__ = index
 
 
     def request(self, req, form):
         """
         Show new hold request form.
         """
         argd = wash_urlargd(form, {'ln': (str, ""), 'barcode': (str, "")})
 
         _ = gettext_set_language(argd['ln'])
         uid = getUid(req)
 
         body = perform_new_request(recid=self.recid,
                                    barcode=argd['barcode'],
                                    ln=argd['ln'])
 
         uid = getUid(req)
         if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
             return page_not_authorized(req, "../holdings/request",
                                        navmenuid = 'yourbaskets')
 
         if isGuestUser(uid):
             if not CFG_WEBSESSION_DIFFERENTIATE_BETWEEN_GUESTS:
                 return redirect_to_url(req, "%s/youraccount/login%s" % (
                     CFG_SITE_SECURE_URL,
                         make_canonical_urlargd({
                     'referer' : "%s/%s/%s/holdings/request%s" % (
                         CFG_SITE_SECURE_URL,
                         CFG_SITE_RECORD,
                         self.recid,
                         make_canonical_urlargd(argd, {})),
                     "ln" : argd['ln']}, {})), norobot=True)
 
 
         user_info = collect_user_info(req)
         (auth_code, auth_msg) = check_user_can_view_record(user_info, self.recid)
         if auth_code and user_info['email'] == 'guest':
             cookie = mail_cookie_create_authorize_action(VIEWRESTRCOLL, {'collection' : guess_primary_collection_of_a_record(self.recid)})
             target = '/youraccount/login' + \
                      make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \
                 CFG_SITE_SECURE_URL + user_info['uri']}, {})
             return redirect_to_url(req, target, norobot=True)
         elif auth_code:
             return page_not_authorized(req, "../", \
                 text = auth_msg)
 
 
         unordered_tabs = get_detailed_page_tabs(get_colID(guess_primary_collection_of_a_record(self.recid)), self.recid, ln=argd['ln'])
         ordered_tabs_id = [(tab_id, values['order']) for (tab_id, values) in unordered_tabs.iteritems()]
         ordered_tabs_id.sort(lambda x, y: cmp(x[1], y[1]))
         link_ln = ''
         if argd['ln'] != CFG_SITE_LANG:
             link_ln = '?ln=%s' % argd['ln']
         tabs = [(unordered_tabs[tab_id]['label'], \
                  '%s/%s/%s/%s%s' % (CFG_SITE_SECURE_URL, CFG_SITE_RECORD, self.recid, tab_id, link_ln), \
                  tab_id in ['holdings'],
                  unordered_tabs[tab_id]['enabled']) \
                 for (tab_id, _order) in ordered_tabs_id
                 if unordered_tabs[tab_id]['visible'] == True]
         top = webstyle_templates.detailed_record_container_top(self.recid,
                                                                tabs,
                                                                argd['ln'])
         bottom = webstyle_templates.detailed_record_container_bottom(self.recid,
                                                                      tabs,
                                                                      argd['ln'])
 
         title = websearch_templates.tmpl_record_page_header_content(req, self.recid, argd['ln'])[0]
         navtrail = create_navtrail_links(cc=guess_primary_collection_of_a_record(self.recid), ln=argd['ln'])
         navtrail += ' &gt; <a class="navtrail" href="%s/%s/%s?ln=%s">'% (CFG_SITE_SECURE_URL, CFG_SITE_RECORD, self.recid, argd['ln'])
         navtrail += title
         navtrail += '</a>'
 
         return pageheaderonly(title=title,
                               navtrail=navtrail,
                               uid=uid,
                               verbose=1,
                               req=req,
                               metaheaderadd = "<link rel=\"stylesheet\" href=\"%s/img/jquery/jquery-ui.css\" type=\"text/css\" />" % CFG_SITE_SECURE_URL,
                               language=argd['ln'],
                               navmenuid='search',
                               navtrail_append_title_p=0) + \
                               websearch_templates.tmpl_search_pagestart(argd['ln']) + \
                               top + body + bottom + \
                               websearch_templates.tmpl_search_pageend(argd['ln']) + \
                               pagefooteronly(lastupdated=__lastupdated__, language=argd['ln'], req=req)
 
 
     def send(self, req, form):
         """
         Create a new hold request.
         """
         argd = wash_urlargd(form, {'period_from': (str, ""),
                                    'period_to': (str, ""),
                                    'barcode': (str, "")
                                    })
 
         uid = getUid(req)
 
         period_from = argd['period_from']
         period_to = argd['period_to']
         period_from = period_from.strip()
         period_to = period_to.strip()
         barcode = argd['barcode']
 
         body = perform_new_request_send(recid=self.recid,
                                         uid=uid,
                                         period_from=argd['period_from'],
                                         period_to=argd['period_to'],
                                         barcode=barcode)
 
         ln = CFG_SITE_LANG
         _ = gettext_set_language(ln)
 
         user_info = collect_user_info(req)
         (auth_code, auth_msg) = check_user_can_view_record(user_info, self.recid)
         if auth_code and user_info['email'] == 'guest':
             cookie = mail_cookie_create_authorize_action(VIEWRESTRCOLL, {'collection' : guess_primary_collection_of_a_record(self.recid)})
             target = '/youraccount/login' + \
                      make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \
                 CFG_SITE_SECURE_URL + user_info['uri']}, {})
             return redirect_to_url(req, target)
         elif auth_code:
             return page_not_authorized(req, "../", \
                 text = auth_msg)
 
         unordered_tabs = get_detailed_page_tabs(get_colID(guess_primary_collection_of_a_record(self.recid)), self.recid, ln=ln)
         ordered_tabs_id = [(tab_id, values['order']) for (tab_id, values) in unordered_tabs.iteritems()]
         ordered_tabs_id.sort(lambda x, y: cmp(x[1], y[1]))
         link_ln = ''
         if argd['ln'] != CFG_SITE_LANG:
             link_ln = '?ln=%s' % ln
         tabs = [(unordered_tabs[tab_id]['label'], \
                  '%s/%s/%s/%s%s' % (CFG_SITE_SECURE_URL, CFG_SITE_RECORD, self.recid, tab_id, link_ln), \
                  tab_id in ['holdings'],
                  unordered_tabs[tab_id]['enabled']) \
                 for (tab_id, _order) in ordered_tabs_id
                 if unordered_tabs[tab_id]['visible'] == True]
         top = webstyle_templates.detailed_record_container_top(self.recid,
                                                                tabs,
                                                                argd['ln'])
         bottom = webstyle_templates.detailed_record_container_bottom(self.recid,
                                                                      tabs,
                                                                      argd['ln'])
 
         title = websearch_templates.tmpl_record_page_header_content(req, self.recid, argd['ln'])[0]
         navtrail = create_navtrail_links(cc=guess_primary_collection_of_a_record(self.recid), ln=argd['ln'])
         navtrail += ' &gt; <a class="navtrail" href="%s/%s/%s?ln=%s">'% (CFG_SITE_SECURE_URL, CFG_SITE_RECORD, self.recid, argd['ln'])
         navtrail += title
         navtrail += '</a>'
 
         return pageheaderonly(title=title,
                               navtrail=navtrail,
                               uid=uid,
                               verbose=1,
                               req=req,
                               language=argd['ln'],
                               navmenuid='search',
                               navtrail_append_title_p=0) + \
                               websearch_templates.tmpl_search_pagestart(argd['ln']) + \
                               top + body + bottom + \
                               websearch_templates.tmpl_search_pageend(argd['ln']) + \
                               pagefooteronly(lastupdated=__lastupdated__,
                               language=argd['ln'], req=req)
 
 
     def ill_request_with_recid(self, req, form):
         """
         Show ILL request form.
         """
 
         argd = wash_urlargd(form, {'ln': (str, "")})
 
         _ = gettext_set_language(argd['ln'])
         uid = getUid(req)
 
         body = ill_request_with_recid(recid=self.recid,
                                       ln=argd['ln'])
 
         if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
             return page_not_authorized(req, "../holdings/ill_request_with_recid",
                                        navmenuid = 'yourbaskets')
 
         if isGuestUser(uid):
             if not CFG_WEBSESSION_DIFFERENTIATE_BETWEEN_GUESTS:
                 return redirect_to_url(req, "%s/youraccount/login%s" % (
                     CFG_SITE_SECURE_URL,
                         make_canonical_urlargd({
                     'referer' : "%s/%s/%s/holdings/ill_request_with_recid%s" % (
                         CFG_SITE_SECURE_URL,
                         CFG_SITE_RECORD,
                         self.recid,
                         make_canonical_urlargd(argd, {})),
                     "ln" : argd['ln']}, {})))
 
 
         user_info = collect_user_info(req)
         (auth_code, auth_msg) = check_user_can_view_record(user_info, self.recid)
         if auth_code and user_info['email'] == 'guest':
             cookie = mail_cookie_create_authorize_action(VIEWRESTRCOLL, {'collection' : guess_primary_collection_of_a_record(self.recid)})
             target = '/youraccount/login' + \
                      make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \
                 CFG_SITE_SECURE_URL + user_info['uri']}, {})
             return redirect_to_url(req, target)
         elif auth_code:
             return page_not_authorized(req, "../", \
                 text = auth_msg)
 
 
 
         unordered_tabs = get_detailed_page_tabs(get_colID(guess_primary_collection_of_a_record(self.recid)),
                                                     self.recid,
                                                     ln=argd['ln'])
         ordered_tabs_id = [(tab_id, values['order']) for (tab_id, values) in unordered_tabs.iteritems()]
         ordered_tabs_id.sort(lambda x, y: cmp(x[1], y[1]))
         link_ln = ''
         if argd['ln'] != CFG_SITE_LANG:
             link_ln = '?ln=%s' % argd['ln']
         tabs = [(unordered_tabs[tab_id]['label'], \
                  '%s/%s/%s/%s%s' % (CFG_SITE_SECURE_URL, CFG_SITE_RECORD, self.recid, tab_id, link_ln), \
                  tab_id in ['holdings'],
                  unordered_tabs[tab_id]['enabled']) \
                 for (tab_id, _order) in ordered_tabs_id
                 if unordered_tabs[tab_id]['visible'] == True]
         top = webstyle_templates.detailed_record_container_top(self.recid,
                                                                tabs,
                                                                argd['ln'])
         bottom = webstyle_templates.detailed_record_container_bottom(self.recid,
                                                                      tabs,
                                                                      argd['ln'])
 
         title = websearch_templates.tmpl_record_page_header_content(req, self.recid, argd['ln'])[0]
         navtrail = create_navtrail_links(cc=guess_primary_collection_of_a_record(self.recid), ln=argd['ln'])
         navtrail += ' &gt; <a class="navtrail" href="%s/%s/%s?ln=%s">'% (CFG_SITE_SECURE_URL, CFG_SITE_RECORD, self.recid, argd['ln'])
         navtrail += title
         navtrail += '</a>'
 
         return pageheaderonly(title=title,
                               navtrail=navtrail,
                               uid=uid,
                               verbose=1,
                               req=req,
                               metaheaderadd = "<link rel=\"stylesheet\" href=\"%s/img/jquery/jquery-ui.css\" type=\"text/css\" />" % CFG_SITE_SECURE_URL,
                               language=argd['ln'],
                               navmenuid='search',
                               navtrail_append_title_p=0) + \
                               websearch_templates.tmpl_search_pagestart(argd['ln']) + \
                               top + body + bottom + \
                               websearch_templates.tmpl_search_pageend(argd['ln']) + \
                               pagefooteronly(lastupdated=__lastupdated__, language=argd['ln'], req=req)
 
 
     def ill_register_request_with_recid(self, req, form):
         """
         Register ILL request.
         """
 
         argd = wash_urlargd(form, {'ln': (str, ""),
                                    'period_of_interest_from': (str, ""),
                                    'period_of_interest_to': (str, ""),
                                    'additional_comments': (str, ""),
                                    'conditions': (str, ""),
                                    'only_edition': (str, ""),
                                    })
 
         _ = gettext_set_language(argd['ln'])
         uid = getUid(req)
 
         body = ill_register_request_with_recid(recid=self.recid,
                                                uid=uid,
                                                period_of_interest_from =  argd['period_of_interest_from'],
                                                period_of_interest_to =  argd['period_of_interest_to'],
                                                additional_comments =  argd['additional_comments'],
                                                conditions = argd['conditions'],
                                                only_edition = argd['only_edition'],
                                                ln=argd['ln'])
 
         uid = getUid(req)
         if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
             return page_not_authorized(req, "../holdings/ill_request_with_recid",
                                        navmenuid = 'yourbaskets')
 
         if isGuestUser(uid):
             if not CFG_WEBSESSION_DIFFERENTIATE_BETWEEN_GUESTS:
                 return redirect_to_url(req, "%s/youraccount/login%s" % (
                     CFG_SITE_SECURE_URL,
                         make_canonical_urlargd({
                     'referer' : "%s/%s/%s/holdings/ill_request_with_recid%s" % (
                         CFG_SITE_SECURE_URL,
                         CFG_SITE_RECORD,
                         self.recid,
                         make_canonical_urlargd(argd, {})),
                     "ln" : argd['ln']}, {})))
 
 
         user_info = collect_user_info(req)
         (auth_code, auth_msg) = check_user_can_view_record(user_info, self.recid)
         if auth_code and user_info['email'] == 'guest':
             cookie = mail_cookie_create_authorize_action(VIEWRESTRCOLL, {'collection' : guess_primary_collection_of_a_record(self.recid)})
             target = '/youraccount/login' + \
                      make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \
                 CFG_SITE_SECURE_URL + user_info['uri']}, {})
             return redirect_to_url(req, target)
         elif auth_code:
             return page_not_authorized(req, "../", \
                 text = auth_msg)
 
 
 
         unordered_tabs = get_detailed_page_tabs(get_colID(guess_primary_collection_of_a_record(self.recid)),
                                                     self.recid,
                                                     ln=argd['ln'])
         ordered_tabs_id = [(tab_id, values['order']) for (tab_id, values) in unordered_tabs.iteritems()]
         ordered_tabs_id.sort(lambda x, y: cmp(x[1], y[1]))
         link_ln = ''
         if argd['ln'] != CFG_SITE_LANG:
             link_ln = '?ln=%s' % argd['ln']
         tabs = [(unordered_tabs[tab_id]['label'], \
                  '%s/%s/%s/%s%s' % (CFG_SITE_SECURE_URL, CFG_SITE_RECORD, self.recid, tab_id, link_ln), \
                  tab_id in ['holdings'],
                  unordered_tabs[tab_id]['enabled']) \
                 for (tab_id, _order) in ordered_tabs_id
                 if unordered_tabs[tab_id]['visible'] == True]
         top = webstyle_templates.detailed_record_container_top(self.recid,
                                                                tabs,
                                                                argd['ln'])
         bottom = webstyle_templates.detailed_record_container_bottom(self.recid,
                                                                      tabs,
                                                                      argd['ln'])
 
         title = websearch_templates.tmpl_record_page_header_content(req, self.recid, argd['ln'])[0]
         navtrail = create_navtrail_links(cc=guess_primary_collection_of_a_record(self.recid), ln=argd['ln'])
         navtrail += ' &gt; <a class="navtrail" href="%s/%s/%s?ln=%s">'% (CFG_SITE_SECURE_URL, CFG_SITE_RECORD, self.recid, argd['ln'])
         navtrail += title
         navtrail += '</a>'
 
         return pageheaderonly(title=title,
                               navtrail=navtrail,
                               uid=uid,
                               verbose=1,
                               req=req,
                               language=argd['ln'],
                               navmenuid='search',
                               navtrail_append_title_p=0) + \
                               websearch_templates.tmpl_search_pagestart(argd['ln']) + \
                               top + body + bottom + \
                               websearch_templates.tmpl_search_pageend(argd['ln']) + \
                               pagefooteronly(lastupdated=__lastupdated__, language=argd['ln'], req=req)
diff --git a/modules/bibcirculation/lib/bibcirculationadmin_webinterface.py b/modules/bibcirculation/lib/bibcirculationadmin_webinterface.py
index dac87dffd..0f7628c9d 100644
--- a/modules/bibcirculation/lib/bibcirculationadmin_webinterface.py
+++ b/modules/bibcirculation/lib/bibcirculationadmin_webinterface.py
@@ -1,2148 +1,2148 @@
 ## This file is part of Invenio.
 ## Copyright (C) 2008, 2009, 2010, 2011 CERN.
 ##
 ## Invenio is free software; you can redistribute it and/or
 ## modify it under the terms of the GNU General Public License as
 ## published by the Free Software Foundation; either version 2 of the
 ## License, or (at your option) any later version.
 ##
 ## Invenio is distributed in the hope that it will be useful, but
 ## WITHOUT ANY WARRANTY; without even the implied warranty of
 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 ## General Public License for more details.
 ##
 ## You should have received a copy of the GNU General Public License
 ## along with Invenio; if not, write to the Free Software Foundation, Inc.,
 ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 
 """Invenio BibCirculation Administrator (URLs) Interface."""
 
 __revision__ = ""
 
 import invenio.bibcirculationadminlib as bal
 from invenio.config import CFG_SITE_URL
 from invenio.urlutils import redirect_to_url
 from invenio.config import CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF
 
 from invenio.webinterface_handler import wash_urlargd, WebInterfaceDirectory
 
 class WebInterfaceBibCirculationAdminPages(WebInterfaceDirectory):
     """Defines the set of /admin2/bibcirculation pages."""
 
     _exports = ['', 'index', 'borrower_search', 'item_search', 'borrower_notification',
         'get_pending_requests', 'item_search_result', 'loan_return', 'loan_on_desk_step1',
         'loan_on_desk_step2', 'loan_on_desk_step3', 'loan_on_desk_step4', 'loan_on_desk_confirm',
         'register_new_loan', 'loan_return_confirm', 'get_next_waiting_loan_request',
         'make_new_loan_from_request', 'all_requests', 'get_item_req_historical_overview',
         'get_item_loans_historical_overview', 'all_loans',
         'bor_loans_historical_overview', 'bor_requests_historical_overview',
         'get_item_requests_details', 'get_item_loans_details', 'get_borrower_details',
         'get_item_details', 'get_library_details', 'get_borrower_requests_details',
         'get_borrower_loans_details', 'borrower_search_result', 'associate_barcode',
         'get_borrower_notes', 'get_loans_notes', 'get_item_loans_notes', 'new_item',
         'add_new_borrower_step1', 'add_new_borrower_step2', 'add_new_borrower_step3',
         'update_borrower_info_step1', 'update_borrower_info_step2', 'add_new_library_step1',
         'add_new_library_step2', 'add_new_library_step3', 'update_library_info_step1',
         'update_library_info_step2', 'update_library_info_step3', 'update_library_info_step4',
         'update_library_info_step5', 'new_book_step1', 'new_book_step2', 'add_new_copy_step1',
         'add_new_copy_step2', 'add_new_copy_step3', 'add_new_copy_step4', 'add_new_copy_step5',
         'update_item_info_step1', 'update_item_info_step2', 'update_item_info_step3',
         'update_item_info_step4', 'update_item_info_step5', 'update_item_info_step6',
         'search_library_step1', 'search_library_step2', 'get_library_notes',
         'change_due_date_step1', 'change_due_date_step2', 'claim_book_return',
         'all_expired_loans', 'get_waiting_requests', 'create_new_loan_step1',
         'create_new_loan_step2', 'create_new_request_step1', 'create_new_request_step2',
         'create_new_request_step3', 'create_new_request_step4', 'place_new_request_step1',
         'place_new_request_step2', 'place_new_request_step3', 'place_new_loan_step1',
         'place_new_loan_step2', 'place_new_loan_step3', 'order_new_copy_step1',
         'ordered_books', 'get_purchase_notes',
         'register_ill_request_step0', 'register_ill_request_step1', 'register_ill_request_step2',
         'list_ill_request', 'list_acquisition',
         'ill_request_details_step1', 'ill_request_details_step2',
         'ill_request_details_step3', 'ordered_books_details_step1',
         'ordered_books_details_step2', 'ordered_books_details_step3',
         'add_new_vendor_step1', 'add_new_vendor_step2', 'add_new_vendor_step3',
         'update_vendor_info_step1', 'update_vendor_info_step2',
         'update_vendor_info_step3', 'update_vendor_info_step4',
         'update_vendor_info_step5', 'search_vendor_step1',
         'search_vendor_step2', 'get_vendor_details', 'get_vendor_notes',
         'register_ill_request_with_no_recid_step1',
         'register_ill_request_with_no_recid_step2',
         'register_ill_request_with_no_recid_step3',
         'register_ill_request_with_no_recid_step4',
         'get_borrower_ill_details', 'get_ill_library_notes',
         'get_expired_loans_with_requests', 'register_ill_book_request',
         'register_ill_book_request_result',
         'register_ill_book_request_from_borrower_page',
         'register_ill_book_request_from_borrower_page_result',
         'register_ill_request_from_borrower_page_step1',
         'register_ill_request_from_borrower_page_step2',
         'register_ill_article_request_step1',
         'register_ill_article_request_step2',
         'register_ill_article_request_step3', 'ill_search', 'ill_search_result',
         'bor_ill_historical_overview', 'delete_copy_step1', 'delete_copy_step2',
         'merge_libraries_step1', 'merge_libraries_step2',
         'merge_libraries_step3',
         'register_purchase_request_step1', 'register_purchase_request_step2',
         'register_purchase_request_step3',
         'acq_details_step1', 'acq_details_step2']
 
     def index(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation"""
         argd = wash_urlargd(form, {'ln': (str, "en")})
         ln = argd['ln']
         return bal.index(req, ln)
 
 
     def borrower_search(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/borrowers_search"""
         argd = wash_urlargd(form, {'empty_barcode': (str, None),
                                    'redirect_to_new_request': (str, "no"),
                                     'ln': (str, "en")})
         empty_barcode = argd['empty_barcode']
         redirect_to_new_request = argd['redirect_to_new_request']
         ln = argd['ln']
 
         if redirect_to_new_request == 'yes':
             redirect_to_new_request = True
         else:
             redirect_to_new_request = False
 
         return bal.borrower_search(req, empty_barcode,
                                    redirect_to_new_request=redirect_to_new_request, ln=ln)
 
 
     def item_search(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/holdings_search"""
         argd = wash_urlargd(form, {'ln': (str, "en")})
         ln = argd['ln']
         return bal.item_search(req, [], ln)
 
     def item_search_result(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/item_search_result"""
         argd = wash_urlargd(form, {'p': (str, ''), 'f': (str, ''),
                                    'ln': (str, "en")})
         p  = argd['p']
         f  = argd['f']
         ln = argd['ln']
 
         if p is not None:
             p = p.strip()
 
         return bal.item_search_result(req, p, f, ln)
 
     def borrower_notification(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/borrower_notification"""
         argd = wash_urlargd(form, {'borrower_id': (str, None), 'borrower_email': (str, None),
             'template': (str, None), 'message': (str, None), 'load_msg_template': (str, None),
             'subject': (str, None), 'send_message': (str, None), 'ln': (str, "en")})
 
         borrower_id = argd['borrower_id']
         borrower_email = argd['borrower_email']
         template = argd['template']
         message = argd['message']
         load_msg_template = argd['load_msg_template']
         subject = argd['subject']
         send_message = argd['send_message']
         ln = argd['ln']
 
         if borrower_email is not None:
             borrower_email = borrower_email.strip()
 
         return bal.borrower_notification(req, borrower_id, borrower_email, template,
                                          message, load_msg_template,
                                          subject, send_message, ln)
 
 
     def get_pending_requests(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/get_pending_requests"""
         argd = wash_urlargd(form, {'request_id': (str, None), 'print_data': (str, None),
                                    'ln': (str, "en")})
         request_id = argd['request_id']
         print_data = argd['print_data']
         ln = argd['ln']
         return bal.get_pending_requests(req, request_id, print_data, ln)
 
 
 
     def delete_copy_step1(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/delete_copy_step1"""
         argd = wash_urlargd(form, {'barcode': (str, ''), 'ln': (str, "en")})
 
         barcode = argd['barcode']
         ln = argd['ln']
 
         return bal.delete_copy_step1(req, barcode, ln)
 
     def delete_copy_step2(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/delete_copy_step2"""
         argd = wash_urlargd(form, {'barcode': (str, ''), 'ln': (str, "en")})
 
         barcode = argd['barcode']
         ln = argd['ln']
 
         return bal.delete_copy_step2(req, barcode, ln)
 
     def loan_return(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/loan_return"""
         argd = wash_urlargd(form, {'ln': (str, "en")})
         ln = argd['ln']
         return bal.loan_return(req, ln)
 
 
     def loan_on_desk_step1(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/loan_on_desk_step1"""
         argd = wash_urlargd(form, {'key': (str, None), 'string': (str, None), 'ln': (str, "en")})
         key = argd['key']
         string = argd['string']
         ln = argd['ln']
 
         if string is not None:
             string = string.strip()
 
         return bal.loan_on_desk_step1(req, key, string, ln)
 
 
     def loan_on_desk_step2(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/loan_on_desk_step2"""
         argd = wash_urlargd(form, {'user_id': (int, None), 'ln': (str, "en")})
         user_id = argd['user_id']
         ln = argd['ln']
 
         #user_info = user_info.split(',')
         #user_info = json.load(user_info)
 
 
         return bal.loan_on_desk_step2(req, user_id, ln)
 
 
     def loan_on_desk_step3(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/loan_on_desk_step4"""
         argd = wash_urlargd(form, {'user_id': (int, None), 'barcode': (str, None),
                                     'ln': (str, "en")})
         user_id = argd['user_id']
         list_of_barcodes = argd['barcode']
         ln = argd['ln']
 
         if list_of_barcodes is not None:
             list_of_barcodes = list_of_barcodes.split()
         else:
             list_of_barcodes = []
 
         return bal.loan_on_desk_step3(req, user_id, list_of_barcodes, ln)
 
 
     def loan_on_desk_step4(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/loan_on_desk_step5"""
         argd = wash_urlargd(form, {'list_of_barcodes': (str, None), 'user_id': (int, None),
                         'datepickerhidden': (str, None), 'note': (str, None), 'ln': (str, "en")})
         list_of_barcodes = argd['list_of_barcodes']
         user_id = argd['user_id']
         due_date = argd['datepickerhidden']
         note = argd['note']
         ln = argd['ln']
 
         list_of_barcodes = list_of_barcodes.strip('[]')
         list_of_barcodes = list_of_barcodes.split(',')
 
         for i in range(len(list_of_barcodes)):
             list_of_barcodes[i] = list_of_barcodes[i].strip('\' ')
 
         due_date = due_date.split(',')
 
 
         return bal.loan_on_desk_step4(req, list_of_barcodes, user_id, due_date, note, ln)
 
 
     def loan_on_desk_confirm(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/loan_on_desk_confirm"""
         argd = wash_urlargd(form, {'barcode': (str, None), 'borrower_id': (str, None),
                                     'ln': (str, "en")})
         barcode = argd['barcode']
         borrower_id = argd['borrower_id']
         ln = argd['ln']
         return bal.loan_on_desk_confirm(req, barcode, borrower_id, ln)
 
 
     def register_new_loan(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/register_new_loan"""
         argd = wash_urlargd(form, {'barcode': (str, None), 'borrower_id': (str, None),
                                    'request_id': (str, None), 'new_note': (str, None),
                                    'print_data': (str, None), 'ln': (str, "en")})
         barcode     = argd['barcode']
         borrower_id = argd['borrower_id']
         request_id  = argd['request_id']
         new_note    = argd['new_note']
         print_data  = argd['print_data']
         ln          = argd['ln']
 
         if barcode is not None:
             barcode = barcode.strip()
 
         return bal.register_new_loan(req, barcode, borrower_id, request_id,
                                      new_note, print_data, ln)
 
 
     def loan_return_confirm(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/loan_return_confirm"""
         argd = wash_urlargd(form, {'barcode': (str, None), 'ln': (str, "en")})
         barcode = argd['barcode']
         ln = argd['ln']
         if barcode is not None:
             barcode = barcode.strip()
 
         return bal.loan_return_confirm(req, barcode, ln)
 
 
     def get_next_waiting_loan_request(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/get_next_waiting_loan_request"""
         argd = wash_urlargd(form, {'recid': (str, None), 'barcode': (str, None),
                                     'check_id': (str, None), 'ln': (str, "en")})
         recid    = argd['recid']
         barcode  = argd['barcode']
         check_id = argd['check_id']
         ln       = argd['ln']
         return bal.get_next_waiting_loan_request(req, recid, barcode, check_id, ln)
 
 
     def make_new_loan_from_request(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/make_new_loan_from_request"""
         argd = wash_urlargd(form, {'check_id': (str, None), 'barcode': (str, None),
                                     'ln': (str, "en")})
         check_id = argd['check_id']
         barcode  = argd['barcode']
         ln       = argd['ln']
 
         return bal.make_new_loan_from_request(req, check_id, barcode, ln)
 
 
     def all_requests(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/all_requests"""
         argd = wash_urlargd(form, {'request_id': (str, None), 'ln': (str, "en")})
         request_id = argd['request_id']
         ln = argd['ln']
         return bal.all_requests(req, request_id, ln)
 
 
     def get_item_req_historical_overview(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/get_item_req_historical_overview"""
         argd = wash_urlargd(form, {'recid': (str, None), 'ln': (str, "en")})
         recid = argd['recid']
         ln = argd['ln']
         return bal.get_item_req_historical_overview(req, recid, ln)
 
 
     def get_item_loans_historical_overview(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/get_item_loans_historical_overview"""
         argd = wash_urlargd(form, {'recid': (str, None), 'ln': (str, "en")})
         recid = argd['recid']
         ln = argd['ln']
         return bal.get_item_loans_historical_overview(req, recid, ln)
 
 
     #def all_loans_test(self, req, form):
     #    """http://cdsweb.cern.ch/admin2/bibcirculation/all_loans"""
     #    argd = wash_urlargd(form, {'ln': (str, "en")})
     #    ln = argd['ln']
     #    return bal.all_loans_test(req, ln)
 
 
     def all_loans(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/all_loans"""
         argd = wash_urlargd(form, {'msg': (str, None), 'ln': (str, "en")})
         msg = argd['msg']
         ln = argd['ln']
 
         return bal.all_loans(req, msg=msg, ln=ln)
 
 
     def bor_loans_historical_overview(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/bor_loans_historical_overview"""
         argd = wash_urlargd(form, {'borrower_id': (str, None), 'ln': (str, "en")})
         borrower_id = argd['borrower_id']
         ln = argd['ln']
         return bal.bor_loans_historical_overview(req, borrower_id, ln)
 
 
     def bor_requests_historical_overview(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/bor_requests_historical_overview"""
         argd = wash_urlargd(form, {'borrower_id': (str, None), 'ln': (str, "en")})
         borrower_id = argd['borrower_id']
         ln = argd['ln']
         return bal.bor_requests_historical_overview(req, borrower_id, ln)
 
 
     def get_item_requests_details(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/borrowers_search"""
         argd = wash_urlargd(form, {'recid': (str, None), 'request_id': (str, None),
                                     'ln': (str, "en")})
         recid = argd['recid']
         request_id = argd['request_id']
         ln = argd['ln']
         return bal.get_item_requests_details(req, recid, request_id, ln)
 
 
     def get_item_loans_details(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/borrowers_search"""
         argd = wash_urlargd(form, {'recid': (str, None), 'barcode': (str, None),
                             'loan_id': (str, None), 'force': (str, None), 'ln': (str, "en")})
         recid = argd['recid']
         barcode = argd['barcode']
         loan_id = argd['loan_id']
         force = argd['force']
         ln = argd['ln']
         return bal.get_item_loans_details(req, recid, barcode, loan_id, force, ln)
 
 
     def get_borrower_details(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/borrowers_search"""
         argd = wash_urlargd(form, {'borrower_id': (str, None), 'update': (str, 'False'),
                                    'ln': (str, "en")})
         borrower_id = argd['borrower_id']
         update = argd['update']
         ln = argd['ln']
 
         if update == 'True':
             update = True
         else:
             update = False
 
         return bal.get_borrower_details(req, borrower_id, update, ln)
 
 
     def get_item_details(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/"""
         argd = wash_urlargd(form, {'recid': (str, None), 'ln': (str, "en")})
         recid = argd['recid']
         ln = argd['ln']
 
         try:
             recid = int(recid)
         except:
             recid = None
 
         return bal.get_item_details(req, recid, ln)
 
 
     def get_library_details(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/get_library_details"""
         argd = wash_urlargd(form, {'library_id': (str, None), 'ln': (str, "en")})
         library_id = argd['library_id']
         ln = argd['ln']
         return bal.get_library_details(req, library_id, ln)
 
 
     def get_borrower_requests_details(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/get_borrower_requests_details"""
         argd = wash_urlargd(form, {'borrower_id': (str, None), 'request_id': (str, None),
                                     'ln': (str, "en")})
         borrower_id = argd['borrower_id']
         request_id = argd['request_id']
         ln = argd['ln']
         return bal.get_borrower_requests_details(req, borrower_id, request_id, ln)
 
 
     def get_borrower_loans_details(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/get_borrower_loans_details"""
         argd = wash_urlargd(form, {'recid': (str, None), 'barcode': (str, None),
                                     'borrower_id': (str, None), 'renewall': (str, None),
                                     'force': (str, None), 'loan_id': (str, None),
                                     'ln': (str, "en")})
         recid = argd['recid']
         barcode = argd['barcode']
         borrower_id = argd['borrower_id']
         renewall = argd['renewall']
         force = argd['force']
         loan_id = argd['loan_id']
         ln = argd['ln']
         return bal.get_borrower_loans_details(req, recid, barcode, borrower_id,
                                               renewall, force, loan_id, ln)
 
 
     def borrower_search_result(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/borrower_search_result"""
         argd = wash_urlargd(form, {'column': (str, "name"), 'string': (str, ''),
                                    'redirect_to_new_request': (str, "no"), 'ln': (str, "en")})
         column = argd['column']
         string = argd['string']
         redirect_to_new_request = argd['redirect_to_new_request']
         ln = argd['ln']
 
         string = string.strip()
         if redirect_to_new_request == 'yes':
             redirect_to_new_request = True
         else:
             redirect_to_new_request = False
 
         return bal.borrower_search_result(req, column, string,
                                 redirect_to_new_request=redirect_to_new_request,
                                 ln=ln)
 
 
     def associate_barcode(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/associate_barcode"""
         argd = wash_urlargd(form, {'request_id': (str, None), 'recid': (str, None),
                                     'borrower_id': (str, None), 'ln': (str, "en")})
         request_id = argd['request_id']
         recid = argd['recid']
         borrower_id = argd['borrower_id']
         ln = argd['ln']
         return bal.associate_barcode(req, request_id, recid, borrower_id, ln)
 
 
     def get_borrower_notes(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/get_borrower_notes"""
         argd = wash_urlargd(form, {'borrower_id': (str, None), 'delete_key': (str, None),
                                     'library_notes': (str, None), 'ln': (str, "en")})
         borrower_id = argd['borrower_id']
         delete_key = argd['delete_key']
         library_notes = argd['library_notes']
         ln = argd['ln']
         return bal.get_borrower_notes(req, borrower_id, delete_key,
                                       library_notes, ln)
 
 
     def get_loans_notes(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/get_loans_notes"""
         argd = wash_urlargd(form, {'loan_id': (str, None), 'recid': (str, None),
                                     'delete_key': (str, None), 'library_notes': (str, None),
                                     'back': (str, ""), 'ln': (str, "en")})
         loan_id = argd['loan_id']
         #recid = argd['recid']
         delete_key = argd['delete_key']
         library_notes = argd['library_notes']
         back = argd['back']
         ln = argd['ln']
         return bal.get_loans_notes(req, loan_id, delete_key,
                                    library_notes, back, ln)
 
 
     def get_item_loans_notes(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/get_item_loans_notes"""
         argd = wash_urlargd(form, {'loan_id': (str, None), 'add_notes': (str, None),
                                     'new_note': (str, None), 'ln': (str, "en")})
         loan_id = argd['loan_id']
         #recid = argd['recid']
         add_notes = argd['add_notes']
         new_note = argd['new_note']
         ln = argd['ln']
         return bal.get_item_loans_notes(req, loan_id, add_notes,
                                         new_note, ln)
 
 
     def new_item(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/new_item"""
         argd = wash_urlargd(form, {'isbn': (str, None), 'ln': (str, "en")})
         isbn = argd['isbn']
         ln = argd['ln']
         return bal.new_item(req, isbn, ln)
 
 
     def add_new_borrower_step1(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/add_new_borrower_step1"""
         argd = wash_urlargd(form, {'ln': (str, "en")})
         ln = argd['ln']
         return bal.add_new_borrower_step1(req, ln)
 
 
     def add_new_borrower_step2(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/add_new_borrower_step2"""
         argd = wash_urlargd(form, {'name': (str, ''), 'email': (str, ''),
             'phone': (str, ''), 'address': (str, ''), 'mailbox': (str, ''),
             'notes': (str, ''), 'ln': (str, "en")})
         name = argd['name']
         email = argd['email']
         phone = argd['phone']
         address = argd['address']
         mailbox = argd['mailbox']
         notes = argd['notes']
         ln = argd['ln']
 
         name = name.strip()
         email = email.strip()
         phone = phone.strip()
         address = address.strip()
         mailbox = mailbox.strip()
         notes = notes.strip()
 
         return bal.add_new_borrower_step2(req, name, email, phone, address,
                                           mailbox, notes, ln)
 
     def update_borrower_info_step1(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/update_borrower_info_step1"""
         argd = wash_urlargd(form, {'borrower_id': (str, None), 'ln': (str, "en")})
         borrower_id = argd['borrower_id']
         ln = argd['ln']
         return bal.update_borrower_info_step1(req, borrower_id, ln)
 
 
     def update_borrower_info_step2(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/update_borrower_info_step2"""
         argd = wash_urlargd(form, {'borrower_id': (int, None), 'name': (str, ''),
             'email': (str, ''), 'phone': (str, ''), 'address': (str, ''),
             'mailbox': (str, ''), 'ln': (str, "en")})
 
         name = argd['name']
         email = argd['email']
         phone = argd['phone']
         address = argd['address']
         mailbox = argd['mailbox']
         borrower_id = argd['borrower_id']
         ln = argd['ln']
 
         name = name.strip()
         email = email.strip()
         phone = phone.strip()
         address = address.strip()
         mailbox = mailbox.strip()
 
         return bal.update_borrower_info_step2(req, borrower_id, name, email, phone, address,
                                               mailbox, ln)
 
     def add_new_library_step1(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/add_new_library_step1"""
         argd = wash_urlargd(form, {'ln': (str, "en")})
         ln = argd['ln']
         return bal.add_new_library_step1(req, ln)
 
 
     def add_new_library_step2(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/add_new_library_step2"""
         argd = wash_urlargd(form, {'name': (str, ''), 'email': (str, ''),
             'phone': (str, ''), 'address': (str, ''), 'type': (str, ''),
             'notes': (str, None), 'ln': (str, "en")})
         name = argd['name']
         email = argd['email']
         phone = argd['phone']
         address = argd['address']
         library_type = argd['type']
         notes = argd['notes']
         ln = argd['ln']
 
         name = name.strip()
         email = email.strip()
         phone = phone.strip()
         address = address.strip()
         library_type = library_type.strip()
 
         return bal.add_new_library_step2(req, name, email, phone, address,
                                          library_type, notes, ln)
 
 
     def add_new_library_step3(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/add_new_library_step3"""
         argd = wash_urlargd(form, {'name': (str, None), 'email': (str, None),
             'phone': (str, None), 'address': (str, None), 'type': (str, None),
             'notes': (str, None), 'ln': (str, "en")})
         name = argd['name']
         email = argd['email']
         phone = argd['phone']
         address = argd['address']
         library_type = argd['type']
         notes = argd['notes']
         ln = argd['ln']
 
         return bal.add_new_library_step3(req,name, email, phone, address, library_type, notes, ln)
 
 
     def update_library_info_step1(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/update_library_info_step1"""
         argd = wash_urlargd(form, {'ln': (str, "en")})
         ln = argd['ln']
         return bal.update_library_info_step1(req, ln)
 
 
     def update_library_info_step2(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/update_library_info_step2"""
         argd = wash_urlargd(form, {'column': (str, None), 'string': (str, None),
                                     'ln': (str, "en")})
         column = argd['column']
         string = argd['string']
         ln = argd['ln']
 
         if string is not None:
             string = string.strip()
 
         return bal.update_library_info_step2(req, column, string, ln)
 
 
     def update_library_info_step3(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/update_library_info_step3"""
         argd = wash_urlargd(form, {'library_id': (str, None), 'ln': (str, "en")})
         library_id = argd['library_id']
         ln = argd['ln']
         return bal.update_library_info_step3(req, library_id, ln)
 
 
     def update_library_info_step4(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/update_library_info_step4"""
         argd = wash_urlargd(form, {'name': (str, ''), 'email': (str, ''),
             'phone': (str, ''), 'address': (str, ''), 'library_id': (str, ''),
             'lib_type': (str, ''), 'ln': (str, "en")})
 
         name = argd['name']
         email = argd['email']
         phone = argd['phone']
         address = argd['address']
         lib_type = argd['lib_type']
         library_id = argd['library_id']
         ln = argd['ln']
 
         name = name.strip()
         email = email.strip()
         phone = phone.strip()
         address = address.strip()
         lib_type = lib_type.strip()
 
         return bal.update_library_info_step4(req, name, email, phone, address, lib_type,
                                              library_id, ln)
 
 
     def update_library_info_step5(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/update_library_info_step5"""
         argd = wash_urlargd(form, {'name': (str, None), 'email': (str, None),
                         'phone': (str, None), 'address': (str, None), 'library_id': (str, None),
                         'lib_type': (str, None), 'ln': (str, "en")})
 
         name = argd['name']
         email = argd['email']
         phone = argd['phone']
         address = argd['address']
         lib_type = argd['lib_type']
         library_id = argd['library_id']
         ln = argd['ln']
 
         return bal.update_library_info_step5(req, name, email, phone, address, lib_type,
                                              library_id, ln)
 
 
     def new_book_step1(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/new_book_step1"""
         argd = wash_urlargd(form, {'ln': (str, "en")})
         ln = argd['ln']
         return bal.new_book_step1(req, ln)
 
 
     def new_book_step2(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/new_book_step2"""
         argd = wash_urlargd(form, {'ln': (str, "en")})
         ln = argd['ln']
         return bal.new_book_step2(req, ln)
 
 
     def add_new_copy_step1(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/add_new_copy_step1"""
         argd = wash_urlargd(form, {'ln': (str, "en")})
         ln = argd['ln']
         return bal.add_new_copy_step1(req, ln)
 
 
     def add_new_copy_step2(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/add_new_copy_step2"""
         argd = wash_urlargd(form, {'p': (str, None), 'f': (str, None), 'ln': (str, "en")})
         p  = argd['p']
         f  = argd['f']
         ln = argd['ln']
 
         if p is not None:
             p = p.strip()
 
         return bal.add_new_copy_step2(req, p, f, ln)
 
 
     def add_new_copy_step3(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/add_new_copy_step3"""
         argd = wash_urlargd(form, {'recid': (str, None), 'barcode': (str, None),
                                    'ln': (str, "en")})
         recid   = argd['recid']
         barcode = argd['barcode']
         ln      = argd['ln']
         return bal.add_new_copy_step3(req, recid, barcode, ln)
 
 
     def add_new_copy_step4(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/add_new_copy_step4"""
         argd = wash_urlargd(form, {'barcode': (str, None), 'library': (str, ''),
             'location': (str, ''), 'collection': (str, ''), 'description': (str, ''),
             'loan_period': (str, ''), 'status': (str, ''),
             'expected_arrival_date': (str, ''), 'recid': (str, None), 'ln': (str, "en")})
 
         barcode     = argd['barcode']
         library     = argd['library']
         location    = argd['location']
         collection  = argd['collection']
         description = argd['description']
         loan_period = argd['loan_period']
         status      = argd['status']
         expected_arrival_date = argd['expected_arrival_date']
         recid       = argd['recid']
         ln          = argd['ln']
 
         if barcode is not None:
             barcode = barcode.strip()
 
         library     = library.strip()
         location    = location.strip()
         collection  = collection.strip()
         description = description.strip()
 
         loan_period = loan_period.strip()
         status      = status.strip()
         expected_arrival_date = expected_arrival_date.strip()
 
         if recid is not None:
             recid = recid.strip()
 
         return bal.add_new_copy_step4(req, barcode, library, location, collection,
                                       description, loan_period, status,
                                       expected_arrival_date, recid, ln)
 
 
     def add_new_copy_step5(self, req, form):
 
         argd = wash_urlargd(form, {'barcode': (str, None), 'library': (str, None),
             'location': (str, None), 'collection': (str, None), 'description': (str, None),
             'loan_period': (str, None), 'status': (str, None),
             'expected_arrival_date': (str, None), 'recid': (str, None), 'ln': (str, "en")})
 
         barcode = argd['barcode']
         library = argd['library']
         location = argd['location']
         collection = argd['collection']
         description = argd['description']
         loan_period = argd['loan_period']
         status = argd['status']
         expected_arrival_date = argd['expected_arrival_date']
         recid = argd['recid']
         ln = argd['ln']
         return bal.add_new_copy_step5(req, barcode, library, location, collection,
                             description, loan_period, status, expected_arrival_date, recid, ln)
 
 
     def update_item_info_step1(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/update_item_info_step1"""
         argd = wash_urlargd(form, {'ln': (str, "en")})
         ln = argd['ln']
         return bal.update_item_info_step1(req, ln)
 
 
     def update_item_info_step2(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/update_item_info_step2"""
         argd = wash_urlargd(form, {'p': (str, '()'), 'f': (str, '()'), 'ln': (str, "en")})
         p = argd['p']
         f = argd['f']
         ln = argd['ln']
 
         p = p.strip()
 
         return bal.update_item_info_step2(req, p, f, ln)
 
 
     def update_item_info_step3(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/update_item_info_step3"""
         argd = wash_urlargd(form, {'recid': (int, 0), 'ln': (str, "en")})
         recid = argd['recid']
         ln = argd['ln']
         return bal.update_item_info_step3(req, recid, ln)
 
 
     def update_item_info_step4(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/update_item_info_step4"""
         argd = wash_urlargd(form, {'barcode': (str, '()'), 'ln': (str, "en")})
         barcode = argd['barcode']
         ln = argd['ln']
         return bal.update_item_info_step4(req, barcode, ln)
 
 
     def update_item_info_step5(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/update_item_info_step5"""
         argd = wash_urlargd(form, {'barcode': (str, ''), 'old_barcode': (str, ''),
             'library': (int, 0), 'location': (str, 'Unknown'), 'collection': (str, 'Unknown'),
             'description': (str, ''), 'loan_period': (str, '4 weeks'),
             'status': (str, CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF), 'expected_arrival_date': (str, ''),
             'recid': (int, 0), 'ln': (str, "en")})
 
         barcode = argd['barcode']
         old_barcode = argd['old_barcode']
         library = argd['library']
         location = argd['location']
         collection = argd['collection']
         description = argd['description']
         loan_period = argd['loan_period']
         status = argd['status']
         expected_arrival_date = argd['expected_arrival_date']
         recid = argd['recid']
         ln = argd['ln']
 
         barcode = barcode.strip()
         old_barcode = old_barcode.strip()
         location = location.strip()
         collection = collection.strip()
         description = description.strip()
         loan_period = loan_period.strip()
         status = status.strip()
         expected_arrival_date = expected_arrival_date.strip()
 
         return bal.update_item_info_step5(req, barcode, old_barcode, library, location,
                                           collection, description, loan_period,
                                           status, expected_arrival_date, recid, ln)
 
 
     def update_item_info_step6(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/update_item_info_step6"""
         argd = wash_urlargd(form, {'barcode': (str, '-'), 'old_barcode': (str, '-'),
             'library_id': (int, 0), 'location': (str, 'Unknown'), 'collection': (str, 'Unknown'),
             'description': (str, ''), 'loan_period': (str, '4 weeks'),
             'status': (str, CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF), 'expected_arrival_date': (str, ''),
             'recid': (int, 0), 'ln': (str, "en")})
 
         barcode = argd['barcode']
         old_barcode = argd['old_barcode']
         library_id = argd['library_id']
         location = argd['location']
         collection = argd['collection']
         description = argd['description']
         loan_period = argd['loan_period']
         status = argd['status']
         expected_arrival_date = argd['expected_arrival_date']
         recid = argd['recid']
 
         ln = argd['ln']
 
         tup_infos = (barcode, old_barcode, library_id, location, collection,
                     description, loan_period, status, expected_arrival_date, recid)
 
         return bal.update_item_info_step6(req, tup_infos, ln)
 
 
     def search_library_step1(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/search_library_step1"""
         argd = wash_urlargd(form, {'ln': (str, "en")})
         ln = argd['ln']
         return bal.search_library_step1(req=req, ln=ln)
 
 
     def search_library_step2(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/search_library_step2"""
         argd = wash_urlargd(form, {'column': (str, ''), 'string': (str, ''), 'ln': (str, "en")})
         column = argd['column']
         string = argd['string']
         ln = argd['ln']
 
         string = string.strip()
 
         return bal.search_library_step2(req, column, string, ln)
 
 
     def get_library_notes(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/get_library_notes"""
         argd = wash_urlargd(form, {'library_id': (str, None), 'delete_key': (str, None),
                                     'library_notes': (str, None), 'ln': (str, "en")})
         library_id = argd['library_id']
         delete_key = argd['delete_key']
         library_notes = argd['library_notes']
         ln = argd['ln']
         return bal.get_library_notes(req, library_id, delete_key, library_notes, ln)
 
 
     def change_due_date_step1(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/change_due_date_step1"""
         argd = wash_urlargd(form, {'barcode': (str, None), 'borrower_id': (str, None),
                                     'ln': (str, "en")})
         barcode = argd['barcode']
         borrower_id = argd['borrower_id']
         ln = argd['ln']
         return bal.change_due_date_step1(req, barcode, borrower_id, ln)
 
 
     def change_due_date_step2(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/change_due_date_step2"""
         argd = wash_urlargd(form, {'new_due_date': (str, None), 'loan_id': (str, None),
                                     'borrower_id': (str, None), 'ln': (str, "en")})
         new_due_date = argd['new_due_date']
         loan_id = argd['loan_id']
         borrower_id = argd['borrower_id']
         ln = argd['ln']
         return bal.change_due_date_step2(req, new_due_date, loan_id, borrower_id, ln)
 
 
     def claim_book_return(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/claim_book_return"""
         argd = wash_urlargd(form, {'borrower_id': (str, None), 'recid': (str, None),
                             'loan_id': (str, None), 'template': (str, None), 'ln': (str, "en")})
         borrower_id = argd['borrower_id']
         recid = argd['recid']
         loan_id = argd['loan_id']
         template = argd['template']
         ln = argd['ln']
         return bal.claim_book_return(req, borrower_id, recid, loan_id, template, ln)
 
 
     def all_expired_loans(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/all_expired_loans"""
         argd = wash_urlargd(form, {'ln': (str, "en")})
         ln = argd['ln']
 
         return bal.all_expired_loans(req, ln)
 
 
     def get_waiting_requests(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/get_waiting_requests"""
         argd = wash_urlargd(form, {'request_id': (str, None), 'print_data': (str, None),
                                     'ln': (str, "en")})
         request_id = argd['request_id']
         print_data = argd['print_data']
         ln = argd['ln']
         return bal.get_waiting_requests(req, request_id, print_data, ln)
 
 
     def create_new_loan_step1(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/create_new_loan_step1"""
         argd = wash_urlargd(form, {'borrower_id': (str, None), 'ln': (str, "en")})
         borrower_id = argd['borrower_id']
         ln = argd['ln']
         return bal.create_new_loan_step1(req, borrower_id, ln)
 
 
     def create_new_loan_step2(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/create_new_loan_step2"""
         argd = wash_urlargd(form, {'borrower_id': (str, None), 'barcode': (str, None),
                                     'notes': (str, None), 'ln': (str, "en")})
         borrower_id = argd['borrower_id']
         barcode = argd['barcode']
         notes = argd['notes']
         ln = argd['ln']
         return bal.create_new_loan_step2(req, borrower_id, barcode, notes, ln)
 
 
     def create_new_request_step1(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/create_new_request_step1"""
         argd = wash_urlargd(form, {'borrower_id': (str, None), 'p': (str, None),
                             'f': (str, None), 'search': (str, None), 'ln': (str, "en")})
 
         borrower_id = argd['borrower_id']
         p = argd['p']
         f = argd['f']
         search = argd['search']
         ln = argd['ln']
 
         if borrower_id is not None:
             borrower_id = borrower_id.strip()
         if p is not None:
             p = p.strip()
 
         return bal.create_new_request_step1(req, borrower_id, p, f, search, ln)
 
 
     def create_new_request_step2(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/create_new_request_step2"""
         argd = wash_urlargd(form, {'recid': (str, None), 'borrower_id': (str, None),
                             'ln': (str, "en")})
         recid = argd['recid']
         borrower_id = argd['borrower_id']
         ln = argd['ln']
         return bal.create_new_request_step2(req, recid, borrower_id, ln)
 
 
     def create_new_request_step3(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/create_new_request_step3"""
         argd = wash_urlargd(form, {'borrower_id': (str, None), 'barcode': (str, None),
                                     'recid': (str, None), 'ln': (str, "en")})
         borrower_id = argd['borrower_id']
         barcode = argd['barcode']
         recid = argd['recid']
         ln = argd['ln']
         return bal.create_new_request_step3(req, borrower_id, barcode, recid, ln)
 
 
     def create_new_request_step4(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/create_new_request_step4"""
         argd = wash_urlargd(form, {'period_from': (str, None), 'period_to': (str, None),
                     'barcode': (str, None), 'borrower_id': (str, None), 'recid': (str, None),
                     'ln': (str, "en")})
         period_from = argd['period_from']
         period_to = argd['period_to']
         barcode = argd['barcode']
         borrower_id = argd['borrower_id']
         recid = argd['recid']
         ln = argd['ln']
         return bal.create_new_request_step4(req, period_from, period_to, barcode,
                                             borrower_id, recid, ln)
 
 
     def place_new_request_step1(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/place_new_request_step1"""
         argd = wash_urlargd(form, {'barcode': (str, None), 'recid': (str, None),
                             'key': (str, None), 'string': (str, None), 'ln': (str, "en")})
         barcode = argd['barcode']
         recid = argd['recid']
         key = argd['key']
         string = argd['string']
         ln = argd['ln']
 
         if barcode is not None:
             barcode = barcode.strip()
         if recid is not None:
             recid = recid.strip()
         if string is not None:
             string = string.strip()
 
         return bal.place_new_request_step1(req, barcode, recid, key, string, ln)
 
 
     def place_new_request_step2(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/place_new_request_step2"""
         argd = wash_urlargd(form, {'barcode': (str, None), 'recid': (str, None),
                                     'user_info': (str, None), 'ln': (str, "en")})
         barcode = argd['barcode']
         recid = argd['recid']
         user_info = argd['user_info']
         ln = argd['ln']
 
         if user_info is not None:
             user_info = user_info.split(',')
 
         return bal.place_new_request_step2(req, barcode, recid, user_info, ln)
 
 
     def place_new_request_step3(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/place_new_request_step3"""
         argd = wash_urlargd(form, {'barcode': (str, None), 'recid': (str, None),
                     'user_info': (str, None), 'period_from': (str, None),
                     'period_to': (str, None), 'ln': (str, "en")})
         barcode = argd['barcode']
         recid = argd['recid']
         user_info = argd['user_info']
         period_from = argd['period_from']
         period_to = argd['period_to']
         ln = argd['ln']
 
         if user_info is not None:
             user_info = user_info.split(',')
 
         return bal.place_new_request_step3(req, barcode, recid, user_info, period_from,
                                            period_to, ln)
 
 
     def place_new_loan_step1(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/place_new_loan_step1"""
         argd = wash_urlargd(form, {'barcode': (str, None), 'recid': (str, None),
                             'key': (str, None), 'string': (str, None), 'ln': (str, "en")})
         barcode = argd['barcode']
         recid = argd['recid']
         key = argd['key']
         string = argd['string']
         ln = argd['ln']
 
         if barcode is not None:
             barcode = barcode.strip()
         if recid is not None:
             recid = recid.strip()
         if string is not None:
             string = string.strip()
 
         return bal.place_new_loan_step1(req, barcode, recid, key, string, ln)
 
 
     def place_new_loan_step2(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/place_new_loan_step2"""
         argd = wash_urlargd(form, {'barcode': (str, None), 'recid': (str, None),
                                     'user_info': (str, None), 'ln': (str, "en")})
         barcode = argd['barcode']
         recid = argd['recid']
         user_info = argd['user_info']
         ln = argd['ln']
         return bal.place_new_loan_step2(req, barcode, recid, user_info, ln)
 
 
     def place_new_loan_step3(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/place_new_loan_step3"""
         argd = wash_urlargd(form, {'barcode': (str, None), 'recid': (str, None),
             'ccid': (str, None), 'name': (str, None), 'email': (str, None),
             'phone': (str, None), 'address': (str, None), 'mailbox': (str, None),
             'due_date': (str, None), 'notes': (str, None), 'ln': (str, "en")})
         barcode = argd['barcode']
         recid = argd['recid']
         ccid = argd['ccid']
         name = argd['name']
         email = argd['email']
         phone = argd['phone']
         address = argd['address']
         mailbox = argd['mailbox']
         due_date = argd['due_date']
         notes = argd['notes']
         ln = argd['ln']
         return bal.place_new_loan_step3(req, barcode, recid, ccid, name, email,
                                         phone, address, mailbox, due_date, notes,
                                         ln)
 
 
     def order_new_copy_step1(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/order_new_copy_step1"""
         argd = wash_urlargd(form, {'recid': (str, None), 'ln': (str, "en")})
         recid = argd['recid']
         ln = argd['ln']
 
         return bal.order_new_copy_step1(req, recid, ln)
 
     def ordered_books(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/ordered_books"""
         argd = wash_urlargd(form, {'ln': (str, "en")})
         ln = argd['ln']
 
         return bal.list_ordered_books(req, ln)
 
 
     def get_purchase_notes(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/get_purchase_notes"""
         argd = wash_urlargd(form, {'purchase_id': (str, None), 'delete_key': (str, None),
                                    'library_notes': (str, None), 'ln': (str, "en")})
         purchase_id = argd['purchase_id']
         delete_key = argd['delete_key']
         library_notes = argd['library_notes']
         ln = argd['ln']
 
         return bal.get_purchase_notes(req, purchase_id, delete_key, library_notes, ln)
 
 
     def register_ill_request_step0(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/register_ill_request_step0"""
         argd = wash_urlargd(form, {'recid': (str, None), 'key': (str, None),
                                     'string': (str, None), 'ln': (str, "en")})
         recid = argd['recid']
         key = argd['key']
         string = argd['string']
         ln = argd['ln']
         return bal.register_ill_request_step0(req, recid, key, string, ln)
 
 
     def register_ill_request_step1(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/register_ill_request_step1"""
         argd = wash_urlargd(form, {'recid': (str, None), 'user_info': (str, None),
                                     'ln': (str, "en")})
         recid = argd['recid']
         user_info = argd['user_info']
         ln = argd['ln']
 
         return bal.register_ill_request_step1(req, recid, user_info, ln)
 
     def register_ill_request_step2(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/register_ill_request_step2"""
         argd = wash_urlargd(form, {'recid': (str, None), 'user_info': (str, None),
                 'period_of_interest_from': (str, None), 'period_of_interest_to': (str, None),
                 'notes': (str, None), 'only_edition': (str, None), 'ln': (str, "en")})
         recid = argd['recid']
         user_info = argd['user_info']
         period_of_interest_from = argd['period_of_interest_from']
         period_of_interest_to = argd['period_of_interest_to']
         notes = argd['notes']
         only_edition = argd['only_edition']
         ln = argd['ln']
 
         return bal.register_ill_request_step2(req, recid, user_info,
                                               period_of_interest_from, period_of_interest_to,
                                               notes, only_edition, ln)
 
     def list_ill_request(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/list_ill_request"""
         argd = wash_urlargd(form, {'status': (str, None), 'ln': (str, "en")})
         status = argd['status']
         ln = argd['ln']
 
         return bal.list_ill_request(req, status, ln)
 
     def list_acquisition(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/list_acquisition"""
         argd = wash_urlargd(form, {'status': (str, None), 'ln': (str, "en")})
         status = argd['status']
         ln = argd['ln']
 
         return bal.list_acquisition(req, status, ln)
 
     def ill_request_details_step1(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/ill_request_details_step1"""
 
         argd = wash_urlargd(form, {'delete_key': (str, None), 'ill_request_id': (str, None),
                                    'new_status': (str, None), 'ln': (str, "en")})
 
         delete_key = argd['delete_key']
         ill_request_id = argd['ill_request_id']
         new_status = argd['new_status']
         ln = argd['ln']
 
         return bal.ill_request_details_step1(req, delete_key, ill_request_id, new_status, ln)
 
     def ill_request_details_step2(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/ill_request_details_step2"""
 
         argd = wash_urlargd(form, {'delete_key': (str, None),
             'ill_request_id': (str, None), 'new_status': (str, None),
             'library_id': (str, None), 'request_date': (str, None),
             'expected_date': (str, None), 'arrival_date': (str, None),
             'due_date': (str, None), 'return_date': (str, None),
             'cost': (str, None), 'currency': (str, None),
             'barcode': (str, None), 'library_notes': (str, None),
             'title': (str, None), 'authors': (str, None), 'place': (str, None),
             'publisher': (str, None), 'year': (str, None),
             'edition': (str, None), 'isbn': (str, None),
             'periodical_title': (str,None), 'volume': (str,''),
             'issue': (str,''), 'page': (str,''), 'issn': (str,None),
             'ln': (str, "en")})
 
         delete_key = argd['delete_key']
         ill_request_id = argd['ill_request_id']
         new_status = argd['new_status']
         library_id = argd['library_id']
         request_date = argd['request_date']
         expected_date = argd['expected_date']
         arrival_date = argd['arrival_date']
         due_date = argd['due_date']
         return_date = argd['return_date']
         cost = argd['cost']
         currency = argd['currency']
         barcode = argd['barcode']
         library_notes = argd['library_notes']
 
         title = argd['title']
         authors = argd['authors']
         place = argd['place']
         publisher = argd['publisher']
         year = argd['year']
         edition = argd['edition']
         isbn = argd['isbn']
 
         periodical_title = argd['periodical_title']
         volume = argd['volume']
         issue = argd['issue']
         page = argd['page']
         issn = argd['issn']
 
         ln = argd['ln']
 
         if library_notes is not None:
             library_notes = library_notes.strip()
         if delete_key is not None:
             delete_key = delete_key.strip()
         if ill_request_id is not None:
             ill_request_id = ill_request_id.strip()
         if new_status is not None:
             new_status = new_status.strip()
         if library_id is not None:
             library_id = library_id.strip()
         if return_date is not None:
             return_date = return_date.strip()
         if expected_date is not None:
             expected_date = expected_date.strip()
         if arrival_date is not None:
             arrival_date = arrival_date.strip()
         if due_date is not None:
             due_date = due_date.strip()
         if return_date is not None:
             return_date = return_date.strip()
         if cost is not None:
             cost = cost.strip()
         if currency is not None:
             currency = currency.strip()
         if barcode is not None:
             barcode = barcode.strip()
 
         if title is not None:
             title = title.strip()
         if authors is not None:
             authors = authors.strip()
         if place is not None:
             place = place.strip()
         if publisher is not None:
             publisher = publisher.strip()
         if year is not None:
             year = year.strip()
         if edition is not None:
             edition =  edition.strip()
         if isbn is not None:
             isbn = isbn.strip()
 
 
         if periodical_title is not None:
             periodical_title = periodical_title.strip()
         if volume is not None:
             volume = volume.strip()
         if issue is not None:
             issue = issue.strip()
         if page is not None:
             page = page.strip()
         if issn is not None:
             issn = issn.strip()
 
         #article_info = {'periodical_title': periodical_title, 'article_title:': title,
                    #     'authors': author, report_number,
                 #    volume, issue, pages, year, issn}
 
         article_info = {'periodical_title': periodical_title, 'title': title, 'authors': authors,
             'place': place, 'publisher': publisher, 'year' : year,  'edition': "", 'issn' : issn,
             'volume': volume, 'issue': issue, 'page': page }
 
         book_info = {'title': title, 'authors': authors, 'place': place, 'publisher': publisher,
                      'year': year, 'edition': edition, 'isbn': isbn}
         #article_details = ()
 
         return bal.ill_request_details_step2(req, delete_key, ill_request_id, new_status,
                                         library_id, request_date, expected_date, arrival_date,
                                         due_date, return_date, cost, currency, barcode,
                                         library_notes, book_info, article_info, ln)
 
     def acq_details_step1(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/acq_details_step1"""
 
         argd = wash_urlargd(form, {'delete_key': (str, None), 'ill_request_id': (str, None),
                                    'new_status': (str, None), 'ln': (str, "en")})
 
         delete_key = argd['delete_key']
         ill_request_id = argd['ill_request_id']
         new_status = argd['new_status']
         ln = argd['ln']
 
         return bal.acq_details_step1(req, delete_key, ill_request_id, new_status, ln)
 
     def acq_details_step2(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/ill_request_details_step2"""
 
         argd = wash_urlargd(form, {'ill_request_id': (str, None),
             'new_status': (str, None), 'library_id': (str, None),
             'request_date': (str, None), 'expected_date': (str, None),
             'arrival_date': (str, None), 'due_date': (str, None),
             'return_date': (str, None), 'cost': (str, ''), 'authors': (str, ''),
             'library_notes': (str, ''), 'title': (str, ''), 'place': (str, ''),
             'publisher': (str, ''), 'year': (str, ''), 'edition': (str, ''),
             'isbn': (str, ''), 'budget_code': (str, ''),
             'standard_number': (str, ''), 'ln': (str, "en")})
 
         ill_request_id = argd['ill_request_id']
         new_status = argd['new_status']
         library_id = argd['library_id']
         request_date = argd['request_date']
         expected_date = argd['expected_date']
         arrival_date = argd['arrival_date']
         due_date = argd['due_date']
         return_date = argd['return_date']
         cost = argd['cost'].strip()
         budget_code = argd['budget_code'].strip()
         library_notes = argd['library_notes'].strip()
         standard_number = argd['standard_number'].strip()
 
         title = argd['title'].strip()
         authors = argd['authors'].strip()
         place = argd['place'].strip()
         publisher = argd['publisher'].strip()
         year = argd['year'].strip()
         edition = argd['edition'].strip()
         isbn = argd['isbn'].strip()
         ln = argd['ln'].strip()
 
         if ill_request_id is not None:
             ill_request_id = ill_request_id.strip()
         if new_status is not None:
             new_status = new_status.strip()
         if library_id is not None:
             library_id = library_id.strip()
         if return_date is not None:
             return_date = return_date.strip()
         if expected_date is not None:
             expected_date = expected_date.strip()
         if arrival_date is not None:
             arrival_date = arrival_date.strip()
         if due_date is not None:
             due_date = due_date.strip()
         if return_date is not None:
             return_date = return_date.strip()
 
         item_info = {'title': title, 'authors': authors,
                      'place': place, 'publisher': publisher,
                      'year': year, 'edition': edition, 'isbn': isbn,
                      'standard_number': standard_number}
 
         return bal.acq_details_step2(req, None, ill_request_id,
                                     new_status, library_id, request_date,
                                     expected_date, arrival_date, due_date,
                                     return_date, cost, budget_code,
                                     library_notes, item_info, ln)
 
     def ordered_books_details_step1(self, req, form):
         """    """
         argd = wash_urlargd(form, {'purchase_id': (str, None),
                                    'delete_key': (str, None),
                                    'ln': (str, "en")})
         purchase_id = argd['purchase_id']
         delete_key = argd['delete_key']
         ln = argd['ln']
 
         return bal.ordered_books_details_step1(req, purchase_id, delete_key, ln)
 
     def ordered_books_details_step2(self, req, form):
         """    """
         argd = wash_urlargd(form, {'purchase_id': (str, None), 'recid': (str, None),
             'vendor_id': (str, None), 'cost': (str, None), 'currency': (str, None),
             'status': (str, None), 'order_date': (str, None), 'expected_date': (str, None),
             'purchase_notes': (str, None), 'library_notes': (str, None), 'ln': (str, "en")})
 
         purchase_id = argd['purchase_id']
         recid = argd['recid']
         vendor_id = argd['vendor_id']
         cost = argd['cost']
         currency = argd['currency']
         status = argd['status']
         order_date = argd['order_date']
         expected_date = argd['expected_date']
         purchase_notes = argd['purchase_notes']
         library_notes = argd['library_notes']
         ln = argd['ln']
 
         return bal.ordered_books_details_step2(req, purchase_id, recid, vendor_id,
                                                cost, currency, status, order_date, expected_date,
                                                purchase_notes, library_notes, ln)
 
 
     def ordered_books_details_step3(self, req, form):
         """    """
         argd = wash_urlargd(form, {'purchase_id': (str, None), 'recid': (str, None),
             'vendor_id': (str, None), 'cost': (str, None), 'currency': (str, None),
             'status': (str, None), 'order_date': (str, None), 'expected_date': (str, None),
             'purchase_notes': (str, None), 'library_notes': (str, None), 'ln': (str, "en")})
         purchase_id = argd['purchase_id']
         recid = argd['recid']
         vendor_id = argd['vendor_id']
         cost = argd['cost']
         currency = argd['currency']
         status = argd['status']
         order_date = argd['order_date']
         expected_date = argd['expected_date']
         purchase_notes = argd['purchase_notes']
         library_notes = argd['library_notes']
         ln = argd['ln']
 
         return bal.ordered_books_details_step3(req, purchase_id, recid, vendor_id,
                                                cost, currency, status, order_date, expected_date,
                                                purchase_notes, library_notes, ln)
 
     def add_new_vendor_step1(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/add_new_vendor_step1"""
         argd = wash_urlargd(form, {'ln': (str, "en")})
         ln = argd['ln']
         return bal.add_new_vendor_step1(req, ln)
 
 
     def add_new_vendor_step2(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/add_new_vendor_step2"""
         argd = wash_urlargd(form, {'name': (str, None), 'email': (str, None),
         'phone': (str, None), 'address': (str, None), 'notes': (str, None), 'ln': (str, "en")})
 
         name = argd['name']
         email = argd['email']
         phone = argd['phone']
         address = argd['address']
         notes = argd['notes']
         ln = argd['ln']
 
         if name is not None:
             name = name.strip()
         if email is not None:
             email = email.strip()
         if phone is not None:
             phone = phone.strip()
         if address is not None:
             address = address.strip()
 
         return bal.add_new_vendor_step2(req, name, email, phone, address,
                                         notes, ln)
 
 
     def add_new_vendor_step3(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/add_new_vendor_step3"""
         argd = wash_urlargd(form, {'name': (str, None), 'email': (str, None),
             'phone': (str, None), 'address': (str, None), 'notes': (str, None),
             'ln': (str, "en")})
 
         name = argd['name']
         email = argd['email']
         phone = argd['phone']
         address = argd['address']
         notes = argd['notes']
         ln = argd['ln']
         return bal.add_new_vendor_step3(req, name, email, phone, address,
                                         notes, ln)
 
 
     def update_vendor_info_step1(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/update_vendor_info_step1"""
         argd = wash_urlargd(form, {'ln': (str, "en")})
         ln = argd['ln']
         return bal.update_vendor_info_step1(req, ln)
 
 
     def update_vendor_info_step2(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/update_vendor_info_step2"""
         argd = wash_urlargd(form, {'column': (str, None), 'string': (str, None),
             'ln': (str, "en")})
 
         column = argd['column']
         string = argd['string']
         ln = argd['ln']
 
         if string is not None:
             string = string.strip()
 
         return bal.update_vendor_info_step2(req, column, string, ln)
 
 
     def update_vendor_info_step3(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/update_vendor_info_step3"""
         argd = wash_urlargd(form, {'vendor_id': (str, None), 'ln': (str, "en")})
         vendor_id = argd['vendor_id']
         ln = argd['ln']
         return bal.update_vendor_info_step3(req, vendor_id, ln)
 
 
     def update_vendor_info_step4(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/update_vendor_info_step4"""
         argd = wash_urlargd(form, {'name': (str, None), 'email': (str, None),
             'phone': (str, None), 'address': (str, None), 'vendor_id': (str, None),
             'ln': (str, "en")})
 
         name = argd['name']
         email = argd['email']
         phone = argd['phone']
         address = argd['address']
         vendor_id = argd['vendor_id']
         ln = argd['ln']
 
         if name is not None:
             name = name.strip()
         if email is not None:
             email = email.strip()
         if phone is not None:
             phone = phone.strip()
         if address is not None:
             address = address.strip()
 
         return bal.update_vendor_info_step4(req, name, email, phone, address,
                                             vendor_id, ln)
 
 
     def update_vendor_info_step5(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/update_vendor_info_step5"""
         argd = wash_urlargd(form, {'name': (str, None), 'email': (str, None),
             'phone': (str, None), 'address': (str, None), 'vendor_id': (str, None),
             'ln': (str, "en")})
 
         name = argd['name']
         email = argd['email']
         phone = argd['phone']
         address = argd['address']
         vendor_id = argd['vendor_id']
         ln = argd['ln']
         return bal.update_vendor_info_step5(req, name, email, phone, address,
                                             vendor_id, ln)
 
 
     def search_vendor_step1(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/search_vendor_step1"""
         argd = wash_urlargd(form, {'ln': (str, "en")})
         ln = argd['ln']
         return bal.search_vendor_step1(req, ln)
 
 
     def search_vendor_step2(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/search_vendor_step2"""
         argd = wash_urlargd(form, {'column': (str, ''), 'string': (str, ''), 'ln': (str, "en")})
         column = argd['column']
         string = argd['string']
         ln = argd['ln']
 
         if string is not None:
             string = string.strip()
 
         return bal.search_vendor_step2(req, column, string, ln)
 
 
     def get_vendor_details(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/get_vendor_details"""
         argd = wash_urlargd(form, {'vendor_id': (str, None), 'ln': (str, "en")})
         vendor_id = argd['vendor_id']
         ln = argd['ln']
         return bal.get_vendor_details(req, vendor_id, ln)
 
 
     def get_vendor_notes(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/get_vendor_notes"""
         argd = wash_urlargd(form, {'vendor_id': (str, None), 'add_notes': (str, None),
                                     'new_note': (str, None), 'ln': (str, "en")})
         vendor_id = argd['vendor_id']
         add_notes = argd['add_notes']
         new_note = argd['new_note']
         ln = argd['ln']
         return bal.get_vendor_notes(req, vendor_id, add_notes, new_note, ln)
 
 
     def register_ill_request_with_no_recid_step1(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/register_ill_request_with_no_recid_step1"""
         argd = wash_urlargd(form, {'ln': (str, "en"), 'borrower_id': (str, None)})
         ln = argd['ln']
         borrower_id = argd['borrower_id']
         if borrower_id == 'None':
             borrower_id = None
 
         return bal.register_ill_request_with_no_recid_step1(req, borrower_id, ln)
 
 
     def register_ill_request_with_no_recid_step2(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/register_ill_request_with_no_recid_step2"""
 
         argd = wash_urlargd(form, {'title': (str, ''), 'authors': (str, ''),
             'place': (str, ''), 'publisher': (str, ''), 'year': (str, ''),
             'edition': (str, ''), 'isbn': (str, ''), 'budget_code': (str, ''),
             'period_of_interest_from': (str, ''), 'period_of_interest_to': (str, ''),
             'additional_comments': (str, ''), 'only_edition': (str, 'No'), 'key': (str, None),
             'string': (str, ''), 'borrower_id': (str, None), 'ln': (str, "en")})
 
         title = argd['title']
         authors = argd['authors']
         place = argd['place']
         publisher = argd['publisher']
         year = argd['year']
         edition = argd['edition']
         isbn = argd['isbn']
         budget_code = argd['budget_code']
         period_of_interest_from = argd['period_of_interest_from']
         period_of_interest_to = argd['period_of_interest_to']
         additional_comments = argd['additional_comments']
         only_edition = argd['only_edition']
         key = argd['key']
         string = argd['string']
         borrower_id = argd['borrower_id']
         ln = argd['ln']
 
         if borrower_id is not None:
             borrower_id = borrower_id.strip()
         if borrower_id == 'None':
             borrower_id = None
 
         title = title.strip()
         authors = authors.strip()
         place = place.strip()
         publisher = publisher.strip()
         year = year.strip()
         edition =  edition.strip()
         isbn = isbn.strip()
         budget_code = budget_code.strip()
         period_of_interest_from = period_of_interest_from.strip()
         period_of_interest_to = period_of_interest_to.strip()
         string = string.strip()
 
         return bal.register_ill_request_with_no_recid_step2(req, title, authors, place,
                             publisher, year, edition, isbn, budget_code, period_of_interest_from,
                             period_of_interest_to, additional_comments,
                             only_edition, key, string, borrower_id, ln)
 
 
     def register_ill_request_with_no_recid_step3(self, req, form):
         """    """
         argd = wash_urlargd(form, {'title': (str, None), 'authors': (str, None),
             'place': (str, None), 'publisher': (str, None), 'year': (str, None),
             'edition': (str, None), 'isbn': (str, None), 'user_info': (str, None),
             'budget_code': (str, ''), 'period_of_interest_from': (str, None),
             'period_of_interest_to': (str, None), 'additional_comments': (str, None),
             'only_edition': (str, 'No'), 'ln': (str, "en")})
 
         title = argd['title']
         authors = argd['authors']
         place = argd['place']
         publisher = argd['publisher']
         year = argd['year']
         edition = argd['edition']
         isbn = argd['isbn']
 
         user_info = argd['user_info']
 
         budget_code = argd['budget_code']
         period_of_interest_from = argd['period_of_interest_from']
         period_of_interest_to = argd['period_of_interest_to']
         additional_comments = argd['additional_comments']
         only_edition = argd['only_edition']
 
         ln = argd['ln']
 
         if user_info is not None:
             user_info = user_info.split(',')
 
         return bal.register_ill_request_with_no_recid_step3(req, title, authors, place,
                                                             publisher, year, edition, isbn,
                                                             user_info, budget_code,
                                                             period_of_interest_from,
                                                             period_of_interest_to,
                                                             additional_comments,
                                                             only_edition, ln)
 
     def register_ill_request_with_no_recid_step4(self, req, form):
         """    """
 
         argd = wash_urlargd(form, {'title': (str, None), 'authors': (str, None),
             'place': (str, None), 'publisher': (str, None), 'year': (str, None),
             'edition': (str, None), 'isbn': (str, None), 'borrower_id': (str, None),
             'budget_code': (str, ''), 'period_of_interest_from': (str, None),
             'period_of_interest_to': (str, None), 'additional_comments': (str, None),
             'only_edition': (str, None), 'ln': (str, "en")})
 
         title = argd['title']
         authors = argd['authors']
         place = argd['place']
         publisher = argd['publisher']
         year = argd['year']
         edition = argd['edition']
         isbn = argd['isbn']
 
         borrower_id = argd['borrower_id']
 
         budget_code = argd['budget_code']
         period_of_interest_from = argd['period_of_interest_from']
         period_of_interest_to = argd['period_of_interest_to']
         additional_comments = argd['additional_comments']
         only_edition = argd['only_edition']
 
         ln = argd['ln']
 
         book_info = (title, authors, place, publisher, year, edition, isbn)
 
         request_details = (budget_code, period_of_interest_from, period_of_interest_to,
                             additional_comments, only_edition)
 
         return bal.register_ill_request_with_no_recid_step4(req, book_info, borrower_id,
                                                             request_details, ln)
 
 
     def get_borrower_ill_details(self, req, form):
         """    """
         argd = wash_urlargd(form, {'borrower_id': (str, None),'ln': (str, "en")})
         borrower_id = argd['borrower_id']
         ln = argd['ln']
 
         return bal.get_borrower_ill_details(req, borrower_id, ln)
 
 
     def bor_ill_historical_overview(self, req, form):
         """    """
         argd = wash_urlargd(form, {'borrower_id': (str, None), 'ln': (str, "en")})
         borrower_id = argd['borrower_id']
         ln = argd['ln']
 
         return bal.bor_ill_historical_overview(req, borrower_id, ln)
 
 
     def get_ill_library_notes(self, req, form):
         """    """
         argd = wash_urlargd(form, {'ill_id': (str, None), 'delete_key': (str, None),
                                         'library_notes': (str, None), 'ln': (str, "en")})
         ill_id = argd['ill_id']
         delete_key = argd['delete_key']
         library_notes = argd['library_notes']
         ln = argd['ln']
 
         return bal.get_ill_library_notes(req, ill_id, delete_key, library_notes, ln)
 
 
     def get_expired_loans_with_requests(self, req, form):
         """    """
         argd = wash_urlargd(form, {'request_id': (str, None), 'ln': (str, "en")})
         request_id = argd['request_id']
         ln = argd['ln']
 
         return bal.get_expired_loans_with_requests(req, request_id, ln)
 
 
     def register_ill_book_request(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/holdings_search"""
         argd = wash_urlargd(form, {'borrower_id': (str, None), 'ln': (str, "en")})
         ln = argd['ln']
         borrower_id = argd['borrower_id']
         return bal.register_ill_book_request(req, borrower_id, ln)
 
 
     def register_ill_book_request_result(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/item_search_result"""
         argd = wash_urlargd(form, {'borrower_id': (str, None),'p': (str, None),
                                     'f': (str, None), 'ln': (str, "en")})
         p = argd['p']
         f = argd['f']
         ln = argd['ln']
         borrower_id = argd['borrower_id']
         return bal.register_ill_book_request_result(req, borrower_id, p, f, ln)
 
     def register_ill_book_request_from_borrower_page(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/holdings_search"""
         argd = wash_urlargd(form, {'borrower_id': (str, None), 'ln': (str, "en")})
         borrower_id = argd['borrower_id']
         ln = argd['ln']
         return bal.register_ill_book_request_from_borrower_page(req, borrower_id, ln)
 
     def register_purchase_request_step1(self, req, form):
         """    """
         argd = wash_urlargd(form, {'recid': (str, ''), 'type': (str, 'acq-book'),
                 'title': (str, ''), 'authors': (str, ''), 'place': (str, ''),
                 'publisher': (str, ''), 'year': (str, ''), 'edition': (str, ''),
                 'this_edition_only': (str, 'No'),
                 'isbn': (str, ''), 'standard_number': (str, ''),
                 'budget_code': (str, ''), 'cash': (str, 'No'),
                 'period_of_interest_from': (str, ''),
                 'period_of_interest_to': (str, ''),
                 'additional_comments': (str, ''), 'ln': (str, "en")})
 
         recid = argd['recid'].strip()
-        req_type = argd['type'].strip()
+        request_type = argd['type'].strip()
         title = argd['title'].strip()
         authors = argd['authors'].strip()
         place = argd['place'].strip()
         publisher = argd['publisher'].strip()
         year = argd['year'].strip()
         edition = argd['edition'].strip()
         this_edition_only = argd['this_edition_only'].strip()
         isbn = argd['isbn'].strip()
         standard_number = argd['standard_number'].strip()
         budget_code = argd['budget_code'].strip()
         cash = argd['cash'] == 'Yes'
         period_of_interest_from = argd['period_of_interest_from'].strip()
         period_of_interest_to = argd['period_of_interest_to'].strip()
         additional_comments = argd['additional_comments'].strip()
         ln = argd['ln']
 
-        return bal.register_purchase_request_step1(req, recid, req_type, title,
+        return bal.register_purchase_request_step1(req, recid, request_type, title,
                                 authors, place, publisher, year, edition,
                                 this_edition_only, isbn, standard_number,
                                 budget_code, cash, period_of_interest_from,
                                 period_of_interest_to, additional_comments, ln)
 
 
     def register_purchase_request_step2(self, req, form):
         """    """
         argd = wash_urlargd(form, {'type': (str, 'acq-book'),
                 'title': (str, ''), 'authors': (str, ''), 'place': (str, ''),
                 'publisher': (str, ''), 'year': (str, ''), 'edition': (str, ''),
                 'this_edition_only': (str, 'No'),
                 'isbn': (str, ''), 'standard_number': (str, ''),
                 'budget_code': (str, ''), 'cash': (str, 'No'),
                 'period_of_interest_from': (str, ''),
                 'period_of_interest_to': (str, ''),
                 'additional_comments': (str, ''), 'p': (str, ''),
                 'f': (str, ''), 'ln': (str, "en")})
 
-        type = argd['type'].strip()
+        request_type = argd['type'].strip()
         title = argd['title'].strip()
         authors = argd['authors'].strip()
         place = argd['place'].strip()
         publisher = argd['publisher'].strip()
         year = argd['year'].strip()
         edition = argd['edition'].strip()
         this_edition_only = argd['this_edition_only'].strip()
         isbn = argd['isbn'].strip()
         standard_number = argd['standard_number'].strip()
         budget_code = argd['budget_code'].strip()
         cash = (argd['cash'] == 'Yes')
         period_of_interest_from = argd['period_of_interest_from'].strip()
         period_of_interest_to = argd['period_of_interest_to'].strip()
         additional_comments = argd['additional_comments'].strip()
         p = argd['p'].strip()
         f = argd['f'].strip()
         ln = argd['ln']
 
-        return bal.register_purchase_request_step2(req, type, title, authors,
+        return bal.register_purchase_request_step2(req, request_type, title, authors,
                         place, publisher, year, edition, this_edition_only,
                         isbn, standard_number, budget_code, cash,
                         period_of_interest_from, period_of_interest_to,
                         additional_comments, p, f, ln)
 
     def register_purchase_request_step3(self, req, form):
         """    """
         argd = wash_urlargd(form, {'type': (str, 'acq-book'),
                 'title': (str, ''), 'authors': (str, ''), 'place': (str, ''),
                 'publisher': (str, ''), 'year': (str, ''), 'edition': (str, ''),
                 'this_edition_only': (str, 'No'),
                 'isbn': (str, ''), 'standard_number': (str, ''),
                 'budget_code': (str, ''), 'cash': (str, 'No'),
                 'period_of_interest_from': (str, ''),
                 'period_of_interest_to': (str, ''),
                 'additional_comments': (str, ''),
                 'borrower_id': (str, ''), 'ln': (str, "en")})
 
-        type = argd['type'].strip()
+        request_type = argd['type'].strip()
         title = argd['title'].strip()
         authors = argd['authors'].strip()
         place = argd['place'].strip()
         publisher = argd['publisher'].strip()
         year = argd['year'].strip()
         edition = argd['edition'].strip()
         this_edition_only = argd['this_edition_only'].strip()
         isbn = argd['isbn'].strip()
         standard_number = argd['standard_number'].strip()
         budget_code = argd['budget_code'].strip()
         cash = (argd['cash'] == 'Yes')
         period_of_interest_from = argd['period_of_interest_from'].strip()
         period_of_interest_to = argd['period_of_interest_to'].strip()
         additional_comments = argd['additional_comments'].strip()
         borrower_id = argd['borrower_id'].strip()
         ln = argd['ln']
 
-        return bal.register_purchase_request_step3(req, type, title, authors,
+        return bal.register_purchase_request_step3(req, request_type, title, authors,
                         place, publisher, year, edition, this_edition_only,
                         isbn, standard_number,
                         budget_code, cash, period_of_interest_from,
                         period_of_interest_to, additional_comments,
                         borrower_id, ln)
 
     def register_ill_article_request_step1(self, req, form):
         """    """
         argd = wash_urlargd(form, {'ln': (str, "en")})
 
         ln = argd['ln']
 
         return bal.register_ill_article_request_step1(req, ln)
 
 
     def register_ill_article_request_step2(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/register_ill_request_with_no_recid_step2"""
 
         argd = wash_urlargd(form, {'periodical_title': (str, None),
             'article_title': (str, None), 'author': (str, None),
             'report_number': (str, None), 'volume': (str, None),
             'issue': (str, None), 'page': (str, None), 'year': (str, None),
             'budget_code': (str, ''), 'issn': (str, None),
             'period_of_interest_from': (str, None),
             'period_of_interest_to': (str, None),
             'additional_comments': (str, None), 'key': (str, None),
             'string': (str, None), 'ln': (str, "en")})
 
         periodical_title = argd['periodical_title']
         article_title = argd['article_title']
         author = argd['author']
         report_number = argd['report_number']
         volume = argd['volume']
         issue = argd['issue']
         page = argd['page']
         year = argd['year']
         budget_code = argd['budget_code']
         issn = argd['issn']
         period_of_interest_from = argd['period_of_interest_from']
         period_of_interest_to = argd['period_of_interest_to']
         additional_comments = argd['additional_comments']
         key = argd['key']
         string = argd['string']
         ln = argd['ln']
 
         return bal.register_ill_article_request_step2(req, periodical_title, article_title,
                                                       author, report_number,
                                                       volume, issue, page, year, budget_code,
                                                       issn, period_of_interest_from,
                                                       period_of_interest_to,
                                                       additional_comments, key, string, ln)
 
 
     def register_ill_article_request_step3(self, req, form):
 
         argd = wash_urlargd(form, {'periodical_title': (str, ''), 'article_title': (str, ''),
                 'author': (str, ''), 'report_number': (str, ''), 'volume': (str, ''),
                 'issue': (str, ''), 'page': (str, ''), 'year': (str, ''), 'issn': (str, ''),
                 'user_info': (str, None), 'request_details': (str, '()'),
                 'ln': (str, "en"), 'period_of_interest_from': (str, ''),
                 'period_of_interest_to': (str, ''), 'budget_code': (str, ''),
                 'additional_comments': (str, '')})
 
         periodical_title = argd['periodical_title']
         article_title = argd['article_title']
         author = argd['author']
         report_number = argd['report_number']
         volume = argd['volume']
         issue = argd['issue']
         page = argd['page']
         year = argd['year']
         issn = argd['issn']
         user_info = argd['user_info']
         request_details = argd['request_details']
         ln = argd['ln']
         period_of_interest_from = argd['period_of_interest_from']
         period_of_interest_to = argd['period_of_interest_to']
         budget_code = argd['budget_code']
         additional_comments = argd['additional_comments']
 
         request_details = (period_of_interest_from, period_of_interest_to,
                            budget_code, additional_comments)
 
         if user_info is not None:
             user_info = user_info.split(',')
 
         return bal.register_ill_article_request_step3(req, periodical_title, article_title,
                                         author, report_number, volume, issue, page, year, issn,
                                         user_info, request_details, ln)
 
 
     def ill_search(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/holdings_search"""
         argd = wash_urlargd(form, {'ln': (str, "en")})
         ln = argd['ln']
         return bal.ill_search(req, ln)
 
 
     def ill_search_result(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/item_search_result"""
         argd = wash_urlargd(form, {'p': (str, None), 'f': (str, None), 'date_from': (str, None),
                                         'date_to': (str, None), 'ln': (str, "en")})
         p = argd['p']
         f = argd['f']
         date_from = argd['date_from']
         date_to = argd['date_to']
         ln = argd['ln']
 
         if p is not None:
             p = p.strip()
         if date_from is not None:
             date_from = date_from.strip()
         if date_to is not None:
             date_to = date_to.strip()
 
         return bal.ill_search_result(req, p, f, date_from, date_to, ln)
 
     def merge_libraries_step1(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/merge_libraries_step1"""
         argd = wash_urlargd(form, {'library_id': (int, None), 'p': (str, None),
                                     'f': (str, None), 'ln': (str, None)})
 
         library_id = argd['library_id']
         p  = argd['p']
         f  = argd['f']
         ln = argd['ln']
 
         if p is not None:
             p = p.strip()
 
         return bal.merge_libraries_step1(req, library_id, f, p, ln)
 
     def merge_libraries_step2(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/merge_libraries_step2"""
         argd = wash_urlargd(form, {'library_from': (int, None), 'library_to': (int, None),
                                              'ln': (str, "en")})
 
         library_from = argd['library_from']
         library_to   = argd['library_to']
         ln = argd['ln']
 
         return bal.merge_libraries_step2(req, library_from, library_to, ln)
 
     def merge_libraries_step3(self, req, form):
         """http://cdsweb.cern.ch/admin2/bibcirculation/merge_libraries_step2"""
         argd = wash_urlargd(form, {'library_from': (int, None), 'library_to': (int, None),
                                              'ln': (str, "en")})
 
         library_from = argd['library_from']
         library_to   = argd['library_to']
         ln = argd['ln']
 
         return bal.merge_libraries_step3(req, library_from, library_to, ln)
 
     def __call__(self, req, form):
         """Redirect calls without final slash."""
         redirect_to_url(req, '%s/admin2/bibcirculation/' % CFG_SITE_URL)
diff --git a/modules/bibcirculation/lib/bibcirculationadminlib.py b/modules/bibcirculation/lib/bibcirculationadminlib.py
index c20ced647..779bec78a 100644
--- a/modules/bibcirculation/lib/bibcirculationadminlib.py
+++ b/modules/bibcirculation/lib/bibcirculationadminlib.py
@@ -1,6778 +1,6777 @@
 ## Administrator interface for Bibcirculation
 ##
 ## This file is part of Invenio.
 ## Copyright (C) 2008, 2009, 2010, 2011 CERN.
 ##
 ## Invenio is free software; you can redistribute it and/or
 ## modify it under the terms of the GNU General Public License as
 ## published by the Free Software Foundation; either version 2 of the
 ## License, or (at your option) any later version.
 ##
 ## Invenio is distributed in the hope that it will be useful, but
 ## WITHOUT ANY WARRANTY; without even the implied warranty of
 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 ## General Public License for more details.
 ##
 ## You should have received a copy of the GNU General Public License
 ## along with Invenio; if not, write to the Free Software Foundation, Inc.,
 ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 
 ## """Invenio Bibcirculation Administrator Interface."""
 
 from __future__ import division
 
 """Invenio Bibcirculation Administrator Interface."""
 
 __revision__ = "$Id$"
 
 __lastupdated__ = """$Date$"""
 
-import datetime, time, cgi, types
+import datetime, time, types
 
 # Others Invenio imports
 from invenio.config import \
     CFG_SITE_LANG, \
     CFG_SITE_SECURE_URL, \
     CFG_CERN_SITE
 import invenio.access_control_engine as acce
 from invenio.webpage import page
 from invenio.webuser import getUid, page_not_authorized
 from invenio.webstat import register_customevent
 from invenio.errorlib import register_exception
 from invenio.mailutils import send_email
 from invenio.search_engine import perform_request_search, record_exists
 from invenio.urlutils import create_html_link, redirect_to_url
 from invenio.messages import gettext_set_language
 from invenio.bibcirculation_utils import book_title_from_MARC, \
       update_status_if_expired, \
       renew_loan_for_X_days, \
       print_pending_hold_requests_information, \
       print_new_loan_information, \
       validate_date_format, \
       generate_email_body, \
       book_information_from_MARC, \
       search_user, \
       tag_all_requests_as_done, \
       update_user_info_from_ldap, \
       update_requests_statuses, \
       has_date_format, \
       generate_tmp_barcode
       #is_periodical, \
       #create_ill_record, \
       #create_item_details_url
 from invenio.webstat import register_customevent
 from invenio.errorlib import register_exception
 
 # Bibcirculation imports
 from invenio.bibcirculation_config import \
      CFG_BIBCIRCULATION_TEMPLATES, CFG_BIBCIRCULATION_AMAZON_ACCESS_KEY, \
      CFG_BIBCIRCULATION_LIBRARIAN_EMAIL, CFG_BIBCIRCULATION_LOANS_EMAIL, \
      CFG_BIBCIRCULATION_ACQ_TYPE
 import invenio.bibcirculation_dblayer as db
 from invenio.bibcirculation_cern_ldap import get_user_info_from_ldap
 import invenio.template
 bc_templates = invenio.template.load('bibcirculation')
 
 from invenio.config import \
     CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN, \
     CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF, \
     CFG_BIBCIRCULATION_ITEM_STATUS_IN_PROCESS, \
     CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN, \
     CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED, \
     CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING, \
     CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING, \
     CFG_BIBCIRCULATION_REQUEST_STATUS_DONE, \
     CFG_BIBCIRCULATION_REQUEST_STATUS_CANCELLED, \
     CFG_BIBCIRCULATION_ILL_STATUS_NEW, \
     CFG_BIBCIRCULATION_LIBRARY_TYPE_MAIN, \
     CFG_BIBCIRCULATION_ACQ_STATUS_NEW
 
 def is_adminuser(req):
     """check if user is a registered administrator. """
 
     return acce.acc_authorize_action(req, "runbibcirculation")
 
 def mustloginpage(req, message):
     """show a page asking the user to login."""
 
     navtrail_previous_links = '<a class="navtrail" href="%s/admin/">' \
         'Admin Area</a> &gt; ' \
         '<a class="navtrail" href="%s/admin/bibcirculation/">' \
         'BibCirculation Admin</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL)
 
     return page_not_authorized(req=req, text=message,
         navtrail=navtrail_previous_links)
 
 def index(req, ln=CFG_SITE_LANG):
     """main function to show pages for bibcirculationadmin
     """
     navtrail_previous_links = '<a class="navtrail"' \
                               ' href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     body = bc_templates.tmpl_index(ln=ln)
 
     return page(title=_("BibCirculation Admin"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 
 
 def borrower_search(req, empty_barcode, redirect_to_new_request=False,
                     ln=CFG_SITE_LANG):
     """
     Page (for administrator) where is it possible to search
     for a borrower (who is on crcBORROWER table) using his/her name,
     email, phone or id.
 
     If redirect_to_new_request is False, the returned page will be "Borrower details"
     If redirect_to_new_request is True,  the returned page will be "New Request"
     """
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     infos = []
 
     if empty_barcode:
         infos.append(empty_barcode)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                     'href="%s/help/admin">Admin Area' \
                     '</a> &gt; <a class="navtrail" ' \
                     'href="%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s">' \
                     'Circulation Management' \
                     '</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
 
     body = bc_templates.tmpl_borrower_search(infos=infos,
                                 redirect_to_new_request=redirect_to_new_request,
                                 ln=ln)
 
     if redirect_to_new_request:
         title = _("New Request")
     else:
         title = _("Borrower Search")
 
     return page(title=title,
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def borrower_search_result(req, column, string, redirect_to_new_request=False,
                            ln=CFG_SITE_LANG):
     """
     Search a borrower and return a list with all the possible results.
 
     @type column:  string
     @param column: identify the column, of the table crcBORROWER, that will be
                    considered during the search. Can be 'name', 'email' or 'id'.
 
     @type string:  string
     @param string: string used for the search process.
 
     If redirect_to_new_request is True,  the returned page will be "Borrower details"
     If redirect_to_new_request is False, the returned page will be "New Request"
 
     """
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     if string == '':
         message = _('Empty string.') + ' ' + _('Please, try again.')
         return borrower_search(req, message, redirect_to_new_request, ln)
     else:
         result = search_user(column, string)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a> &gt; <a class="navtrail" ' \
                               'href="%s/admin2/bibcirculation/bibcirculationadmin.py/loan_on_desk_step1">Circulation Management' \
                               '</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     if len(result) == 1:
         if redirect_to_new_request:
             return create_new_request_step1(req, result[0][0])
 
         else:
             return get_borrower_details(req, result[0][0], False, ln)
             #return create_new_request_step1(req, borrower_id, p, f, search, ln)
     else:
         body = bc_templates.tmpl_borrower_search_result(result=result,
                                 redirect_to_new_request=redirect_to_new_request,
                                 ln=ln)
 
         return page(title=_("Borrower search result"),
                     uid=id_user,
                     req=req,
                     body=body,
                     language=ln,
                     navtrail=navtrail_previous_links,
                     lastupdated=__lastupdated__)
 
 
 def item_search(req, infos=[], ln=CFG_SITE_LANG):
     """
     Display a form where is possible to searh for an item.
     """
 
     navtrail_previous_links = '<a class="navtrail" ' \
                     'href="%s/help/admin">Admin Area' \
                     '</a> &gt; <a class="navtrail" ' \
                     'href="%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s">' \
                     'Circulation Management' \
                     '</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
 
     _ = gettext_set_language(ln)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     body = bc_templates.tmpl_item_search(infos=infos, ln=ln)
 
     return page(title=_("Item search"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def item_search_result(req, p, f, ln=CFG_SITE_LANG):
     """
     Search an item and return a list with all the possible results. To retrieve
     the information desired, we use the method 'perform_request_search' (from
     search_engine.py). In the case of BibCirculation, we are just looking for
     books (items) inside the collection 'Books'.
 
     @type p:   string
     @param p:  search pattern
 
     @type f:   string
     @param f:  search field
 
     """
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     infos = []
 
     if p == '':
         infos.append(_('Empty string.') + ' ' + _('Please, try again.'))
         return item_search(req, infos, ln)
 
     if f == 'barcode':
         p = p.strip('\'" \t')
         recid = db.get_recid(p)
 
         if recid is None:
             infos.append(_('The barcode %(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s does not exist on BibCirculation database.') % {'x_barcode': p, 'x_strong_tag_open': '<strong>', 'x_strong_tag_close': '</strong>'})
             body = bc_templates.tmpl_item_search(infos=infos, ln=ln)
         else:
             return get_item_details(req, recid, ln=ln)
 
     elif f == 'recid':
         p = p.strip('\'" \t')
         recid = p
 
         if not record_exists(recid):
             infos.append(_("Requested record does not seem to exist."))
             body = bc_templates.tmpl_item_search(infos=infos, ln=ln)
         else:
             return get_item_details(req, recid, ln=ln)
 
     else:
         result = perform_request_search(cc="Books", sc="1", p=p, f=f)
         body = bc_templates.tmpl_item_search_result(result=result, ln=ln)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                     'href="%s/help/admin">Admin Area' \
                     '</a> &gt; <a class="navtrail" ' \
                     'href="%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s">' \
                     'Circulation Management' \
                     '</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
 
     return page(title=_("Item search result"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def load_template(template):
     """
     Load a letter/notification template from
     bibcirculation_config.py.
 
     @type template:  string.
     @param template: template that will be used.
 
     @return:         template(string)
     """
 
     if template == "overdue_letter":
         output = CFG_BIBCIRCULATION_TEMPLATES['OVERDUE']
 
     elif template == "reminder":
         output = CFG_BIBCIRCULATION_TEMPLATES['REMINDER']
 
     elif template == "notification":
         output = CFG_BIBCIRCULATION_TEMPLATES['NOTIFICATION']
 
     elif template == "claim_return":
         output = CFG_BIBCIRCULATION_TEMPLATES['SEND_RECALL']
 
     else:
         output = CFG_BIBCIRCULATION_TEMPLATES['EMPTY']
 
     return output
 
 
 
 def borrower_notification(req, borrower_id, borrower_email, template, message,
                           load_msg_template, subject, send_message,
                           ln=CFG_SITE_LANG):
     """
     Send a message/email to a borrower.
 
     @type borrower_id:   integer.
     @param borrower_id:  identify the borrower. It is also the primary key of
                          the table crcBORROWER.
 
     @type borrower_email:   string.
     @param borrower_email:  The librarian can change the email manually.
                             In that case, this value will be taken instead
                             of the borrower details email
 
     @type template:      string.
     @param template:     identify the template that will be used in the notification.
 
     @type message:       string.
     @param message:      message written by the administrator.
 
     @type subject:       string.
     @param subject:      subject of the message.
 
     @return:             send a message/email to a borrower.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     if borrower_email != None:
         email = borrower_email
     else:
         email = db.get_borrower_email(borrower_id)
 
     if load_msg_template and template is not None:
         show_template = load_template(template)
 
     elif send_message:
         send_email(fromaddr = CFG_BIBCIRCULATION_LIBRARIAN_EMAIL,
                    toaddr   = email,
                    subject  = subject,
                    content  = message,
                    header   = '',
                    footer   = '',
                    attempt_times = 1,
                    attempt_sleeptime = 10
                    )
         body = bc_templates.tmpl_send_notification(ln=ln)
 
     else:
         show_template = load_template(template)
         body = bc_templates.tmpl_borrower_notification(email=email,
                                                        subject=subject,
                                                        email_body=show_template,
                                                        borrower_id=borrower_id,
                                                        ln=ln)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a> &gt; <a class="navtrail" ' \
                               'href="%s/admin2/bibcirculation/bibcirculationadmin.py/loan_on_desk_step1">Circulation Management' \
                               '</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     return page(title="Borrower Notification",
                  uid=id_user,
                  req=req,
                  body=body, language=ln,
                  navtrail=navtrail_previous_links,
                  lastupdated=__lastupdated__)
 
 
 
 def get_next_waiting_loan_request(req, recid, barcode, check_id,
                                   ln=CFG_SITE_LANG):
     """
     *** Obsolete and unmantained function ***
     Return the next loan request that is waiting or pending.
 
     @type recid:     integer.
     @param recid:    identify the record. It is also the primary key of
                      the table bibrec.
 
     @type barcode:   string.
     @param barcode:  identify the item. It is the primary key of the table
                      crcITEM.
 
     @type check_id:  integer.
     @param check_id: identify the hold request. It is also the primary key
                      of the table crcLOANREQUEST.
 
     @return:         list of waiting requests with the same recid.
     """
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     if check_id:
         db.update_loan_request_status(check_id,
                                     CFG_BIBCIRCULATION_REQUEST_STATUS_CANCELLED)
         #update_request_data(check_id)
     else:
         db.update_item_status(CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF, barcode)
         db.return_loan(barcode)
 
     update_requests_statuses(barcode)
 
     result = db.get_next_waiting_loan_request(recid)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a> &gt; <a class="navtrail" ' \
                               'href="%s/admin2/bibcirculation/bibcirculationadmin.py/loan_on_desk_step1">Circulation Management' \
                               '</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL)
 
 
     body = bc_templates.tmpl_get_next_waiting_loan_request(result=result,
                                                             recid=recid,
                                                             barcode=barcode,
                                                             ln=ln)
 
     return page(title=_("Next requests"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def make_new_loan_from_request(req, check_id, barcode, ln=CFG_SITE_LANG):
     """
     Turns a request into a loan.
 
     @type check_id:  integer.
     @param check_id: identify the hold request. It is also the primary key
                      of the table crcLOANREQUEST.
 
     @type barcode:   string.
     @param barcode:  identify the item. It is the primary key of the table
                      crcITEM.
     """
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     infos = []
 
     recid = db.get_request_recid(check_id)
     borrower_id = db.get_request_borrower_id(check_id)
     borrower_info = db.get_borrower_details(borrower_id)
 
     due_date = renew_loan_for_X_days(barcode)
     if db.is_item_on_loan(barcode):
         infos.append('The item with the barcode %(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s is on loan.' % {'x_barcode': barcode, 'x_strong_tag_open': '<strong>', 'x_strong_tag_close': '</strong>'})
         return redirect_to_url(req,
             '%s/admin2/bibcirculation/all_loans?ln=%s&msg=ok' % (CFG_SITE_SECURE_URL, ln))
     else:
         db.new_loan(borrower_id, recid, barcode, due_date,
                     CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN, 'normal', '')
         infos.append(_('A new loan has been registered with success.'))
         #try:
         #    register_customevent("baskets", ["display", "", user_str])
         #except:
         #    register_exception(suffix="Do the webstat tables exists? Try with 'webstatadmin --load-config'")
 
     tag_all_requests_as_done(barcode, borrower_id)
     db.update_item_status(CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN, barcode)
     update_requests_statuses(barcode)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                     'href="%s/help/admin">Admin Area' \
                     '</a> &gt; <a class="navtrail" ' \
                     'href="%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s">' \
                     'Circulation Management' \
                     '</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
 
     body = bc_templates.tmpl_register_new_loan(borrower_info=borrower_info,
                                                infos=infos,
                                                recid=recid,
                                                ln=ln)
 
     return page(title=_("New Loan"),
                 uid=id_user,
                 req=req,
                 body=body,
                 language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def loan_return(req, ln=CFG_SITE_LANG):
     """
     Page where is possible to register the return of an item.
     """
 
     _ = gettext_set_language(ln)
 
     infos = []
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a> &gt; <a class="navtrail" ' \
                               'href="%s/admin2/bibcirculation/bibcirculationadmin.py/loan_on_desk_step1">Circulation Management' \
                               '</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     body = bc_templates.tmpl_loan_return(infos=infos, ln=ln)
 
     return page(title=_("Loan return"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def loan_return_confirm(req, barcode, ln=CFG_SITE_LANG):
     """
     Performs the return of a loan and displays a confirmation page.
     In case the book is requested, it is possible to select a request
     and make a loan from it (make_new_loan_from_request)
 
     @type barcode:   string.
     @param barcode:  identify the item. It is the primary key of the table
                      crcITEM.
     """
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     infos = []
     _ = gettext_set_language(ln)
 
     recid   = db.get_id_bibrec(barcode)
     loan_id = db.is_item_on_loan(barcode)
 
     if recid is None:
         infos.append(_('%(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s Unknown barcode.') % {'x_barcode': barcode, 'x_strong_tag_open': '<strong>', 'x_strong_tag_close': '</strong>'} + ' ' + _('Please, try again.'))
         body = bc_templates.tmpl_loan_return(infos=infos, ln=ln)
 
     elif loan_id is None:
         message = _("The item the with barcode %(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s is not on loan. Please, try again.") % {'x_barcode': barcode, 'x_strong_tag_open': '<strong>', 'x_strong_tag_close': '</strong>'}
 
         infos.append(message)
         body = bc_templates.tmpl_loan_return(infos=infos, ln=ln)
 
     else:
 
         library_id = db.get_item_info(barcode)[1]
         if CFG_CERN_SITE:
             library_type = db.get_library_type(library_id)
             if library_type != CFG_BIBCIRCULATION_LIBRARY_TYPE_MAIN:
                 library_name = db.get_library_name(library_id)
                 message = _("%(x_strong_tag_open)sWARNING:%(x_strong_tag_close)s Note that item %(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s location is %(x_strong_tag_open)s%(x_location)s%(x_strong_tag_close)s") % {'x_barcode': barcode, 'x_strong_tag_open': '<strong>', 'x_strong_tag_close': '</strong>', 'x_location': library_name}
                 infos.append(message)
 
         borrower_id = db.get_borrower_id(barcode)
         borrower_name = db.get_borrower_name(borrower_id)
 
         db.update_item_status(CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF, barcode)
         db.return_loan(barcode)
 
         update_requests_statuses(barcode)
 
         result = db.get_next_waiting_loan_request(recid)
         body = bc_templates.tmpl_loan_return_confirm(
                                             infos=infos,
                                             borrower_name=borrower_name,
                                             borrower_id=borrower_id,
                                             recid=recid,
                                             barcode=barcode,
                                             return_date=datetime.date.today(),
                                             result=result,
                                             ln=ln)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     return page(title=_("Loan return"),
                 uid=id_user,
                 req=req,
                 body=body,
                 language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def loan_on_desk_step1(req, key, string, ln=CFG_SITE_LANG):
     """
     Step 1/4 of loan procedure.
     Search a user/borrower and return a list with all the possible results.
 
     @type key:     string.
     @param key:    attribute that will be considered during the search. Can be 'name',
                    'email' or 'ccid/id'.
 
     @type string:  string.
     @param string: keyword used during the search.
 
     @return:       list of potential borrowers.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     infos = []
     _ = gettext_set_language(ln)
 
     if key and not string:
         infos.append(_('Empty string. Please, try again.'))
         body = bc_templates.tmpl_loan_on_desk_step1(result=None, key=key,
                                                     string=string, infos=infos,
                                                     ln=ln)
 
         navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
         return page(title=_("Loan on desk"),
                     uid=id_user,
                     req=req,
                     body=body, language=ln,
                     navtrail=navtrail_previous_links,
                     lastupdated=__lastupdated__)
 
     result = search_user(key, string)
     borrowers_list = []
 
     if len(result) == 0 and key:
         if CFG_CERN_SITE:
             infos.append(_("0 borrowers found.") + ' ' +_("Search by CCID."))
         else:
             new_borrower_link = create_html_link(CFG_SITE_SECURE_URL +
                                 '/admin2/bibcirculation/add_new_borrower_step1',
                                 {'ln': ln}, _("Register new borrower."))
             message = _("0 borrowers found.") + ' ' + new_borrower_link
             infos.append(message)
     elif len(result) == 1:
         return loan_on_desk_step2(req, result[0][0], ln)
     else:
         for user in result:
             borrower_data = db.get_borrower_data_by_id(user[0])
             borrowers_list.append(borrower_data)
 
     body = bc_templates.tmpl_loan_on_desk_step1(result=borrowers_list,
                                                 key=key,
                                                 string=string,
                                                 infos=infos,
                                                 ln=ln)
 
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     return page(title=_("Circulation management"),
                 uid=id_user,
                 req=req,
                 body=body,
                 language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def loan_on_desk_step2(req, user_id, ln=CFG_SITE_LANG):
     """
     Step 2/4 of loan procedure.
     Display the user/borrower's information.
 
     @type user_id:  integer
     @param user_id: identify the borrower. It is also the primary key of
                     the table crcBORROWER.
 
     """
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
     infos = []
     _ = gettext_set_language(ln)
 
     body = bc_templates.tmpl_loan_on_desk_step2(user_id=user_id,
                                                 infos=infos,
                                                 ln=ln)
 
     return page(title=_("Circulation management"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def loan_on_desk_step3(req, user_id, list_of_barcodes, ln=CFG_SITE_LANG):
     """
     Step 3/4 of loan procedure.
     Checks that the barcodes exist and that there are no request on these records.
     Lets the librarian change the due dates and add notes.
 
     @type user_id:  integer
     @param user_id: identify the borrower. It is also the primary key of
                     the table crcBORROWER.
 
     @type list_of_barcodes:  list
     @param list_of_barcodes: list of strings with the barcodes
                              introduced by the librarian with the barcode reader
     """
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     infos = []
     list_of_books = []
 
     # to avoid duplicates
     aux = []
     for bc in list_of_barcodes:
         if bc not in aux:
             aux.append(bc)
     list_of_barcodes = aux
 
     for value in list_of_barcodes:
         recid = db.get_id_bibrec(value)
         loan_id = db.is_item_on_loan(value)
         queue = db.get_queue_request(recid)
 
         if recid is None:
             infos.append(_('%(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s Unknown barcode.') % {'x_barcode': value, 'x_strong_tag_open': '<strong>', 'x_strong_tag_close': '</strong>'} + ' ' + _('Please, try again.'))
             body = bc_templates.tmpl_loan_on_desk_step2(user_id=user_id,
                                                         infos=infos,
                                                         ln=ln)
         elif loan_id:
             infos.append('The item with the barcode %(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s is on loan.' % {'x_barcode': value, 'x_strong_tag_open': '<strong>', 'x_strong_tag_close': '</strong>'})
             body = bc_templates.tmpl_loan_on_desk_step2(user_id=user_id,
                                                         infos=infos,
                                                         ln=ln)
         elif user_id is None:
             infos.append(_('You must select one borrower.'))
             body = bc_templates.tmpl_loan_on_desk_step1(result=None,
                                                         key='',
                                                         string='',
                                                         infos=infos,
                                                         ln=ln)
         else:
             (library_id, location) = db.get_lib_location(value)
             tup = (recid, value, library_id, location)
             list_of_books.append(tup)
             book_details = db.get_item_info(value)
             item_status = book_details[7]
 
             if item_status != CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF:
                 message = _("%(x_strong_tag_open)sWARNING:%(x_strong_tag_close)s Note that item %(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s status is %(x_strong_tag_open)s%(x_status)s%(x_strong_tag_close)s") % {'x_barcode': value, 'x_strong_tag_open': '<strong>', 'x_strong_tag_close': '</strong>', 'x_status': item_status}
 
                 infos.append(message)
 
             if CFG_CERN_SITE:
                 library_type = db.get_library_type(library_id)
                 if library_type != CFG_BIBCIRCULATION_LIBRARY_TYPE_MAIN:
                     library_name = db.get_library_name(library_id)
                     message = _("%(x_strong_tag_open)sWARNING:%(x_strong_tag_close)s Note that item %(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s location is %(x_strong_tag_open)s%(x_location)s%(x_strong_tag_close)s") % {'x_barcode': value, 'x_strong_tag_open': '<strong>', 'x_strong_tag_close': '</strong>', 'x_location': library_name}
                     infos.append(message)
 
             if len(queue) != 0  and  queue[0][0] != user_id:
                 message = _("Another user is waiting for the book: %(x_strong_tag_open)s%(x_title)s%(x_strong_tag_close)s. \n\n If you want continue with this loan choose %(x_strong_tag_open)s[Continue]%(x_strong_tag_close)s.") % {'x_title': book_title_from_MARC(recid), 'x_strong_tag_open': '<strong>', 'x_strong_tag_close': '</strong>'}
                 infos.append(message)
 
             body = bc_templates.tmpl_loan_on_desk_step3(user_id=user_id,
                                                     list_of_books=list_of_books,
                                                     infos=infos, ln=ln)
 
     if list_of_barcodes == []:
         infos.append(_('Empty barcode.') + ' ' + _('Please, try again.'))
         body = bc_templates.tmpl_loan_on_desk_step2(user_id=user_id,
                                                     infos=infos,
                                                     ln=ln)
 
     if infos == []:
         # shortcut to simplify loan process
         due_dates = []
         for bc in list_of_barcodes:
             due_dates.append(renew_loan_for_X_days(bc))
 
         return loan_on_desk_step4(req, list_of_barcodes, user_id,
                        due_dates, None, ln)
 
     else:
         return page(title=_("Circulation management"),
                 uid=id_user,
                 req=req,
                 body=body,
                 metaheaderadd = "<link rel=\"stylesheet\" href=\"%s/img/jquery/jquery-ui.css\" type=\"text/css\" />" % CFG_SITE_SECURE_URL,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def loan_on_desk_step4(req, list_of_barcodes, user_id,
                        due_date, note, ln=CFG_SITE_LANG):
     """
     Step 4/4 of loan procedure.
     Checks that items are not on loan and that the format of
     the dates is correct and creates the loans
 
     @type user_id:           integer
     @param user_id:          identify the borrower. It is also the primary key of
                              the table crcBORROWER.
 
     @type list_of_barcodes:  list
     @param list_of_barcodes: list of strings with the barcodes
                              introduced by the librarian with the barcode reader
 
     @type due_date:          list.
     @param due_date:         list of due dates.
 
     @type note:              string.
     @param note:             note about the new loan.
 
     @return:                 page with the list 'Last Loans'
     """
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     infos = []
 
     #loaned_on = datetime.date.today()
 
     #Check if one of the given items is on loan.
     on_loan = []
     for barcode in list_of_barcodes:
         is_on_loan = db.is_item_on_loan(barcode)
         if is_on_loan:
             on_loan.append(barcode)
 
     if len(on_loan) != 0:
         message = _("The items with barcode %(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s are already on loan.") % {'x_barcode': on_loan, 'x_strong_tag_open': '<strong>', 'x_strong_tag_close': '</strong>'}
         infos.append(message)
 
         body = bc_templates.tmpl_loan_on_desk_step1(result=None, key='',
                                                     string='', infos=infos,
                                                     ln=ln)
 
         return page(title=_("Loan on desk"),
                     uid=id_user,
                     req=req,
                     body=body, language=ln,
                     navtrail=navtrail_previous_links,
                     lastupdated=__lastupdated__)
 
     # validate the period of interest given by the admin
     for date in due_date:
         if validate_date_format(date) is False:
             infos = []
             message = _("The given due date %(x_strong_tag_open)s%(x_date)s%(x_strong_tag_close)s is not a valid date or date format") % {'x_date': date, 'x_strong_tag_open': '<strong>', 'x_strong_tag_close': '</strong>'}
 
             infos.append(message)
 
             list_of_books = []
             for bc in list_of_barcodes:
                 recid = db.get_id_bibrec(bc)
                 (library_id, location) = db.get_lib_location(bc)
                 tup = (recid, bc, library_id, location)
                 list_of_books.append(tup)
 
             body = bc_templates.tmpl_loan_on_desk_step3(user_id=user_id,
                                                     list_of_books=list_of_books,
                                                     infos=infos, ln=ln)
 
             return page(title=_("Circulation management"),
                         uid=id_user,
                         req=req,
                         body=body, language=ln,
                         navtrail=navtrail_previous_links,
                         lastupdated=__lastupdated__)
 
     #if borrower_id == None:
     #    db.new_borrower(ccid, name, email, phone, address, mailbox, '')
     #    borrower_id = db.get_borrower_id_by_email(email)
 
     for i in range(len(list_of_barcodes)):
         note_format = {}
         if note:
             note_format[time.strftime("%Y-%m-%d %H:%M:%S")] = str(note)
         barcode = list_of_barcodes[i]
         recid = db.get_recid(barcode)
         db.new_loan(user_id, recid, barcode, due_date[i],
                     CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN,
                     'normal', note_format)
 
         tag_all_requests_as_done(barcode, user_id)
         db.update_item_status(CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN, barcode)
         update_requests_statuses(barcode)
 
     return redirect_to_url(req,
             '%s/admin2/bibcirculation/all_loans?ln=%s&msg=ok' % (CFG_SITE_SECURE_URL, ln))
 
 
 def loan_on_desk_confirm(req, barcode=None, borrower_id=None, ln=CFG_SITE_LANG):
     """
     *** Obsolete and unmantained function ***
     Confirm the return of an item.
 
     @type barcode:       string.
     @param barcode:      identify the item. It is the primary key of the table
                          crcITEM.
 
     @type borrower_id:   integer.
     @param borrower_id:  identify the borrower. It is also the primary key of
                          the table crcBORROWER.
     """
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     result = db.loan_on_desk_confirm(barcode, borrower_id)
 
     body = bc_templates.tmpl_loan_on_desk_confirm(result=result,
                                                   barcode=barcode,
                                                   borrower_id=borrower_id,
                                                   ln=ln)
 
     return page(title=_("Loan on desk confirm"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def register_new_loan(req, barcode, borrower_id,
                       request_id, new_note, print_data, ln=CFG_SITE_LANG):
     """
     Register a new loan. This function is from the "Associate barcode" pages.
 
     @type barcode:       string.
     @param barcode:      identify the item. It is the primary key of the table
                          crcITEM.
 
     @type borrower_id:   integer.
     @param borrower_id:  identify the borrower. It is also the primary key of
                          the table crcBORROWER.
 
     @type request_id:    integer.
     @param request_id:   identify the hold request. It is also the primary key
                          of the table crcLOANREQUEST.
 
     @type new_note:     string.
     @param new_note:    associate a note to this loan.
 
     @type print_data:   string.
     @param print_data:  print the information about this loan.
 
     @return:            new loan
     """
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     has_recid = db.get_id_bibrec(barcode)
     loan_id = db.is_item_on_loan(barcode)
 
     recid = db.get_request_recid(request_id)
     list_of_barcodes = db.get_barcodes(recid)
 
     infos = []
 
     if print_data == 'true':
         return print_new_loan_information(req, ln)
 
     else:
         if has_recid is None:
             message = _('%(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s Unknown barcode.') % {'x_barcode': barcode, 'x_strong_tag_open': '<strong>', 'x_strong_tag_close': '</strong>'} + ' ' + _('Please, try again.')
             infos.append(message)
             borrower = db.get_borrower_details(borrower_id)
             title = _("Associate barcode")
             body = bc_templates.tmpl_associate_barcode(request_id=request_id,
                                                        recid=recid,
                                                        borrower=borrower,
                                                        infos=infos,
                                                        ln=ln)
 
         elif loan_id:
             infos.append(_('The item with the barcode %(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s is on loan.') % {'x_barcode': barcode, 'x_strong_tag_open': '<strong>', 'x_strong_tag_close': '</strong>'})
             borrower = db.get_borrower_details(borrower_id)
             title = _("Associate barcode")
             body = bc_templates.tmpl_associate_barcode(request_id=request_id,
                                                         recid=recid,
                                                         borrower=borrower,
                                                         infos=infos,
                                                         ln=ln)
 
         elif barcode not in list_of_barcodes:
             infos.append(_('The given barcode "%(x_barcode)s" does not correspond to requested item.') % {'x_barcode': barcode})
             borrower = db.get_borrower_details(borrower_id)
             title = _("Associate barcode")
             body = bc_templates.tmpl_associate_barcode(request_id=request_id,
                                                         recid=recid,
                                                         borrower=borrower,
                                                         infos=infos,
                                                         ln=ln)
 
         else:
             recid = db.get_id_bibrec(barcode)
             #loaned_on = datetime.date.today()
             due_date = renew_loan_for_X_days(barcode)
 
             if new_note:
                 note_format = '[' + time.ctime() + '] ' + new_note + '\n'
             else:
                 note_format = ''
 
             last_id = db.new_loan(borrower_id, recid, barcode,
                         due_date, CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN,
                         'normal', note_format)
             # register event in webstat
             try:
                 register_customevent("loanrequest", [request_id, last_id])
             except:
                 register_exception(suffix="Do the webstat tables exists? Try with 'webstatadmin --load-config'")
-            requested_barcode = db.get_requested_barcode(request_id)
+            #requested_barcode = db.get_requested_barcode(request_id)
 
             tag_all_requests_as_done(barcode, borrower_id)
 
             db.update_item_status(CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN, barcode)
 
             db.update_loan_request_status(request_id,
                                         CFG_BIBCIRCULATION_REQUEST_STATUS_DONE)
             db.update_request_barcode(barcode, request_id)
             update_requests_statuses(barcode)
 
             result = db.get_all_loans(20)
 
             infos.append(_('A new loan has been registered with success.'))
 
             title = _("Current loans")
             body = bc_templates.tmpl_all_loans(result=result,
                                                        infos=infos,
                                                        ln=ln)
 
         navtrail_previous_links = '<a class="navtrail" ' \
                                   'href="%s/help/admin">Admin Area' \
                                   '</a>' % (CFG_SITE_SECURE_URL,)
 
         return page(title=title,
                     uid=id_user,
                     req=req,
                     body=body, language=ln,
                     navtrail=navtrail_previous_links,
                     lastupdated=__lastupdated__)
 
 
 def get_borrower_details(req, borrower_id, update, ln=CFG_SITE_LANG):
     """
     Display the details of a borrower.
 
     @type borrower_id:   integer.
     @param borrower_id:  identify the borrower. It is also the primary key of
                          the table crcBORROWER.
     """
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     if update and CFG_CERN_SITE:
         update_user_info_from_ldap(borrower_id)
 
     borrower = db.get_borrower_details(borrower_id)
     if borrower == None:
         info = _('Borrower not found.') + ' ' + _('Please, try again.')
         return borrower_search(req, info, False, ln)
 
     else:
         requests = db.get_borrower_request_details(borrower_id)
         loans = db.get_borrower_loan_details(borrower_id)
         notes = db.get_borrower_notes(borrower_id)
         ill = db.get_ill_requests_details(borrower_id)
 
         req_hist = db.bor_requests_historical_overview(borrower_id)
         loans_hist = db.bor_loans_historical_overview(borrower_id)
         ill_hist = db.bor_ill_historical_overview(borrower_id)
 
         navtrail_previous_links = '<a class="navtrail" ' \
                                   'href="%s/help/admin">Admin Area' \
                                   '</a>' % (CFG_SITE_SECURE_URL,)
 
         body = bc_templates.tmpl_borrower_details(borrower=borrower,
                                                   requests=requests,
                                                   loans=loans,
                                                   notes=notes,
                                                   ill=ill,
                                                   req_hist=req_hist,
                                                   loans_hist=loans_hist,
                                                   ill_hist=ill_hist,
                                                   ln=ln)
 
         return page(title=_("Borrower details"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def get_borrower_loans_details(req, recid, barcode, borrower_id,
                                renewall, force, loan_id, ln=CFG_SITE_LANG):
     """
     Show borrower's loans details.
 
     @type recid:         integer.
     @param recid:        identify the record. It is also the primary key of
                          the table bibrec.
 
     @type barcode:       string.
     @param barcode:      identify the item. It is the primary key of the table
                          crcITEM.
 
     @type borrower_id:   integer.
     @param borrower_id:  identify the borrower. It is also the primary key of
                          the table crcBORROWER.
 
     @type renewall:      string.
     @param renewall:     renew all loans.
 
     @type force:         string.
     @param force:        force the renew of a loan, when usually this is not possible.
 
     @type loan_id:       integer.
     @param loan_id:      identify a loan. It is the primery key of the table
                          crcLOAN.
 
     @return:             borrower loans details.
     """
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     infos = []
 
     force_renew_link = create_html_link(CFG_SITE_SECURE_URL +
                         '/admin2/bibcirculation/get_borrower_loans_details',
                         {'barcode': barcode, 'borrower_id': borrower_id,
                          'loan_id': loan_id, 'force': 'true', 'ln': ln},
                         (_("Yes")))
 
     no_renew_link = create_html_link(CFG_SITE_SECURE_URL +
                         '/admin2/bibcirculation/get_borrower_loans_details',
                         {'borrower_id': borrower_id, 'ln': ln},
                         (_("No")))
 
     if barcode and loan_id and recid:
         queue = db.get_queue_request(recid)
         new_due_date = renew_loan_for_X_days(barcode)
 
         if len(queue) != 0:
             title = book_title_from_MARC(recid)
             message = _("Another user is waiting for this book %(x_strong_tag_open)s%(x_title)s%(x_strong_tag_close)s.") % {'x_title': title, 'x_strong_tag_open': '<strong>', 'x_strong_tag_close': '</strong>'}
             message += '\n\n'
             message += _("Do you want renew this loan anyway?")
             message += '\n\n'
             message += "[%s] [%s]" % (force_renew_link, no_renew_link)
             infos.append(message)
 
         else:
             #db.update_due_date(loan_id, new_due_date)
             db.renew_loan(loan_id, new_due_date)
             #update_status_if_expired(loan_id)
             infos.append(_("Loan renewed with success."))
 
     elif loan_id and barcode and force == 'true':
         new_due_date = renew_loan_for_X_days(barcode)
         db.renew_loan(loan_id, new_due_date)
         update_status_if_expired(loan_id)
         infos.append(_("Loan renewed with success."))
 
     elif borrower_id and renewall=='true':
         list_of_loans = db.get_recid_borrower_loans(borrower_id)
         for (loan_id, recid, barcode) in list_of_loans:
             queue = db.get_queue_request(recid)
             new_due_date = renew_loan_for_X_days(barcode)
 
             force_renewall_link = create_html_link(CFG_SITE_SECURE_URL +
                             '/admin2/bibcirculation/get_borrower_loans_details',
                             {'barcode': barcode, 'borrower_id': borrower_id,
                             'loan_id': loan_id, 'force': 'true', 'ln': ln},
                             (_("Yes")))
 
             if len(queue) != 0:
                 title = book_title_from_MARC(recid)
                 message = _("Another user is waiting for this book %(x_strong_tag_open)s%(x_title)s%(x_strong_tag_close)s.") % {'x_title': title, 'x_strong_tag_open': '<strong>', 'x_strong_tag_close': '</strong>'}
                 message += '\n\n'
                 message += _("Do you want renew this loan anyway?")
                 message += '\n\n'
                 message += "[%s] [%s]" % (force_renewall_link, no_renew_link)
                 infos.append(message)
 
             else:
                 db.renew_loan(loan_id, new_due_date)
                 update_status_if_expired(loan_id)
 
         if infos == []:
             infos.append(_("All loans renewed with success."))
 
     borrower_loans = db.get_borrower_loan_details(borrower_id)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_borrower_loans_details(
                                                 borrower_loans=borrower_loans,
                                                 borrower_id=borrower_id,
                                                 infos=infos, ln=ln)
 
     return page(title=_("Loans details") + \
                         " - %s" %(db.get_borrower_name(borrower_id)),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def get_item_loans_details(req, recid, barcode, loan_id, force,
                            ln=CFG_SITE_LANG):
     """
     Show all the details about all current loans related with a record.
 
     @type recid:      integer.
     @param recid:     identify the record. It is also the primary key of
                       the table bibrec.
 
     @type barcode:    string.
     @param barcode:   identify the item. It is the primary key of the table
                       crcITEM.
 
     @type loan_id:    integer.
     @param loan_id:   identify a loan. It is the primery key of the table
                       crcLOAN.
 
     @type force:      string.
     @param force:     force the renew of a loan, when usually this is not possible.
 
     @return:          item loans details.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     infos = []
 
     if loan_id and barcode and force == 'true':
         new_due_date = renew_loan_for_X_days(barcode)
         #db.update_due_date(loan_id, new_due_date)
         db.renew_loan(loan_id, new_due_date)
         update_status_if_expired(loan_id)
         infos.append(_("Loan renewed with success."))
 
     elif barcode:
         recid = db.get_id_bibrec(barcode)
         queue = db.get_queue_request(recid)
         new_due_date = renew_loan_for_X_days(barcode)
 
 
         force_renew_link = create_html_link(CFG_SITE_SECURE_URL +
                         '/admin2/bibcirculation/get_item_loans_details',
                        {'barcode': barcode, 'loan_id': loan_id, 'force': 'true',
                        'recid': recid, 'ln': ln}, (_("Yes")))
 
         no_renew_link = create_html_link(CFG_SITE_SECURE_URL +
                         '/admin2/bibcirculation/get_item_loans_details',
                         {'recid': recid, 'ln': ln},
                         (_("No")))
 
         if len(queue) != 0:
             title = book_title_from_MARC(recid)
             message = _("Another user is waiting for this book %(x_strong_tag_open)s%(x_title)s%(x_strong_tag_close)s.") % {'x_title': title, 'x_strong_tag_open': '<strong>', 'x_strong_tag_close': '</strong>'}
             message += '\n\n'
             message += _("Do you want renew this loan anyway?")
             message += '\n\n'
             message += "[%s] [%s]" % (force_renew_link, no_renew_link)
             infos.append(message)
         else:
             db.renew_loan(loan_id, new_due_date)
             #db.update_due_date(loan_id, new_due_date)
             update_status_if_expired(loan_id)
             infos.append(_("Loan renewed with success."))
 
     result = db.get_item_loans(recid)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_get_item_loans_details(result=result,
                                                                 recid=recid,
                                                                 infos=infos,
                                                                 ln=ln)
 
     return page(title=_("Loans details") + \
                         " - %s" % (book_title_from_MARC(int(recid))),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def get_item_details(req, recid, ln=CFG_SITE_LANG):
     """
     Display the details of an item.
 
 
     @type recid:   integer.
     @param recid:  identify the record. It is also the primary key of
                    the table bibrec.
 
     @return:       item details.
     """
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     id_user = 1
     infos = []
 
     if recid == None:
         infos.append(_("Record id not valid"))
 
     copies = db.get_item_copies_details(recid)
     requests = db.get_item_requests(recid)
     loans = db.get_item_loans(recid)
     req_hist_overview = db.get_item_requests_historical_overview(recid)
     loans_hist_overview = db.get_item_loans_historical_overview(recid)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_get_item_details(recid=recid,
                                         copies=copies,
                                         requests=requests,
                                         loans=loans,
                                         req_hist_overview=req_hist_overview,
                                         loans_hist_overview=loans_hist_overview,
                                         infos=infos,
                                         ln=ln)
 
     return page(title=_("Item details"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def get_item_req_historical_overview(req, recid, ln=CFG_SITE_LANG):
     """
     Display the requests historical overview of an item.
 
     @type recid:   integer.
     @param recid:  identify the record. It is also the primary key of
                    the table bibrec.
 
     @return:       Item requests - historical overview.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     req_hist_overview = db.get_item_requests_historical_overview(recid)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_get_item_req_historical_overview(
                                             req_hist_overview=req_hist_overview,
                                             ln=ln)
 
     return page(title=_("Requests") + " - " + _("historical overview"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def get_item_loans_historical_overview(req, recid, ln=CFG_SITE_LANG):
     """
     Display the loans historical overview of an item.
 
     @type recid:   integer.
     @param recid:  identify the record. It is also the primary key of
                    the table bibrec.
 
     @return:       Item loans - historical overview.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     loans_hist_overview = db.get_item_loans_historical_overview(recid)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_get_item_loans_historical_overview(
                                         loans_hist_overview=loans_hist_overview,
                                         ln=ln)
 
     return page(title=_("Loans") + " - " + _("historical overview"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def bor_loans_historical_overview(req, borrower_id, ln=CFG_SITE_LANG):
     """
     Display the loans historical overview of a borrower.
 
     @type borrower_id:   integer.
     @param borrower_id:  identify the borrower. It is also the primary key of
                          the table crcBORROWER.
 
     @return:             borrower loans - historical overview.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     loans_hist_overview = db.bor_loans_historical_overview(borrower_id)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_bor_loans_historical_overview(
         loans_hist_overview = loans_hist_overview,
         ln=ln)
 
     return page(title=_("Loans") + " - " + _("historical overview"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def bor_requests_historical_overview(req, borrower_id, ln=CFG_SITE_LANG):
     """
     Display the requests historical overview of a borrower.
 
     @type borrower_id:   integer.
     @param borrower_id:  identify the borrower. It is also the primary key of
                          the table crcBORROWER.
 
     @return:             borrower requests - historical overview.
     """
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     req_hist_overview = db.bor_requests_historical_overview(borrower_id)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_bor_requests_historical_overview(
         req_hist_overview = req_hist_overview,
         ln=ln)
 
     return page(title=_("Requests") + " - " + _("historical overview"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def get_library_details(req, library_id, ln=CFG_SITE_LANG):
     """
     Display the details of a library.
 
     @type library_id:    integer.
     @param library_id:   identify the library. It is also the primary key of
                          the table crcLIBRARY.
 
     @return:             library details.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               ' href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     library_details = db.get_library_details(library_id)
 
     if library_details is None:
         _ = gettext_set_language(ln)
         infos = []
         infos.append(_('Library ID not found.'))
         return search_library_step1(req, infos, ln)
 
     library_items = db.get_library_items(library_id)
 
     body = bc_templates.tmpl_library_details(library_details=library_details,
                                              library_items=library_items,
                                              ln=ln)
 
     return page(title=_("Library details"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def merge_libraries_step1(req, library_id, f=None, p=None, ln=CFG_SITE_LANG):
     """
     Step 1/3 of library merging procedure
 
     @param library_id:  ID of the library to be deleted
 
     @param p: search pattern.
 
     @param f: field
     """
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               ' href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     library_details = db.get_library_details(library_id)
     library_items = db.get_library_items(library_id)
 
     result = None
 
     if f is not None:
         if p in (None, '', '*'):
             result = db.get_all_libraries() #list of (id, name)
         elif f == 'name':
             result = db.search_library_by_name(p)
         elif f == 'email':
             result = db.search_library_by_email(p)
 
 
     body = bc_templates.tmpl_merge_libraries_step1(
                                                 library_details=library_details,
                                                 library_items=library_items,
                                                 result=result,
                                                 p=p,
                                                 ln=ln)
 
     return page(title=_("Merge libraries"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def merge_libraries_step2(req, library_from, library_to, ln=CFG_SITE_LANG):
     """
     Step 2/3 of library merging procedure
     Confirm the libraries selected
 
     @param library_from:  ID of the library to be deleted
 
     @param library_to:    ID of the resulting library
     """
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               ' href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     library_from_details = db.get_library_details(library_from)
     library_from_items   = db.get_library_items(library_from)
 
     library_to_details   = db.get_library_details(library_to)
     library_to_items     = db.get_library_items(library_to)
 
     body = bc_templates.tmpl_merge_libraries_step2(
                                     library_from_details=library_from_details,
                                     library_from_items=library_from_items,
                                     library_to_details=library_to_details,
                                     library_to_items=library_to_items,
                                     ln=ln)
 
     return page(title=_("Merge libraries"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def merge_libraries_step3(req, library_from, library_to, ln=CFG_SITE_LANG):
     """
     Step 3/3 of library merging procedure
     Perform the merge and display the details of the resulting library
 
     @param library_from:  ID of the library to be deleted
 
     @param library_to:    ID of the resulting library
     """
 
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     db.merge_libraries(library_from, library_to)
 
     return get_library_details(req, library_to, ln)
 
 
 def get_borrower_requests_details(req, borrower_id, request_id,
                                   ln=CFG_SITE_LANG):
     """
     Display loans details of a borrower.
 
     @type borrower_id:  integer.
     @param borrower_id: identify the borrower. It is also the primary key of
                         the table crcBORROWER.
 
     @type request_id:   integer.
     @param request_id:  identify the hold request to be cancelled
 
     @return:            borrower requests details.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     if request_id:
         db.cancel_request(request_id)
         #update_request_data(request_id)
 
     result = db.get_borrower_request_details(borrower_id)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     name = db.get_borrower_name(borrower_id)
 
     title = _("Hold requests details") + " - %s" % (name)
     body = bc_templates.tmpl_borrower_request_details(result=result,
                                                       borrower_id=borrower_id,
                                                       ln=ln)
 
     return page(title=title,
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def get_pending_requests(req, request_id, print_data, ln=CFG_SITE_LANG):
     """
     Get all loans requests that are pending.
 
     @type request_id:   integer.
     @param request_id:  identify the hold request. It is also the primary key
                         of the table crcLOANREQUEST.
 
     @type print_data:   string.
     @param print_data:  print requests information.
 
     @return:            list of pending requests (on shelf with hold).
     """
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     if print_data == 'true':
         return print_pending_hold_requests_information(req, ln)
 
     elif request_id:
         db.update_loan_request_status(request_id,
                                     CFG_BIBCIRCULATION_REQUEST_STATUS_CANCELLED)
         barcode = db.get_request_barcode(request_id)
         update_requests_statuses(barcode)
         result = db.get_loan_request_by_status(CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING)
 
     else:
         result = db.get_loan_request_by_status(CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_get_pending_requests(result=result, ln=ln)
 
     return page(title=_("Items on shelf with holds"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def get_waiting_requests(req, request_id, print_data, ln=CFG_SITE_LANG):
     """
     Get all loans requests that are waiting.
 
     @type request_id:   integer.
     @param request_id:  identify the hold request. It is also the primary key
                         of the table crcLOANREQUEST.
 
     @type print_data:   string.
     @param print_data:  print requests information.
 
     @return:            list of waiting requests (on loan with hold).
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     if print_data == 'true':
         return print_pending_hold_requests_information(req, ln)
 
     elif request_id:
         db.update_loan_request_status(request_id,
                                     CFG_BIBCIRCULATION_REQUEST_STATUS_CANCELLED)
 
     result = db.get_loan_request_by_status(CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING)
     aux    = ()
 
     for request in result:
         if db.get_nb_copies_on_loan(request[1]):
             aux += request,
 
     result = aux
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_get_waiting_requests(result=result, ln=ln)
 
     return page(title=_("Items on loan with holds"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def all_requests(req, request_id, ln=CFG_SITE_LANG):
     """
     Display all requests.
 
     @type request_id:   integer.
     @param request_id:  identify the hold request. It is also the primary key
                         of the table crcLOANREQUEST.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     if request_id:
         db.update_loan_request_status(request_id,
                                     CFG_BIBCIRCULATION_REQUEST_STATUS_CANCELLED)
         #update_request_data(request_id)
         result = db.get_all_requests()
     else:
         result = db.get_all_requests()
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_all_requests(result=result, ln=ln)
 
     return page(title=_("List of hold requests"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def all_loans(req, msg=None, ln=CFG_SITE_LANG):
     """
     Display all loans.
 
     @type loans_per_page:   integer.
     @param loans_per_page:  number of loans per page.
 
     @type jloan:            integer.
     @param jloan:           jump to next loan.
 
     @return:                list with all loans (current loans).
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     infos = []
 
     if msg == 'ok':
         infos.append(_('A new loan has been registered with success.'))
 
     result = db.get_all_loans(20)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                     'href="%s/help/admin">Admin Area' \
                     '</a> &gt; <a class="navtrail" ' \
                     'href="%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s">' \
                     'Circulation Management' \
                     '</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
 
     body = bc_templates.tmpl_all_loans(result=result, infos=infos, ln=ln)
 
     return page(title=_("Current loans"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def all_expired_loans(req, ln=CFG_SITE_LANG):
     """
     Display all loans.
 
     @type loans_per_page:   integer.
     @param loans_per_page:  number of loans per page.
 
     @return:                list with all expired loans (overdue loans).
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     result = db.get_all_expired_loans()
 
     infos = []
 
     navtrail_previous_links = '<a class="navtrail" ' \
                     'href="%s/help/admin">Admin Area' \
                     '</a> &gt; <a class="navtrail" ' \
                     'href="%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s">' \
                     'Circulation Management' \
                     '</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
 
     body = bc_templates.tmpl_all_expired_loans(result=result,
                                                infos=infos,
                                                ln=ln)
 
     return page(title=_('Overdue loans'),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def get_item_requests_details(req, recid, request_id, ln=CFG_SITE_LANG):
     """
     Display all requests for a specific item.
 
     @type recid:         integer.
     @param recid:        identify the record. It is also the primary key of
                          the table bibrec.
 
     @type request_id:    integer.
     @param request_id:   identify the hold request. It is also the primary key
                          of the table crcLOANREQUEST.
 
     @return:             Item requests details.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     if request_id:
         db.cancel_request(request_id)
         #update_request_data(request_id)
 
     result = db.get_item_requests(recid)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_get_item_requests_details(recid=recid,
                                                        result=result,
                                                        ln=ln)
 
     return page(title=_("Hold requests") + \
                         " - %s" % (book_title_from_MARC(recid)),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def associate_barcode(req, request_id, recid, borrower_id, ln=CFG_SITE_LANG):
     """
     Associate a barcode to an hold request.
 
     @type request_id:     integer.
     @param request_id:    identify the hold request. It is also the primary key
                           of the table crcLOANREQUEST.
 
     @type recid:          integer.
     @param recid:         identify the record. It is also the primary key of
                           the table bibrec.
 
     @type borrower_id:    integer.
     @param borrower_id:   identify the borrower. It is also the primary key of
                           the table crcBORROWER.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     borrower = db.get_borrower_details(borrower_id)
     infos = []
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_associate_barcode(request_id=request_id,
                                                            recid=recid,
                                                            borrower=borrower,
                                                            infos=infos,
                                                            ln=ln)
 
     return page(title=_("Associate barcode"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def get_borrower_notes(req, borrower_id, delete_key, library_notes,
                        ln=CFG_SITE_LANG):
     """
     Retrieve the notes of a borrower.
 
     @type borrower_id:    integer.
     @param borrower_id:   identify the borrower. It is also the primary key of
                           the table crcBORROWER.
 
    """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     if delete_key and borrower_id:
         borrower_notes = eval(db.get_borrower_notes(borrower_id))
         if delete_key in borrower_notes.keys():
             del borrower_notes[delete_key]
             db.update_borrower_notes(borrower_id, borrower_notes)
 
     elif library_notes:
         if db.get_borrower_notes(borrower_id):
             borrower_notes = eval(db.get_borrower_notes(borrower_id))
         else:
             borrower_notes = {}
 
         note_time = time.strftime("%Y-%m-%d %H:%M:%S")
         if note_time not in borrower_notes.keys():
             borrower_notes[note_time] = str(library_notes)
             db.update_borrower_notes(borrower_id, borrower_notes)
 
     borrower_notes = db.get_borrower_notes(borrower_id)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                     'href="%s/help/admin">Admin Area' \
                     '</a> &gt; <a class="navtrail" ' \
                     'href="%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s">' \
                     'Circulation Management' \
                     '</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
 
     body = bc_templates.tmpl_borrower_notes(borrower_notes=borrower_notes,
                                             borrower_id=borrower_id,
                                             ln=ln)
 
     return page(title=_("Borrower notes"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def get_loans_notes(req, loan_id, delete_key,
                     library_notes, back, ln=CFG_SITE_LANG):
     """
     Get loan's note(s).
 
     @type loan_id:       integer.
     @param loan_id:      identify a loan. It is the primery key of the table
                          crcLOAN.
 
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     if delete_key and loan_id:
         loans_notes = eval(db.get_loan_notes(loan_id))
         if delete_key in loans_notes.keys():
             del loans_notes[delete_key]
             db.update_loan_notes(loan_id, loans_notes)
 
     elif library_notes:
         if db.get_loan_notes(loan_id):
             loans_notes = eval(db.get_loan_notes(loan_id))
         else:
             loans_notes = {}
 
         note_time = time.strftime("%Y-%m-%d %H:%M:%S")
         if note_time not in loans_notes.keys():
             loans_notes[note_time] = str(library_notes)
             db.update_loan_notes(loan_id, loans_notes)
 
     loans_notes = db.get_loan_notes(loan_id)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                     'href="%s/help/admin">Admin Area' \
                     '</a> &gt; <a class="navtrail" ' \
                     'href="%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s">' \
                     'Circulation Management' \
                     '</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
 
     referer = req.headers_in.get('referer')
 
     body = bc_templates.tmpl_get_loans_notes(loans_notes=loans_notes,
                                             loan_id=loan_id,
                                             referer=referer, back=back,
                                             ln=ln)
     return page(title=_("Loan notes"),
                 uid=id_user,
                 req=req,
                 body=body,
                 language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def add_new_borrower_step1(req, ln=CFG_SITE_LANG):
     """
     Add new borrower. Step 1
     """
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     body = bc_templates.tmpl_add_new_borrower_step1(ln=ln)
 
     return page(title=_("Add new borrower") + " - I",
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def add_new_borrower_step2(req, name, email, phone, address, mailbox,
                            notes, ln=CFG_SITE_LANG):
     """
     Add new borrower. Step 2.
 
     @type name:     string.
     @type email:    string.
     @type phone:    string.
     @type address:  string.
     @type mailbox:  string.
     @type notes:    string.
     """
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     infos = []
 
     if name == '':
         infos.append(_("Please, insert a name"))
 
     if email == '':
         infos.append(_("Please, insert a valid email address"))
     else:
         borrower_id = db.get_borrower_id_by_email(email)
         if borrower_id is not None:
             infos.append(_("There is already a borrower using the following email:")
                          + " <strong>%s</strong>" % (email))
 
     tup_infos = (name, email, phone, address, mailbox, notes)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     if len(infos) > 0:
         body = bc_templates.tmpl_add_new_borrower_step1(tup_infos=tup_infos,
                                                         infos=infos, ln=ln)
         title = _("Add new borrower") + " - I"
     else:
         if notes != '':
             borrower_notes = {}
             note_time = time.strftime("%Y-%m-%d %H:%M:%S")
             borrower_notes[note_time] = notes
         else:
             borrower_notes = ''
 
         borrower_id = db.new_borrower(None, name, email, phone,
                                       address, mailbox, borrower_notes)
 
         return redirect_to_url(req,
             '%s/admin2/bibcirculation/get_borrower_details?ln=%s&borrower_id=%s' \
                                             % (CFG_SITE_SECURE_URL, ln, borrower_id))
 
 
         #body = bc_templates.tmpl_add_new_borrower_step2(tup_infos=tup_infos,
         #                                                infos=infos, ln=ln)
         #title = _("Add new borrower") + " - II"
 
     return page(title=title,
                 uid=id_user,
                 req=req,
                 body=body,
                 language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def add_new_borrower_step3(req, tup_infos, ln=CFG_SITE_LANG):
     """
     Add new borrower. Step 3.
 
     @type tup_infos:   tuple.
     @param tup_infos:  tuple containing borrower information.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     if tup_infos[5] != '':
         borrower_notes = {}
         note_time = time.strftime("%Y-%m-%d %H:%M:%S")
         borrower_notes[note_time] = str(tup_infos[5])
     else:
         borrower_notes = ''
 
     db.new_borrower(None, tup_infos[0], tup_infos[1], tup_infos[2],
                     tup_infos[3], tup_infos[4], str(borrower_notes))
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_add_new_borrower_step3(ln=ln)
 
     return page(title=_("Add new borrower") + " - III",
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 #def update_borrower_info_step1(req, ln=CFG_SITE_LANG):
 #    """
 #    Update the borrower's information.
 #    """
 #
 #    navtrail_previous_links = '<a class="navtrail"' \
 #                              ' href="%s/help/admin">Admin Area' \
 #                              '</a>' % (CFG_SITE_SECURE_URL,)
 #
 #    id_user = getUid(req)
 #    (auth_code, auth_message) = is_adminuser(req)
 #    if auth_code != 0:
 #        return mustloginpage(req, auth_message)
 #
 #    _ = gettext_set_language(ln)
 #
 #    body = bc_templates.tmpl_update_borrower_info_step1(ln=ln)
 #
 #    return page(title=_("Update borrower information") + " - I",
 #                uid=id_user,
 #                req=req,
 #                body=body, language=ln,
 #                navtrail=navtrail_previous_links,
 #                lastupdated=__lastupdated__)
 #
 #def update_borrower_info_step2(req, column, string, ln=CFG_SITE_LANG):
 #    """
 #    Update the borrower's information.
 #    """
 #    id_user = getUid(req)
 #    (auth_code, auth_message) = is_adminuser(req)
 #    if auth_code != 0:
 #        return mustloginpage(req, auth_message)
 #
 #    _ = gettext_set_language(ln)
 #
 #    if column == 'name':
 #        result = db.search_borrower_by_name(string)
 #    elif column == 'phone':
 #        result = db.search_borrower_by_phone(string)
 #    elif column == 'email':
 #        result = db.search_borrower_by_email(string)
 #    else:
 #        result = db.search_borrower_by_id(string)
 #
 #    navtrail_previous_links = '<a class="navtrail" ' \
 #                              'href="%s/help/admin">Admin Area' \
 #                              '</a>' % (CFG_SITE_SECURE_URL,)
 #
 #    body = bc_templates.tmpl_update_borrower_info_step2(result=result, ln=ln)
 #
 #    return page(title=_("Update borrower information") + " - II",
 #                uid=id_user,
 #                req=req,
 #                body=body, language=ln,
 #                navtrail=navtrail_previous_links,
 #                lastupdated=__lastupdated__)
 
 def update_borrower_info_step1(req, borrower_id, ln=CFG_SITE_LANG):
     """
     Update the borrower's information.
 
     @param borrower_id:  identify the borrower. It is also the primary key of
                   the table crcBORROWER.
     """
 
     navtrail_previous_links = '<a class="navtrail"' \
                               ' href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     borrower_details = db.get_borrower_details(borrower_id)
 
     tup_infos = (borrower_details[0], borrower_details[2], borrower_details[3],
                  borrower_details[4], borrower_details[5], borrower_details[6])
 
     body = bc_templates.tmpl_update_borrower_info_step1(tup_infos=tup_infos,
                                                         ln=ln)
 
     return page(title=_("Update borrower information"),
                 uid=id_user,
                 req=req,
                 body=body,
                 language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def update_borrower_info_step2(req, borrower_id, name, email, phone, address,
                                mailbox, ln=CFG_SITE_LANG):
     """
     Update the borrower's information.
     """
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     infos = []
 
     if name == '':
         infos.append(_("Please, insert a name"))
 
     if email == '':
         infos.append(_("Please, insert a valid email address"))
     else:
         borrower_email_id = db.get_borrower_id_by_email(email)
         if borrower_email_id is not None and borrower_id != borrower_email_id:
             infos.append(_("There is already a borrower using the following email:")
                          + " <strong>%s</strong>" % (email))
 
     tup_infos = (borrower_id, name, email, phone, address, mailbox)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     if len(infos) > 0:
         body = bc_templates.tmpl_update_borrower_info_step1(tup_infos=tup_infos,
                                                         infos=infos, ln=ln)
     else:
         db.update_borrower_info(borrower_id, name, email,
                                 phone, address, mailbox)
 
         return redirect_to_url(req,
             '%s/admin2/bibcirculation/get_borrower_details?ln=%s&borrower_id=%s' \
                                             % (CFG_SITE_SECURE_URL, ln, borrower_id))
 
     return page(title=_("Update borrower information"),
                 uid=id_user,
                 req=req,
                 body=body,
                 language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def get_item_loans_notes(req, loan_id, add_notes, new_note, ln=CFG_SITE_LANG):
     """
     Get loan's notes.
 
     @param loan_id:  identify a loan. It is the primery key of the table
               crcLOAN.
 
     @param recid:  identify the record. It is also the primary key of
             the table bibrec.
 
     @param borrower_id:  identify the borrower. It is also the primary key of
                   the table crcBORROWER.
 
     @param add_notes:  display the textarea where will be written a new notes.
 
     @param new_notes:  note that will be added to the others library's notes.
     """
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     if new_note:
         date = '[' + time.ctime() + '] '
         new_line = '\n'
         new_note = date + new_note + new_line
         db.add_new_loan_note(new_note, loan_id)
 
     loans_notes = db.get_loans_notes(loan_id)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_get_loans_notes(loans_notes=loans_notes,
                                              loan_id=loan_id,
                                              add_notes=add_notes,
                                              ln=ln)
     return page(title=_("Loan notes"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def new_item(req, isbn, ln=CFG_SITE_LANG):
     """
     Add a new item using the ISBN.
     """
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     book_info = []
     errors = []
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     if isbn:
         from xml.dom import minidom
         import urllib
         filexml = urllib.urlopen('http://ecs.amazonaws.com/onca/xml?' \
                                  'Service=AWSECommerceService&AWSAccessKeyId=' \
                                  + CFG_BIBCIRCULATION_AMAZON_ACCESS_KEY + \
                                  '&Operation=ItemSearch&Condition=All&' \
                                  'ResponseGroup=ItemAttributes&SearchIndex=Books&' \
                                  'Keywords=' + isbn)
 
         xmldoc = minidom.parse(filexml)
 
         try:
             get_error_code = xmldoc.getElementsByTagName('Code')
             get_error_message = xmldoc.getElementsByTagName('Message')
             error_code = get_error_code.item(0).firstChild.data
             error_message = get_error_message.item(0).firstChild.data
             errors.append(str(error_code))
             errors.append(str(error_message))
         except AttributeError:
             errors = ""
 
         try:
             get_author = xmldoc.getElementsByTagName('Author')
             author = get_author.item(0).firstChild.data
             book_info.append(str(author))
         except AttributeError:
             author = ""
             book_info.append(str(author))
 
         try:
             get_ean = xmldoc.getElementsByTagName('EAN')
             ean = get_ean.item(0).firstChild.data
             book_info.append(int(ean))
         except AttributeError:
             ean = ""
             book_info.append(str(ean))
 
         try:
             get_isbn = xmldoc.getElementsByTagName('ISBN')
             short_isbn = get_isbn.item(0).firstChild.data
             book_info.append(str(short_isbn))
         except AttributeError:
             short_isbn = ""
             book_info.append(str(short_isbn))
 
         try:
             get_publisher = xmldoc.getElementsByTagName('Manufacturer')
             publisher = get_publisher.item(0).firstChild.data
             book_info.append(str(publisher))
         except AttributeError:
             publisher = ""
             book_info.append(str(publisher))
 
         try:
             get_nb_pages = xmldoc.getElementsByTagName('NumberOfPages')
             nb_pages = get_nb_pages.item(0).firstChild.data
             book_info.append(int(nb_pages))
         except AttributeError:
             nb_pages = ""
             book_info.append(str(nb_pages))
 
         try:
             get_pub_date = xmldoc.getElementsByTagName('PublicationDate')
             pub_date = get_pub_date.item(0).firstChild.data
             book_info.append(str(pub_date))
         except AttributeError:
             pub_date = ""
             book_info.append(str(pub_date))
 
         try:
             get_title = xmldoc.getElementsByTagName('Title')
             title = get_title.item(0).firstChild.data
             book_info.append(str(title))
         except AttributeError:
             title = ""
             book_info.append(str(title))
 
         try:
             get_edition = xmldoc.getElementsByTagName('Edition')
             edition = get_edition.item(0).firstChild.data
             book_info.append(str(edition))
         except AttributeError:
             edition = ""
             book_info.append(str(edition))
 
         cover_xml = urllib.urlopen('http://ecs.amazonaws.com/onca/xml' \
                                    '?Service=AWSECommerceService&AWSAccessKeyId=' \
                                    + CFG_BIBCIRCULATION_AMAZON_ACCESS_KEY + \
                                    '&Operation=ItemSearch&Condition=All&' \
                                    'ResponseGroup=Images&SearchIndex=Books&' \
                                    'Keywords=' + isbn)
 
         xml_img = minidom.parse(cover_xml)
 
         try:
             get_cover_link = xml_img.getElementsByTagName('MediumImage')
             cover_link = get_cover_link.item(0).firstChild.firstChild.data
             book_info.append(str(cover_link))
         except AttributeError:
             cover_link = CFG_SITE_SECURE_URL + "/img/book_cover_placeholder.gif"
             book_info.append(str(cover_link))
 
         if len(errors)!=0:
             body = bc_templates.tmpl_new_item(errors=errors, ln=ln)
         else:
             body = bc_templates.tmpl_new_item(book_info=book_info, ln=ln)
 
     else:
         body = bc_templates.tmpl_new_item(ln=ln)
 
     return page(title=_("New Item"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 
 def add_new_library_step1(req, ln=CFG_SITE_LANG):
     """
     Add a new Library.
     """
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     body = bc_templates.tmpl_add_new_library_step1(ln=ln)
 
     return page(title=_("Add new library"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def add_new_library_step2(req, name, email, phone, address,
                            lib_type, notes, ln=CFG_SITE_LANG):
 
     """
     Add a new Library.
     """
 
     tup_infos = (name, email, phone, address, lib_type, notes)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     _ = gettext_set_language(ln)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     body = bc_templates.tmpl_add_new_library_step2(tup_infos=tup_infos, ln=ln)
 
     return page(title=_("Add new library"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def add_new_library_step3(req, name, email, phone, address,
                            lib_type, notes, ln=CFG_SITE_LANG):
     """
     Add a new Library.
     """
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     db.add_new_library(name, email, phone, address, lib_type, notes)
 
     body = bc_templates.tmpl_add_new_library_step3(ln=ln)
 
     return page(title=_("Add new library"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def update_library_info_step1(req, ln=CFG_SITE_LANG):
     """
     Update the library's information.
     """
     infos = []
 
     navtrail_previous_links = '<a class="navtrail"' \
                               ' href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     body = bc_templates.tmpl_update_library_info_step1(infos=infos, ln=ln)
 
     return page(title=_("Update library information"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def update_library_info_step2(req, column, string, ln=CFG_SITE_LANG):
     """
     Update the library's information.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     if not string:
         infos = []
         infos.append(_("Empty string.") + ' ' + _('Please, try again.'))
         body = bc_templates.tmpl_update_library_info_step1(infos=infos, ln=ln)
     elif string == '*':
         result = db.get_all_libraries()
         body = bc_templates.tmpl_update_library_info_step2(result=result, ln=ln)
     else:
         if column == 'name':
             result = db.search_library_by_name(string)
         else:
             result = db.search_library_by_email(string)
 
         body = bc_templates.tmpl_update_library_info_step2(result=result, ln=ln)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     return page(title=_("Update library information"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def update_library_info_step3(req, library_id, ln=CFG_SITE_LANG):
     """
     Update the library's information.
 
     library_id - identify the library. It is also the primary key of
                  the table crcLIBRARY.
     """
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     navtrail_previous_links = '<a class="navtrail"' \
                               ' href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     library_info = db.get_library_details(library_id)
 
     body = bc_templates.tmpl_update_library_info_step3(
                                                     library_info=library_info,
                                                     ln=ln)
 
     return page(title=_("Update library information"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def update_library_info_step4(req, name, email, phone, address, lib_type,
                               library_id, ln=CFG_SITE_LANG):
     """
     Update the library's information.
     """
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     tup_infos = (library_id, name, email, phone, address, lib_type)
 
     body = bc_templates.tmpl_update_library_info_step4(tup_infos=tup_infos,
                                                        ln=ln)
 
     return page(title=_("Update library information"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def update_library_info_step5(req, name, email, phone, address, lib_type,
                               library_id, ln=CFG_SITE_LANG):
     """
     Update the library's information.
     """
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     #(library_id, name, email, phone, address) = tup_infos
 
     db.update_library_info(library_id, name, email, phone, address, lib_type)
 
     body = bc_templates.tmpl_update_library_info_step5(ln=ln)
 
     return page(title=_("Update library information"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def new_book_step1(req, ln):
     """
     Add a new book.
     """
     navtrail_previous_links = '<a class="navtrail"' \
                               ' href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     body = bc_templates.tmpl_new_book_step1(ln)
 
     return page(title=_("Order New Book"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def new_book_step2(req, ln):
     """
     Add a new book.
     """
     navtrail_previous_links = '<a class="navtrail"' \
                               ' href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     body = bc_templates.tmpl_new_book_step2(ln)
 
     return page(title=_("Order New Book"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def add_new_copy_step1(req, ln=CFG_SITE_LANG):
     """
     Add a new copy.
     """
 
     navtrail_previous_links = '<a class="navtrail"' \
                               ' href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     body = bc_templates.tmpl_add_new_copy_step1(ln)
 
     return page(title=_("Add new copy") + " - I",
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def add_new_copy_step2(req, p, f, ln=CFG_SITE_LANG):
     """
     Add a new copy.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     result = perform_request_search(cc="Books", sc="1", p=p, f=f)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_add_new_copy_step2(result=result, ln=ln)
 
     return page(title=_("Add new copy") + " - II",
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def add_new_copy_step3(req, recid, barcode, ln=CFG_SITE_LANG):
     """
     Add a new copy.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     infos = []
     result = db.get_item_copies_details(recid)
     libraries = db.get_internal_libraries()
 
     #(barcode, library, library_name, location, collection, description,
     #      loan_period, status, expected_arrival_date, recid)
 
     navtrail_previous_links = '<a class="navtrail"' \
                               ' href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     if barcode is not None:
         if not db.barcode_in_use(barcode):
             barcode = None
 
     tmp_barcode = generate_tmp_barcode()
 
     body = bc_templates.tmpl_add_new_copy_step3(recid=recid,
                                                 result=result,
                                                 libraries=libraries,
                                                 original_copy_barcode=barcode,
                                                 tmp_barcode=tmp_barcode,
                                                 infos=infos,
                                                 ln=ln)
 
     return page(title=_("Add new copy") + " - III",
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def add_new_copy_step4(req, barcode, library, location, collection, description,
                        loan_period, status, expected_arrival_date, recid,
                        ln=CFG_SITE_LANG):
 
     """
     Add a new copy.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     navtrail_previous_links = '<a class="navtrail"' \
                               ' href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     infos = []
 
     result = db.get_item_copies_details(recid)
     libraries = db.get_internal_libraries()
 
     if db.barcode_in_use(barcode):
         infos.append(_("The given barcode <strong>%s</strong> is already in use." % barcode))
         title = _("Add new copy") + " - III"
         body  = bc_templates.tmpl_add_new_copy_step3(recid=recid,
                                                     result=result,
                                                     libraries=libraries,
                                                     original_copy_barcode=None,
                                                     tmp_barcode=None,
                                                     infos=infos,
                                                     ln=ln)
     elif not barcode:
         infos.append(_("The given barcode is empty."))
         title = _("Add new copy") + " - III"
         body  = bc_templates.tmpl_add_new_copy_step3(recid=recid,
                                                     result=result,
                                                     libraries=libraries,
                                                     original_copy_barcode=None,
                                                     tmp_barcode=None,
                                                     infos=infos,
                                                     ln=ln)
     elif barcode[:3] == 'tmp' \
         and status in [CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF,
                        CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN,
                        CFG_BIBCIRCULATION_ITEM_STATUS_IN_PROCESS]:
-            infos.append(_("The status selected does not accept tamporary barcodes."))
-            title = _("Add new copy") + " - III"
-            tmp_barcode = generate_tmp_barcode()
-            body  = bc_templates.tmpl_add_new_copy_step3(recid=recid,
-                                                    result=result,
-                                                    libraries=libraries,
-                                                    original_copy_barcode=None,
-                                                    tmp_barcode=tmp_barcode,
-                                                    infos=infos,
-                                                    ln=ln)
-
+        infos.append(_("The status selected does not accept tamporary barcodes."))
+        title = _("Add new copy") + " - III"
+        tmp_barcode = generate_tmp_barcode()
+        body  = bc_templates.tmpl_add_new_copy_step3(recid=recid,
+                                                     result=result,
+                                                     libraries=libraries,
+                                                     original_copy_barcode=None,
+                                                     tmp_barcode=tmp_barcode,
+                                                     infos=infos,
+                                                     ln=ln)
 
     else:
         library_name = db.get_library_name(library)
         tup_infos = (barcode, library, library_name, location, collection,
                      description, loan_period, status, expected_arrival_date,
                      recid)
         title = _("Add new copy") + " - IV"
         body  = bc_templates.tmpl_add_new_copy_step4(tup_infos=tup_infos, ln=ln)
 
     return page(title=title,
                 uid=id_user,
                 req=req,
                 body=body,
                 metaheaderadd='<link rel="stylesheet" href="%s/img/jquery-ui.css" '\
                                 'type="text/css" />' % CFG_SITE_SECURE_URL,
                 language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def add_new_copy_step5(req, barcode, library, location, collection, description,
                         loan_period, status, expected_arrival_date, recid,
                         ln=CFG_SITE_LANG):
     """
     Add a new copy.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     infos = []
     if not db.barcode_in_use(barcode):
         db.add_new_copy(barcode, recid, library, collection, location,
                         description, loan_period, status, expected_arrival_date)
         update_requests_statuses(barcode)
     else:
         infos.append(_("The given barcode <strong>%s</strong> is already in use.") % barcode)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_add_new_copy_step5(infos=infos, recid=recid, ln=ln)
 
     return page(title=_("Add new copy") + " - V",
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def update_item_info_step1(req, ln=CFG_SITE_LANG):
     """
     Update the item's information.
     """
 
     navtrail_previous_links = '<a class="navtrail"' \
                               ' href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     body = bc_templates.tmpl_update_item_info_step1(ln=ln)
 
     return page(title=_("Update item information"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def update_item_info_step2(req, p, f, ln=CFG_SITE_LANG):
     """
     Update the item's information.
     """
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     result = perform_request_search(cc="Books", sc="1", p=p, f=f)
 
     body = bc_templates.tmpl_update_item_info_step2(result=result, ln=ln)
 
     return page(title="Update item information",
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def update_item_info_step3(req, recid, ln=CFG_SITE_LANG):
     """
     Update the item's information.
     """
 
     navtrail_previous_links = '<a class="navtrail"' \
                               ' href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     result = db.get_item_copies_details(recid)
 
     body = bc_templates.tmpl_update_item_info_step3(recid=recid, result=result,
                                                     ln=ln)
 
     return page(title=_("Update item information"),
                 uid=id_user,
                 req=req,
                 body=body,
                 language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def update_item_info_step4(req, barcode, ln=CFG_SITE_LANG):
     """
     Update the item's information.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     recid = db.get_id_bibrec(barcode)
     result = db.get_item_info(barcode)
     libraries = db.get_internal_libraries()
     libraries += db.get_hidden_libraries()
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     if recid == None:
         _ = gettext_set_language(ln)
         infos = []
         infos.append(_("Barcode <strong>%s</strong> not found" % barcode))
         return item_search(req, infos, ln)
 
 
     body = bc_templates.tmpl_update_item_info_step4(recid=recid,
                                                     result=result,
                                                     libraries=libraries,
                                                     ln=ln)
 
     return page(title=_("Update item information"),
                 uid=id_user,
                 req=req,
                 body=body,
                 language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def update_item_info_step5(req, barcode, old_barcode, library, location,
                            collection, description, loan_period, status,
                            expected_arrival_date, recid, ln=CFG_SITE_LANG):
 
     """
     Update the item's information.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     library_name = db.get_library_name(library)
     tup_infos = (barcode, old_barcode, library, library_name, location,
                  collection, description, loan_period, status,
                  expected_arrival_date, recid)
 
     navtrail_previous_links = '<a class="navtrail"' \
                               ' href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_update_item_info_step5(tup_infos=tup_infos, ln=ln)
 
     return page(title=_("Update item information"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def update_item_info_step6(req, tup_infos, ln=CFG_SITE_LANG):
     """
     Update the item's information.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     infos = []
 
     # tuple containing information for the update process.
     (barcode, old_barcode, library_id, location, collection,
      description, loan_period, status, expected_arrival_date, recid) = tup_infos
 
     is_on_loan = db.is_on_loan(old_barcode)
     #is_requested = db.is_requested(old_barcode)
 
     # if item on loan and new status is CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF,
     # item has to be returned.
     if is_on_loan and status == CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF:
 
         db.update_item_status(CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF, old_barcode)
         db.return_loan(old_barcode)
 
     # update item information.
     db.update_item_info(old_barcode, library_id, collection, location,
                         description, loan_period, status, expected_arrival_date)
     update_requests_statuses(old_barcode)
     navtrail_previous_links = '<a class="navtrail"' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     if barcode != old_barcode:
         if db.barcode_in_use(barcode):
             infos.append(_("Item <strong>[%s]</strong> updated, but the <strong>barcode was not modified</strong> because it is already in use.") % (old_barcode))
         else:
             if db.update_barcode(old_barcode, barcode):
                 infos.append(_("Item <strong>[%s]</strong> updated to <strong>[%s]</strong> with success.") % (old_barcode, barcode))
             else:
                 infos.append(_("Item <strong>[%s]</strong> updated, but the <strong>barcode was not modified</strong> because it was not found (!?).") % (old_barcode))
     else:
         infos.append(_("Item <strong>[%s]</strong> updated with success.") % old_barcode)
 
     copies = db.get_item_copies_details(recid)
     requests = db.get_item_requests(recid)
     loans = db.get_item_loans(recid)
     req_hist_overview = db.get_item_requests_historical_overview(recid)
     loans_hist_overview = db.get_item_loans_historical_overview(recid)
 
 
     body = bc_templates.tmpl_get_item_details(recid=recid,
                                         copies=copies,
                                         requests=requests,
                                         loans=loans,
                                         req_hist_overview=req_hist_overview,
                                         loans_hist_overview=loans_hist_overview,
                                         infos=infos,
                                         ln=ln)
 
     return page(title=_("Update item information"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def search_library_step1(req, infos=[], ln=CFG_SITE_LANG):
     """
     Display the form where we can search a library (by name or email).
     """
 
     navtrail_previous_links = '<a class="navtrail"' \
                               ' href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     body = bc_templates.tmpl_search_library_step1(infos=infos,
                                                               ln=ln)
 
     return page(title=_("Search library"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def search_library_step2(req, column, string, ln=CFG_SITE_LANG):
     """
     Search a library and return a list with all the possible results, using the
     parameters received from the previous step.
 
     column - identify the column, of the table crcLIBRARY, that will be
              considered during the search. Can be 'name' or 'email'.
 
     str - string used for the search process.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     if not string:
         infos = []
         infos.append(_("Emptry string.") + ' ' + _('Please, try again.'))
         body = bc_templates.tmpl_search_library_step1(infos=infos, ln=ln)
     elif string == '*':
         result = db.get_all_libraries()
         body = bc_templates.tmpl_search_library_step2(result=result, ln=ln)
     else:
         if column == 'name':
             result = db.search_library_by_name(string)
         else:
             result = db.search_library_by_email(string)
 
         body = bc_templates.tmpl_search_library_step2(result=result, ln=ln)
 
 
     navtrail_previous_links = '<a class="navtrail" ' \
                     'href="%s/help/admin">Admin Area' \
                     '</a> &gt; <a class="navtrail" ' \
                     'href="%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s">'\
                     'Circulation Management' \
                     '</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
 
     return page(title=_("Search library"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def get_library_notes(req, library_id, delete_key,
                       library_notes, ln=CFG_SITE_LANG):
     """
     Retrieve notes related with a library.
 
     library_id - identify the library. It is also the primary key of
                  the table crcLIBRARY.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     if delete_key and library_id:
         lib_notes = eval(db.get_library_notes(library_id))
         del lib_notes[delete_key]
         db.update_library_notes(library_id, lib_notes)
 
     elif library_notes:
         if db.get_library_notes(library_id):
             lib_notes = eval(db.get_library_notes(library_id))
         else:
             lib_notes = {}
 
         lib_notes[time.strftime("%Y-%m-%d %H:%M:%S")] = str(library_notes)
         db.update_library_notes(library_id, lib_notes)
 
     lib_notes = db.get_library_notes(library_id)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                     'href="%s/help/admin">Admin Area' \
                     '</a> &gt; <a class="navtrail" ' \
                     'href="%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s">'\
                     'Circulation Management' \
                     '</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
 
     body = bc_templates.tmpl_library_notes(library_notes=lib_notes,
                                             library_id=library_id,
                                             ln=ln)
     return page(title=_("Library notes"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def change_due_date_step1(req, barcode, borrower_id, ln=CFG_SITE_LANG):
     """
     Change the due date of a loan, step1.
 
     loan_id: identify a loan. It is the primery key of the table
              crcLOAN.
 
     borrower_id: identify the borrower. It is also the primary key of
                  the table crcBORROWER.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     loan_id = db.get_current_loan_id(barcode)
     loan_details = db.get_loan_infos(loan_id)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_change_due_date_step1(loan_details=loan_details,
                                                    loan_id=loan_id,
                                                    borrower_id=borrower_id,
                                                    ln=ln)
     return page(title=_("Change due date"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 #metaheaderadd = '<link rel="stylesheet" '\
                 #                'href="%s/img/jquery-ui/themes/redmond/ui.theme.css" '\
                 #                'type="text/css" />' % CFG_SITE_SECURE_URL,
                 metaheaderadd = '<link rel="stylesheet" href="%s/img/jquery-ui.css" '\
                                 'type="text/css" />' % CFG_SITE_SECURE_URL,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def change_due_date_step2(req, new_due_date, loan_id, borrower_id,
                           ln=CFG_SITE_LANG):
     """
     Change the due date of a loan, step2.
 
     due_date: new due date.
 
     loan_id: identify a loan. It is the primery key of the table
              crcLOAN.
 
     borrower_id: identify the borrower. It is also the primary key of
                  the table crcBORROWER.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     db.update_due_date(loan_id, new_due_date)
     update_status_if_expired(loan_id)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_change_due_date_step2(new_due_date=new_due_date,
                                                    borrower_id=borrower_id,
                                                    ln=ln)
     return page(title=_("Change due date"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def claim_book_return(req, borrower_id, recid, loan_id,
                       template, ln=CFG_SITE_LANG):
     """
     Claim the return of an item.
 
     borrower_id: identify the borrower. It is also the primary key of
                   the table crcBORROWER.
 
     recid: identify the record. It is also the primary key of
            the table bibrec.
 
     template: letter template.
     """
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     email_body = generate_email_body(load_template(template), loan_id)
 
     email = db.get_borrower_email(borrower_id)
     subject = book_title_from_MARC(int(recid))
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_borrower_notification(email=email,
                                                    subject=subject,
                                                    email_body=email_body,
                                                    borrower_id=borrower_id,
                                                    ln=ln)
 
 
     return page(title=_("Claim return"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def create_new_loan_step1(req, borrower_id, ln=CFG_SITE_LANG):
     """
     Create a new loan from the borrower's page, step1.
 
     borrower_id: identify the borrower. It is also the primary key of
                   the table crcBORROWER.
     """
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     infos = []
 
     borrower = db.get_borrower_details(borrower_id)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_create_new_loan_step1(borrower=borrower,
                                                    infos=infos,
                                                    ln=ln)
 
     return page(title=_("New loan"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def create_new_loan_step2(req, borrower_id, barcode, notes, ln=CFG_SITE_LANG):
     """
     Create a new loan from the borrower's page, step2.
 
     borrower_id: identify the borrower. It is also the primary key of
                   the table crcBORROWER.
 
     barcode: identify the item. It is the primary key of the table
              crcITEM.
 
     notes: notes about the new loan.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
     #borrower_info = db.get_borrower_data(borrower_id)
 
     has_recid = db.get_id_bibrec(barcode)
     loan_id = db.is_item_on_loan(barcode)
 
     if notes:
         notes_format = '[' + time.ctime() + '] ' + notes + '\n'
     else:
         notes_format = ''
 
     infos = []
 
     if has_recid is None:
         infos.append(_('%(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s Unknown barcode.') % {'x_barcode': barcode, 'x_strong_tag_open': '<strong>', 'x_strong_tag_close': '</strong>'} + ' ' + _('Please, try again.'))
         borrower = db.get_borrower_details(borrower_id)
         title = _("New loan")
         body = bc_templates.tmpl_create_new_loan_step1(borrower=borrower,
                                                         infos=infos,
                                                         ln=ln)
 
     elif loan_id:
         infos.append(_('The item with the barcode %(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s is on loan.') % {'x_barcode': barcode, 'x_strong_tag_open': '<strong>', 'x_strong_tag_close': '</strong>'})
         borrower = db.get_borrower_details(borrower_id)
         title = _("New loan")
         body = bc_templates.tmpl_create_new_loan_step1(borrower=borrower,
                                                         infos=infos,
                                                         ln=ln)
 
     else:
         #loaned_on = datetime.date.today()
         due_date = renew_loan_for_X_days(barcode)
         db.new_loan(borrower_id, has_recid, barcode,
                     due_date, CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN,
                     'normal', notes_format)
         tag_all_requests_as_done(barcode, borrower_id)
         db.update_item_status(CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN, barcode)
         update_requests_statuses(barcode)
         result = db.get_all_loans(20)
         title = _("Current loans")
         infos.append(_('A new loan has been registered with success.'))
         body = bc_templates.tmpl_all_loans(result=result, infos=infos, ln=ln)
 
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     return page(title=title,
                 uid=id_user,
                 req=req,
                 body=body,
                 language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def create_new_request_step1(req, borrower_id, p="", f="", search=None,
                              ln=CFG_SITE_LANG):
     """
     Create a new request from the borrower's page, step1.
 
     borrower_id: identify the borrower. It is also the primary key of
                   the table crcBORROWER.
 
     p: search pattern.
 
     f: field
 
     search: search an item.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     infos = []
     borrower = db.get_borrower_details(borrower_id)
 
     if search and p == '':
         infos.append(_('Empty string.') + ' ' + _('Please, try again.'))
         result = ''
 
     elif search and f == 'barcode':
         p = p.strip('\'" \t')
         has_recid = db.get_recid(p)
 
         if has_recid is None:
             infos.append(_('The barcode %(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s does not exist on BibCirculation database.') % {'x_barcode': p, 'x_strong_tag_open': '<strong>', 'x_strong_tag_close': '</strong>'})
             result = ''
         else:
             result = has_recid
 
     elif search:
         result = perform_request_search(cc="Books", sc="1", p=p, f=f)
 
     else:
         result = ''
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     if type(result) is types.IntType or type(result) is types.LongType:
         recid = result
         holdings_information = db.get_holdings_information(recid)
         user_info = db.get_borrower_details(borrower_id)
         body = bc_templates.tmpl_create_new_request_step2(user_info=user_info,
                                     holdings_information=holdings_information,
                                     recid=recid, ln=ln)
 
     else:
         body = bc_templates.tmpl_create_new_request_step1(borrower=borrower,
                                                           infos=infos,
                                                           result=result,
                                                           p=p,
                                                           f=f,
                                                           ln=ln)
 
     return page(title=_("New request"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def create_new_request_step2(req, recid, borrower_id, ln=CFG_SITE_LANG):
     """
     Create a new request from the borrower's page, step2.
 
     recid: identify the record. It is also the primary key of
            the table bibrec.
 
     borrower_id: identify the borrower. It is also the primary key of
             the table crcBORROWER.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     holdings_information = db.get_holdings_information(recid)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     user_info = db.get_borrower_details(borrower_id)
 
     body = bc_templates.tmpl_create_new_request_step2(user_info=user_info,
                                     holdings_information=holdings_information,
                                     recid=recid, ln=ln)
 
     return page(title=_("New request"),
                 uid=id_user,
                 req=req,
                 body=body,
                 language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def create_new_request_step3(req, borrower_id, barcode, recid,
                              ln=CFG_SITE_LANG):
     """
     Create a new request from the borrower's page, step3.
 
     borrower_id: identify the borrower. It is also the primary key of
                   the table crcBORROWER.
 
     barcode: identify the item. It is the primary key of the table
              crcITEM.
 
     recid: identify the record. It is also the primary key of
            the table bibrec.
     """
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     item_info = db.get_item_info(barcode)
 
     if item_info[6] == 'Reference':
         body = bc_templates.tmpl_book_not_for_loan(ln=ln)
     else:
         body = bc_templates.tmpl_create_new_request_step3(
                                                         borrower_id=borrower_id,
                                                         barcode=barcode,
                                                         recid=recid,
                                                         ln=ln)
 
     return page(title=_("New request"),
                 uid=id_user,
                 req=req,
                 body=body,
                 metaheaderadd = "<link rel=\"stylesheet\" href=\"%s/img/jquery/jquery-ui.css\" type=\"text/css\" />" % CFG_SITE_SECURE_URL,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def create_new_request_step4(req, period_from, period_to, barcode,
                              borrower_id, recid, ln=CFG_SITE_LANG):
     """
     Create a new request from the borrower's page, step4.
 
     period_from: begining of the period of interest.
 
     period_to: end of the period of interest.
 
     barcode: identify the item. It is the primary key of the table
              crcITEM.
 
     borrower_id: identify the borrower. It is also the primary key of
                   the table crcBORROWER.
 
     recid: identify the record. It is also the primary key of
            the table bibrec.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     db.new_hold_request(borrower_id, recid, barcode,
                         period_from, period_to,
                         CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING)
 
     update_requests_statuses(barcode)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_create_new_request_step4(ln=ln)
 
     return page(title=_("New request"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def place_new_request_step1(req, barcode, recid, key, string, ln=CFG_SITE_LANG):
     """
     Place a new request from the item's page, step1.
 
     barcode: identify the item. It is the primary key of the table
              crcITEM.
 
     recid: identify the record. It is also the primary key of
            the table bibrec.
 
     key: search field.
 
     string: search pattern.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     recid = db.get_id_bibrec(barcode)
     infos = []
 
     if key and not string:
         infos.append(_('Empty string.') + ' ' + _('Please, try again.'))
         body = bc_templates.tmpl_place_new_request_step1(result=None,
                                                          key=key,
                                                          string=string,
                                                          barcode=barcode,
                                                          recid=recid,
                                                          infos=infos,
                                                          ln=ln)
 
         navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
         return page(title=_("New request"),
                     uid=id_user,
                     req=req,
                     body=body,
                     language=ln,
                     navtrail=navtrail_previous_links,
                     lastupdated=__lastupdated__)
 
     result = search_user(key, string)
     borrowers_list = []
 
     if len(result) == 0 and key:
         if CFG_CERN_SITE:
             infos.append(_("0 borrowers found.") + ' ' +_("Search by CCID."))
         else:
             new_borrower_link = create_html_link(CFG_SITE_SECURE_URL +
                                 '/admin2/bibcirculation/add_new_borrower_step1',
                                 {'ln': ln}, _("Register new borrower."))
             message = _("0 borrowers found.") + ' ' + new_borrower_link
             infos.append(message)
     else:
         for user in result:
             borrower_data = db.get_borrower_data_by_id(user[0])
             borrowers_list.append(borrower_data)
 
     if len(result) == 1:
         return place_new_request_step2(req, barcode, recid,
                                        borrowers_list[0], ln)
     else:
         body = bc_templates.tmpl_place_new_request_step1(result=borrowers_list,
                                                          key=key,
                                                          string=string,
                                                          barcode=barcode,
                                                          recid=recid,
                                                          infos=infos,
                                                          ln=ln)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     return page(title=_("New request"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 
 
 def place_new_request_step2(req, barcode, recid, user_info, ln=CFG_SITE_LANG):
     """
     Place a new request from the item's page, step2.
 
     @type barcode:     string.
     @param barcode:    identify the item. It is the primary key of the table
                        crcITEM.
 
     @type recid:       integer.
     @param recid:      identify the record. It is also the primary key of
                        the table bibrec.
 
     @type user_info:   list.
     @param user_info:  information of the user/borrower who was selected.
 
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     infos = []
 
     body = bc_templates.tmpl_place_new_request_step2(barcode=barcode,
                                                      recid=recid,
                                                      user_info=user_info,
                                                      infos=infos,
                                                      ln=ln)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     return page(title=_("New request"),
                 uid=id_user,
                 req=req,
                 body=body,
                 metaheaderadd = "<link rel=\"stylesheet\" href=\"%s/img/jquery/jquery-ui.css\" type=\"text/css\" />" % CFG_SITE_SECURE_URL,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def place_new_request_step3(req, barcode, recid, user_info,
                             period_from, period_to, ln=CFG_SITE_LANG):
     """
     Place a new request from the item's page, step3.
 
     @type barcode:  string.
     @param barcode: identify the item. It is the primary key of the table
                     crcITEM.
 
     @type recid:    integer.
     @param recid:   identify the record. It is also the primary key of
                     the table bibrec.
 
     @return:        new request.
     """
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     (_id, ccid, name, email, phone, address, mailbox) = user_info
 
     # validate the period of interest given by the admin
     if validate_date_format(period_from) is False:
         infos = []
         infos.append(_("The period of interest %(x_strong_tag_open)sFrom: %(x_date)s%(x_strong_tag_close)s is not a valid date or date format") % {'x_date': period_from, 'x_strong_tag_open': '<strong>', 'x_strong_tag_close': '</strong>'})
 
         body = bc_templates.tmpl_place_new_request_step2(barcode=barcode,
                                                          recid=recid,
                                                          user_info=user_info,
                                                          infos=infos,
                                                          ln=ln)
 
         return page(title=_("New request"),
                     uid=id_user,
                     req=req,
                     body=body,
                     language=ln,
                     navtrail=navtrail_previous_links,
                     lastupdated=__lastupdated__)
 
     elif validate_date_format(period_to) is False:
         infos = []
         infos.append(_("The period of interest %(x_strong_tag_open)sTo: %(x_date)s%(x_strong_tag_close)s is not a valid date or date format") % {'x_date': period_to, 'x_strong_tag_open': '<strong>', 'x_strong_tag_close': '</strong>'})
 
         body = bc_templates.tmpl_place_new_request_step2(barcode=barcode,
                                                          recid=recid,
                                                          user_info=user_info,
                                                          infos=infos,
                                                          ln=ln)
 
     # Register request
     borrower_id = db.get_borrower_id_by_email(email)
 
     if borrower_id == None:
         db.new_borrower(ccid, name, email, phone, address, mailbox, '')
         borrower_id = db.get_borrower_id_by_email(email)
 
     req_id = db.new_hold_request(borrower_id, recid, barcode,
                                  period_from, period_to,
                                  CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING)
 
     pending_request = update_requests_statuses(barcode)
 
     if req_id == pending_request:
         (title, year, author,
          isbn, publisher) = book_information_from_MARC(int(recid))
         details = db.get_loan_request_details(req_id)
         if details:
             library  = details[3]
             location = details[4]
             request_date = details[7]
         else:
             location = ''
             library  = ''
             request_date = ''
 
         link_to_holdings_details = create_html_link(CFG_SITE_SECURE_URL +
                                     '/record/%s/holdings'%str(recid),
                                     {'ln': ln},
                                     (CFG_SITE_SECURE_URL +
                                     '/record/%s/holdings'%str(recid)))
 
         subject = _('New request')
         message = load_template('notification')
 
         message = message % (name, ccid, email, address, mailbox, title,
                              author, publisher, year, isbn, location, library,
                              link_to_holdings_details, request_date)
 
 
         send_email(fromaddr = CFG_BIBCIRCULATION_LIBRARIAN_EMAIL,
                 toaddr   = CFG_BIBCIRCULATION_LOANS_EMAIL,
                 subject  = subject,
                 content  = message,
                 header   = '',
                 footer   = '',
                 attempt_times=1,
                 attempt_sleeptime=10
                 )
         send_email(fromaddr = CFG_BIBCIRCULATION_LIBRARIAN_EMAIL,
                 toaddr   = email,
                 subject  = subject,
                 content  = message,
                 header   = '',
                 footer   = '',
                 attempt_times=1,
                 attempt_sleeptime=10
                 )
 
     body = bc_templates.tmpl_place_new_request_step3(ln=ln)
 
     return page(title=_("New request"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def place_new_loan_step1(req, barcode, recid, key, string, ln=CFG_SITE_LANG):
     """
     Place a new loan from the item's page, step1.
 
     @type barcode:  string.
     @param barcode: identify the item. It is the primary key of the table
                     crcITEM.
 
     @type recid:    integer.
     @param recid:   identify the record. It is also the primary key of
                     the table bibrec.
 
     @type key:      string.
     @param key:     search field.
 
     @type string:   string.
     @param string:  search pattern.
 
     @return:        list of users/borrowers.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     recid = db.get_id_bibrec(barcode)
     infos = []
 
     if key and not string:
         infos.append(_('Empty string.') + ' ' + _('Please, try again.'))
         body = bc_templates.tmpl_place_new_loan_step1(result=None,
                                                         key=key,
                                                         string=string,
                                                         barcode=barcode,
                                                         recid=recid,
                                                         infos=infos,
                                                         ln=ln)
 
         navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
         id_user = getUid(req)
         (auth_code, auth_message) = is_adminuser(req)
         if auth_code != 0:
             return mustloginpage(req, auth_message)
 
         return page(title=_("New loan"),
                     uid=id_user,
                     req=req,
                     body=body, language=ln,
                     navtrail=navtrail_previous_links,
                     lastupdated=__lastupdated__)
 
     result = search_user(key, string)
     borrowers_list = []
 
     if len(result) == 0 and key:
         if CFG_CERN_SITE:
             infos.append(_("0 borrowers found.") + ' ' +_("Search by CCID."))
         else:
             new_borrower_link = create_html_link(CFG_SITE_SECURE_URL +
                                 '/admin2/bibcirculation/add_new_borrower_step1',
                                 {'ln': ln}, _("Register new borrower."))
             message = _("0 borrowers found.") + ' ' + new_borrower_link
             infos.append(message)
     else:
         for user in result:
             borrower_data = db.get_borrower_data_by_id(user[0])
             borrowers_list.append(borrower_data)
 
     body = bc_templates.tmpl_place_new_loan_step1(result=borrowers_list,
                                                               key=key,
                                                               string=string,
                                                               barcode=barcode,
                                                               recid=recid,
                                                               infos=infos,
                                                               ln=ln)
 
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     return page(title=_("New loan"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def place_new_loan_step2(req, barcode, recid, user_info, ln=CFG_SITE_LANG):
     """
     Place a new loan from the item's page, step2.
 
     @type barcode:    string.
     @param barcode:   identify the item. It is the primary key of the table
                       crcITEM.
 
     @type recid:      integer.
     @param recid:     identify the record. It is also the primary key of
                       the table bibrec.
 
     @type user_info:  list.
     @param user_info: information of the user/borrower who was selected.
     """
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     body = bc_templates.tmpl_place_new_loan_step2(barcode=barcode,
                                                     recid=recid,
                                                     user_info=user_info,
                                                     ln=ln)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     return page(title=_("New loan"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def place_new_loan_step3(req, barcode, recid, ccid, name, email, phone,
                          address, mailbox, due_date, notes, ln=CFG_SITE_LANG):
     """
     Place a new loan from the item's page, step3.
 
     @type barcode:  string.
     @param barcode: identify the item. It is the primary key of the table
                     crcITEM.
 
     @type recid:    integer.
     @param recid:   identify the record. It is also the primary key of
                     the table bibrec.
 
     @type name:     string.
     @type email:    string.
     @type phone:    string.
     @type address:  string.
     @type mailbos:  string.
     @type due_date: string.
     @type notes:    string.
 
     @return:        new loan.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     infos = []
 
     if notes:
         notes_format = '[' + time.ctime() + '] ' +  notes +  '\n'
     else:
         notes_format = ''
 
     #loaned_on = datetime.date.today()
 
     borrower_id = db.get_borrower_id_by_email(email)
     borrower_info = db.get_borrower_data(borrower_id)
 
     if db.is_on_loan(barcode):
         infos.append(_("Item with barcode %(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s is already on loan.") % {'x_barcode': barcode, 'x_strong_tag_open': '<strong>', 'x_strong_tag_close': '</strong>'})
 
         copies = db.get_item_copies_details(recid)
         requests = db.get_item_requests(recid)
         loans = db.get_item_loans(recid)
 
         req_hist_overview = db.get_item_requests_historical_overview(recid)
         loans_hist_overview = db.get_item_loans_historical_overview(recid)
 
         title = _("Item details")
         body = bc_templates.tmpl_get_item_details(
                                         recid=recid, copies=copies,
                                         requests=requests, loans=loans,
                                         req_hist_overview=req_hist_overview,
                                         loans_hist_overview=loans_hist_overview,
                                         infos=infos, ln=ln)
 
     elif borrower_id != 0:
         db.new_loan(borrower_id, recid, barcode,
                     due_date, CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN,
                     'normal', notes_format)
 
         tag_all_requests_as_done(barcode, borrower_id)
         db.update_item_status(CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN, barcode)
         update_requests_statuses(barcode)
 
         title = _("New loan")
         body = bc_templates.tmpl_register_new_loan(borrower_info=borrower_info,
                                                    infos=infos,
                                                    recid=recid, ln=ln)
 
     else:
         db.new_borrower(ccid, name, email, phone, address, mailbox, '')
         borrower_id = db.get_borrower_id_by_email(email)
 
         db.new_loan(borrower_id, recid, barcode,
                     due_date, CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN,
                     'normal', notes_format)
         tag_all_requests_as_done(barcode, borrower_id)
         db.update_item_status(CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN, barcode)
         update_requests_statuses(barcode)
         title = _("New loan")
         body = bc_templates.tmpl_register_new_loan(borrower_info=borrower_info,
                                                    infos=infos,
                                                    recid=recid,
                                                    ln=ln)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                     'href="%s/help/admin">Admin Area' \
                     '</a> &gt; <a class="navtrail" ' \
                     'href="%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s">'\
                     'Circulation Management' \
                     '</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
 
     return page(title=title,
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def order_new_copy_step1(req, recid, ln):
     """
     Order a new copy. Step 1.
     """
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     list_of_vendors = db.get_list_of_vendors()
     libraries = db.get_internal_libraries()
 
     body = bc_templates.tmpl_order_new_copy_step1(recid=recid,
                                                 list_of_vendors=list_of_vendors,
                                                 libraries=libraries, ln=ln)
 
     return page(title=_("Order new copy"),
                 uid=id_user,
                 req=req,
                 metaheaderadd = """<link rel="stylesheet" href="%s/img/jquery-ui.css"
                                          type="text/css" >""" % CFG_SITE_SECURE_URL,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def order_new_copy_step2 (req, recid, barcode, vendor_id, cost, currency,
                           status, order_date, expected_date, library_id,
                           notes, ln):
     """
     Order a new copy. Step 2.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     order_info = (recid, barcode, vendor_id, cost, currency, status,
                   order_date, expected_date, library_id, notes)
 
     body = bc_templates.tmpl_order_new_copy_step2(order_info=order_info, ln=ln)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     return page(title=_("Order new copy"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def order_new_copy_step3(req, order_info, ln):
     """
     Order a new copy. Step 3.
     """
 
     #id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     (recid, _barcode, vendor_id, cost, currency, status,
      order_date, expected_date, _library_id, notes) = order_info
 
     cost_format = cost + ' ' + currency
 
     purchase_notes = {time.strftime("%Y-%m-%d %H:%M:%S"): notes}
 
     db.order_new_copy(recid, vendor_id, order_date, cost_format,
                       status, str(purchase_notes), expected_date)
 
     return get_item_details(req, recid, ln)
 
 
 def list_ordered_books(req, ln):
     """
     Return the list with all ordered books.
     """
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     ordered_books = db.get_ordered_books()
 
     body = bc_templates.tmpl_ordered_books(ordered_books=ordered_books, ln=ln)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     return page(title=_("List of ordered books"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def get_purchase_notes(req, purchase_id, delete_key, library_notes,
                        ln=CFG_SITE_LANG):
     """
     Retrieve notes related with a library.
 
     purchase_id - identify the purchase. It is also the primary key of
                  the table crcPURCHASE.
 
     @param add_notes:  display the textarea where will be written a new notes.
 
     @param new_notes:  note that will be added to the others library's notes.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     if delete_key and purchase_id:
         purchase_notes = eval(db.get_purchase_notes(purchase_id))
         del purchase_notes[delete_key]
         db.update_purchase_notes(purchase_id, purchase_notes)
 
     elif library_notes:
         if db.get_purchase_notes(purchase_id):
             purchase_notes = eval(db.get_purchase_notes(purchase_id))
         else:
             purchase_notes = {}
 
         purchase_notes[time.strftime("%Y-%m-%d %H:%M:%S")] = str(library_notes)
         db.update_purchase_notes(purchase_id, purchase_notes)
 
     purchase_notes = db.get_purchase_notes(purchase_id)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_purchase_notes(purchase_notes=purchase_notes,
                                             purchase_id=purchase_id,
                                             ln=ln)
     return page(title=_("Purchase notes"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def register_ill_request_step0(req, recid, key, string, ln=CFG_SITE_LANG):
     """
     Place a new request from the item's page, step1.
 
     barcode: identify the item. It is the primary key of the table
              crcITEM.
 
     recid: identify the record. It is also the primary key of
            the table bibrec.
 
     key: search field.
 
     string: search pattern.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     if string == '':
         message = _('Empty string.') + ' ' + _('Please, try again.')
         return borrower_search(req, message, False, ln)
     else:
         result = search_user(key, string)
 
     infos = []
 
     if not key or (key and not string):
         if key and not string:
             infos.append(_('Empty string.') + ' ' + _('Please, try again.'))
         body = bc_templates.tmpl_register_ill_request_step0(result=None,
                                                             infos=infos,
                                                             key=key,
                                                             string=string,
                                                             recid=recid,
                                                             ln=ln)
 
 
         navtrail_previous_links = '<a class="navtrail" ' \
                                   'href="%s/help/admin">Admin Area' \
                                   '</a>' % (CFG_SITE_SECURE_URL,)
 
 
         return page(title=_("Register ILL request"),
                     uid=id_user,
                     req=req,
                     body=body, language=ln,
                     navtrail=navtrail_previous_links,
                     lastupdated=__lastupdated__)
 
     if CFG_CERN_SITE == 1:
         if  key == 'name':
             result = db.search_borrower_by_name(string)
         elif key == 'email':
             result = db.search_borrower_by_email(string)
         else:
             result = db.search_borrower_by_ccid(int(string))
 
             if result == ():
                 ldap_info = get_user_info_from_ldap(ccid=string)
 
                 if len(ldap_info) == 0:
                     result = ()
                 else:
                     if ldap_info == 'busy':
                         message = bc_templates.tmpl_message_sever_busy(ln)
                         return borrower_search(req, message, False, ln)
 
                     else:
                         try:
                             name = ldap_info['cn'][0]
                         except KeyError:
                             name = ""
                         try:
                             email = ldap_info['mail'][0]
                         except KeyError:
                             email = ""
                         try:
                             phone = ldap_info['telephoneNumber'][0]
                         except KeyError:
                             phone = ""
                         try:
                             address = ldap_info['physicalDeliveryOfficeName'][0]
                         except KeyError:
                             address = ""
                         try:
                             mailbox = ldap_info['postOfficeBox'][0]
                         except KeyError:
                             mailbox = ""
                         try:
                             ccid = ldap_info['employeeID'][0]
                         except KeyError:
                             ccid = ""
 
                         db.new_borrower(ccid, name, email, phone,
                                         address, mailbox, '')
                         result = db.search_borrower_by_ccid(int(ccid))
 
     else:
         if key == 'name':
             result = db.search_borrower_by_name(string)
         elif key == 'email':
             result = db.search_borrower_by_email(string)
         else:
             result = db.search_borrower_by_id(string)
     list_infos = []
     for (borrower_id, ccid, name, email, phone, address, mailbox) in result:
         tup = (borrower_id, ccid, name, email, phone, address, mailbox)
         list_infos.append(tup)
 
 
     body = bc_templates.tmpl_register_ill_request_step0(result=list_infos,
                                                         infos=infos,
                                                         key=key,
                                                         string=string,
                                                         recid=recid,
                                                         ln=ln)
 
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     return page(title=_("Register ILL request"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def register_ill_request_step1(req, recid, user_info, ln=CFG_SITE_LANG):
     """
     Register a new ILL request. Step 1.
     """
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     body = bc_templates.tmpl_register_ill_request_step1(recid=recid,
                                                         user_info=user_info,
                                                         ln=ln)
 
 
     return page(title=_("Register ILL request"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def register_ill_request_step2(req, recid, user_info, period_of_interest_from,
                                period_of_interest_to, notes, only_edition,
                                ln=CFG_SITE_LANG):
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
 
     request_info = (recid, period_of_interest_from, period_of_interest_to,
                     notes, only_edition)
 
     body = bc_templates.tmpl_register_ill_request_step2(user_info=user_info,
                                                     request_info=request_info,
                                                     ln=ln)
 
     return page(title=_("Register ILL request"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def register_ill_request_step3(req, borrower_id, request_info,
                                ln=CFG_SITE_LANG):
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     (recid, period_of_interest_from, period_of_interest_to,
      notes, only_edition) = request_info
 
     book_info = {'recid': recid}
 
     if notes:
         library_notes = {}
         library_notes[time.strftime("%Y-%m-%d %H:%M:%S")] = str(notes)
     else:
         library_notes = {}
 
     db.ill_register_request_on_desk(borrower_id, book_info,
                                     period_of_interest_from,
                                     period_of_interest_to,
                                     CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING,
                                     str(library_notes),
                                     only_edition or 'No', 'book')
 
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_register_ill_request_step3(ln=ln)
 
 
     return page(title=_("Register ILL request"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def list_ill_request(req, status, ln=CFG_SITE_LANG):
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     ill_req = db.get_ill_requests(status)
 
     body = bc_templates.tmpl_list_ill_request(ill_req=ill_req, ln=ln)
 
     return page(title=_("List of ILL requests"),
                 uid=id_user,
                 req=req,
                 body=body,
                 language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def list_acquisition(req, status, ln=CFG_SITE_LANG):
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     acquisitions = db.get_acquisitions(status)
 
     body = bc_templates.tmpl_list_acquisition(ill_req=acquisitions, ln=ln)
 
     return page(title=_("List of acquisitions"),
                 uid=id_user,
                 req=req,
                 body=body,
                 language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def ill_request_details_step1(req, delete_key, ill_request_id, new_status,
                               ln=CFG_SITE_LANG):
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     infos = []
 
     if delete_key and ill_request_id:
         library_notes = eval(db.get_ill_request_notes(ill_request_id))
         del library_notes[delete_key]
         db.update_ill_request_notes(ill_request_id, library_notes)
 
     if new_status:
         db.update_ill_request_status(ill_request_id, new_status)
 
     ill_request_borrower_details = \
                             db.get_ill_request_borrower_details(ill_request_id)
 
     if ill_request_borrower_details is None \
        or len(ill_request_borrower_details) == 0:
         infos.append(_("Borrower request details not found."))
 
     ill_request_details = db.get_ill_request_details(ill_request_id)
     if ill_request_details is None or len(ill_request_details) == 0:
         infos.append(_("Request not found."))
 
 
     libraries = db.get_external_libraries()
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     if infos == []:
         body = bc_templates.tmpl_ill_request_details_step1(
                                     ill_request_id=ill_request_id,
                                     ill_request_details=ill_request_details,
                                     libraries=libraries,
                       ill_request_borrower_details=ill_request_borrower_details,
                                     ln=ln)
         title = _("ILL request details")
     else:
         body = bc_templates.tmpl_display_infos(infos, ln)
 
     return page(title=title,
                 uid=id_user,
                 req=req,
                 metaheaderadd='<link rel="stylesheet" ' \
                                     'href="%s/img/jquery-ui.css" ' \
                                     'type="text/css" />' % CFG_SITE_SECURE_URL,
                 body=body,
                 language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def acq_details_step1(req, delete_key, ill_request_id, new_status,
                               ln=CFG_SITE_LANG):
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     infos = []
 
     if delete_key and ill_request_id:
         library_notes = eval(db.get_ill_request_notes(ill_request_id))
         del library_notes[delete_key]
         db.update_ill_request_notes(ill_request_id, library_notes)
 
     if new_status:
         db.update_ill_request_status(ill_request_id, new_status)
 
     ill_request_borrower_details = \
                             db.get_acq_request_borrower_details(ill_request_id)
 
     if ill_request_borrower_details is None \
        or len(ill_request_borrower_details) == 0:
         infos.append(_("Borrower request details not found."))
 
     ill_request_details = db.get_ill_request_details(ill_request_id)
     if ill_request_details is None or len(ill_request_details) == 0:
         infos.append(_("Request not found."))
 
     vendors = db.get_all_vendors()
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     if infos == []:
         body = bc_templates.tmpl_acq_details_step1(
                                     ill_request_id=ill_request_id,
                                     ill_request_details=ill_request_details,
                                     libraries=vendors,
                       ill_request_borrower_details=ill_request_borrower_details,
                                     ln=ln)
         title = _("Acquisition details")
     else:
         body = bc_templates.tmpl_display_infos(infos, ln)
 
     return page(title=title,
                 uid=id_user,
                 req=req,
                 metaheaderadd = "<link rel=\"stylesheet\" href=\"%s/img/jquery/jquery-ui.css\" type=\"text/css\" />" % CFG_SITE_SECURE_URL,
                 body=body,
                 language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def ill_request_details_step2(req, delete_key, ill_request_id, new_status,
                               library_id, request_date, expected_date,
                               arrival_date, due_date, return_date,
-                              cost, currency, barcode, library_notes,
+                              cost, _currency, barcode, library_notes,
                               book_info, article_info, ln=CFG_SITE_LANG):
 
     #id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     if delete_key and ill_request_id:
         library_previous_notes = eval(db.get_ill_request_notes(ill_request_id))
         del library_previous_notes[delete_key]
         db.update_ill_request_notes(ill_request_id, library_previous_notes)
 
     #navtrail_previous_links = '<a class="navtrail" ' \
     #                          'href="%s/help/admin">Admin Area' \
     #                          '</a>' % (CFG_SITE_SECURE_URL,)
 
     if db.get_ill_request_notes(ill_request_id):
         library_previous_notes = eval(db.get_ill_request_notes(ill_request_id))
     else:
         library_previous_notes = {}
 
     if library_notes:
         library_previous_notes[time.strftime("%Y-%m-%d %H:%M:%S")] = \
                                                             str(library_notes)
 
     if new_status == CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED:
         borrower_id = db.get_ill_borrower(ill_request_id)
         barcode = db.get_ill_barcode(ill_request_id)
         db.update_ill_loan_status(borrower_id, barcode, return_date, 'ill')
 
     db.update_ill_request(ill_request_id, library_id, request_date,
                           expected_date, arrival_date, due_date, return_date,
                           new_status, cost, barcode,
                           str(library_previous_notes))
 
     request_type = db.get_ill_request_type(ill_request_id)
     if request_type == 'book':
         item_info = book_info
     else:
         item_info = article_info
     db.update_ill_request_item_info(ill_request_id, item_info)
 
     return list_ill_request(req, new_status, ln)
 
 def acq_details_step2(req, delete_key, ill_request_id, new_status,
                               library_id, request_date, expected_date,
                               arrival_date, due_date, return_date,
                               cost, budget_code, library_notes,
                               item_info, ln=CFG_SITE_LANG):
 
     #id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     if delete_key and ill_request_id:
         library_previous_notes = eval(db.get_ill_request_notes(ill_request_id))
         del library_previous_notes[delete_key]
         db.update_ill_request_notes(ill_request_id, library_previous_notes)
 
     if db.get_ill_request_notes(ill_request_id):
         library_previous_notes = eval(db.get_ill_request_notes(ill_request_id))
     else:
         library_previous_notes = {}
 
     if library_notes:
         library_previous_notes[time.strftime("%Y-%m-%d %H:%M:%S")] = \
                                                             str(library_notes)
 
-    if new_status == CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED:
-        borrower_id = db.get_ill_borrower(ill_request_id)
+    #if new_status == CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED:
+    #    borrower_id = db.get_ill_borrower(ill_request_id)
 
     db.update_acq_request(ill_request_id, library_id, request_date,
                           expected_date, arrival_date, due_date, return_date,
                           new_status, cost, budget_code,
                           str(library_previous_notes))
 
-    request_type = db.get_ill_request_type(ill_request_id)
+    #request_type = db.get_ill_request_type(ill_request_id)
 
     db.update_ill_request_item_info(ill_request_id, item_info)
 
     return redirect_to_url(req,
             '%s/admin2/bibcirculation/list_acquisition?ln=%s&status=%s' % \
                                                 (CFG_SITE_SECURE_URL, ln, new_status))
 
 def ordered_books_details_step1(req, purchase_id, delete_key, ln=CFG_SITE_LANG):
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     if delete_key and purchase_id:
         purchase_notes = eval(db.get_purchase_notes(purchase_id))
         del purchase_notes[delete_key]
         db.update_purchase_notes(purchase_id, purchase_notes)
 
     list_of_vendors = db.get_list_of_vendors()
     order_details = db.get_order_details(purchase_id)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_ordered_book_details_step1(
                                                 order_details=order_details,
                                                 list_of_vendors=list_of_vendors,
                                                 ln=ln)
 
 
     return page(title=_("Ordered book details"),
                 uid=id_user,
                 req=req,
                 metaheaderadd='<link rel="stylesheet" href="%s/img/jquery-ui.css" '\
                               'type="text/css" />' % CFG_SITE_SECURE_URL,
                 body=body,
                 language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def ordered_books_details_step2(req, purchase_id, recid, vendor_id,
                                 cost, currency, status, order_date,
                                 expected_date, purchase_notes, library_notes,
                                 ln=CFG_SITE_LANG):
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     order_details = (purchase_id, recid, vendor_id,
                      cost, currency, status, order_date,
                      expected_date, purchase_notes,
                      library_notes)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_ordered_book_details_step2(
                                                     order_details=order_details,
                                                     ln=ln)
 
 
     return page(title=_("Ordered book details"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def ordered_books_details_step3(req, purchase_id, recid, vendor_id,
                                 cost, currency, status, order_date,
                                 expected_date, purchase_notes, library_notes,
                                 ln=CFG_SITE_LANG):
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     purchase_notes = eval(purchase_notes)
     library_notes = library_notes.strip(' \n\t')
     if (len(library_notes)) is not 0:
         purchase_notes[time.strftime("%Y-%m-%d %H:%M:%S")] = str(library_notes)
 
     cost_format = cost + ' ' + currency
 
     db.update_purchase(purchase_id, recid, vendor_id, cost_format,
                        status, order_date, expected_date, str(purchase_notes))
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     #body = bc_templates.tmpl_ordered_book_details_step3(ln=ln)
     body = list_ordered_books(req, ln)
 
 
     return page(title=_("Ordered book details"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def add_new_vendor_step1(req, ln=CFG_SITE_LANG):
     """
     Add a new Vendor.
     """
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     body = bc_templates.tmpl_add_new_vendor_step1(ln=ln)
 
     return page(title=_("Add new vendor"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def add_new_vendor_step2(req, name, email, phone, address,
                          notes, ln=CFG_SITE_LANG):
 
     """
     Add a new Vendor.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     tup_infos = (name, email, phone, address, notes)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_add_new_vendor_step2(tup_infos=tup_infos, ln=ln)
 
     return page(title=_("Add new vendor"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def add_new_vendor_step3(req, name, email, phone, address,
                          notes, ln=CFG_SITE_LANG):
     """
     Add a new Vendor.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     db.add_new_vendor(name, email, phone, address, notes)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_add_new_vendor_step3(ln=ln)
 
     return page(title=_("Add new vendor"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def update_vendor_info_step1(req, ln=CFG_SITE_LANG):
     """
     Update the vendor's information.
     """
 
     infos = []
 
     navtrail_previous_links = '<a class="navtrail"' \
                               ' href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     _ = gettext_set_language(ln)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     body = bc_templates.tmpl_update_vendor_info_step1(infos=infos, ln=ln)
 
     return page(title=_("Update vendor information"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def update_vendor_info_step2(req, column, string, ln=CFG_SITE_LANG):
     """
     Update the vendor's information.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     if not string:
         infos = []
         infos.append(_('Empty string.') + ' ' + _('Please, try again.'))
         body = bc_templates.tmpl_update_vendor_info_step1(infos=infos, ln=ln)
 
     elif string == '*':
         result = db.get_all_vendors()
         body = bc_templates.tmpl_update_vendor_info_step2(result=result, ln=ln)
 
     else:
         if column == 'name':
             result = db.search_vendor_by_name(string)
         else:
             result = db.search_vendor_by_email(string)
         body = bc_templates.tmpl_update_vendor_info_step2(result=result, ln=ln)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_update_vendor_info_step2(result=result, ln=ln)
 
     return page(title=_("Update vendor information"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def update_vendor_info_step3(req, vendor_id, ln=CFG_SITE_LANG):
     """
     Update the library's information.
 
     vendor_id - identify the vendor. It is also the primary key of
                  the table crcVENDOR.
 
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     vendor_info = db.get_vendor_details(vendor_id)
 
     navtrail_previous_links = '<a class="navtrail"' \
                               ' href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_update_vendor_info_step3(vendor_info=vendor_info,
                                                                   ln=ln)
 
     return page(title=_("Update vendor information"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def update_vendor_info_step4(req, name, email, phone, address,
                              vendor_id, ln=CFG_SITE_LANG):
     """
     Update the vendor's information.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     tup_infos = (vendor_id, name, email, phone, address)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_update_vendor_info_step4(tup_infos=tup_infos,
                                                                   ln=ln)
 
     return page(title=_("Update vendor information"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def update_vendor_info_step5(req, name, email, phone, address,
                              vendor_id, ln=CFG_SITE_LANG):
     """
     Update the library's information.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     db.update_vendor_info(vendor_id, name, email, phone, address)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_update_vendor_info_step5(ln=ln)
 
     return page(title=_("Update vendor information"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def search_vendor_step1(req, ln=CFG_SITE_LANG):
     """
     Display the form where we can search a vendor (by name or email).
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     infos = []
 
     navtrail_previous_links = '<a class="navtrail"' \
                               ' href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_search_vendor_step1(infos=infos,
                                                              ln=ln)
 
     return page(title=_("Search vendor"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def search_vendor_step2(req, column, string, ln=CFG_SITE_LANG):
     """
     Search a vendor and return a list with all the possible results, using the
     parameters received from the previous step.
 
     column - identify the column, of the table crcVENDOR, that will be
              considered during the search. Can be 'name' or 'email'.
 
     str - string used for the search process.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     if not string:
         infos = []
         infos.append(_('Empty string.') + ' ' + _('Please, try again.'))
         body = bc_templates.tmpl_search_vendor_step1(infos=infos,
                                                              ln=ln)
     elif string == '*':
         result = db.get_all_vendors()
         body = bc_templates.tmpl_search_vendor_step2(result=result, ln=ln)
 
     else:
         if column == 'name':
             result = db.search_vendor_by_name(string)
         else:
             result = db.search_vendor_by_email(string)
         body = bc_templates.tmpl_search_vendor_step2(result=result, ln=ln)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     return page(title=_("Search vendor"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def get_vendor_details(req, vendor_id, ln=CFG_SITE_LANG):
     """
     Display the details of a vendor.
 
     @type vendor_id:    integer.
     @param vendor_id:   identify the vendor. It is also the primary key of
                         the table crcVENDOR.
 
     @return:            vendor details.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     vendor_details = db.get_vendor_details(vendor_id)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               ' href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_vendor_details(vendor_details=vendor_details,
                                                         ln=ln)
 
     return page(title=_("Vendor details"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def get_vendor_notes(req, vendor_id, add_notes, new_note, ln=CFG_SITE_LANG):
     """
     Retrieve notes related with a vendor.
 
     vendor_id - identify the vendor. It is also the primary key of
                 the table crcVENDOR.
 
     @param add_notes:  display the textarea where will be written a new notes.
 
     @param new_notes:  note that will be added to the others vendor's notes.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     if new_note:
         date = '[' + time.ctime() + '] '
         new_line = '\n'
         new_note = date + new_note + new_line
         db.add_new_vendor_note(new_note, vendor_id)
 
     vendor_notes = db.get_vendor_notes(vendor_id)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_vendor_notes(vendor_notes=vendor_notes,
                                                       vendor_id=vendor_id,
                                                       add_notes=add_notes,
                                                       ln=ln)
     return page(title=_("Vendor notes"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def register_ill_request_with_no_recid_step1(req, borrower_id,
                                              ln=CFG_SITE_LANG):
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     infos = []
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_register_ill_request_with_no_recid_step1(
                                                         infos=infos,
                                                         borrower_id=borrower_id,
                                                         admin=True, ln=ln)
 
     return page(title=_("Register ILL request"),
                 uid=id_user,
                 req=req,
                 metaheaderadd = "<link rel=\"stylesheet\" href=\"%s/img/jquery/jquery-ui.css\" type=\"text/css\" />" % CFG_SITE_SECURE_URL,
                 body=body,
                 language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def register_ill_request_with_no_recid_step2(req, title, authors, place,
                             publisher, year, edition, isbn, budget_code,
                             period_of_interest_from, period_of_interest_to,
                             additional_comments, only_edition, key, string,
                             borrower_id, ln=CFG_SITE_LANG):
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     infos = []
     book_info = (title, authors, place, publisher, year, edition, isbn)
     request_details = (budget_code, period_of_interest_from,
                        period_of_interest_to, additional_comments, only_edition)
 
 
     if borrower_id in (None, '', 'None'):
         body = None
         if not key:
             borrowers_list = None
 
         elif not string:
             infos.append(_('Empty string.') + ' ' + _('Please, try again.'))
             borrowers_list = None
 
         else:
             if validate_date_format(period_of_interest_from) is False:
                 infos = []
                 infos.append(_("The period of interest %(x_strong_tag_open)sFrom: %(x_date)s%(x_strong_tag_close)s is not a valid date or date format") % {'x_date': period_of_interest_from, 'x_strong_tag_open': '<strong>', 'x_strong_tag_close': '</strong>'})
 
                 body = bc_templates.tmpl_register_ill_request_with_no_recid_step1(
                                                             infos=infos,
                                                             borrower_id=None,
                                                             admin=True,
                                                             ln=ln)
 
             elif validate_date_format(period_of_interest_to) is False:
                 infos = []
                 infos.append(_("The period of interest %(x_strong_tag_open)sTo: %(x_date)s%(x_strong_tag_close)s is not a valid date or date format") % {'x_date': period_of_interest_to, 'x_strong_tag_open': '<strong>', 'x_strong_tag_close': '</strong>'})
 
                 body = bc_templates.tmpl_register_ill_request_with_no_recid_step1(
                                                                     infos=infos,
                                                                     ln=ln)
 
             else:
                 result = search_user(key, string)
 
                 borrowers_list = []
                 if len(result) == 0:
                     infos.append(_("0 borrowers found."))
                 else:
                     for user in result:
                         borrower_data = db.get_borrower_data_by_id(user[0])
                         borrowers_list.append(borrower_data)
 
         if body == None:
             body = bc_templates.tmpl_register_ill_request_with_no_recid_step2(
                            book_info=book_info, request_details=request_details,
                            result=borrowers_list, key=key, string=string,
                            infos=infos, ln=ln)
 
     else:
         user_info = db.get_borrower_data_by_id(borrower_id)
         return register_ill_request_with_no_recid_step3(req, title, authors,
                                             place, publisher,year, edition,
                                             isbn, user_info, budget_code,
                                             period_of_interest_from,
                                             period_of_interest_to,
                                             additional_comments, only_edition,
                                             ln)
 
 
     navtrail_previous_links = '<a class="navtrail" ' \
                     'href="%s/help/admin">Admin Area' \
                     '</a> &gt; <a class="navtrail" ' \
                     'href="%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s">'\
                     'Circulation Management' \
                     '</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
 
 
 
     return page(title=_("Register ILL request"),
                     uid=id_user,
                     req=req,
                     body=body, language=ln,
                     navtrail=navtrail_previous_links,
                     lastupdated=__lastupdated__)
 
 
 def register_ill_request_with_no_recid_step3(req, title, authors, place,
                                                 publisher, year, edition, isbn,
                                                 user_info, budget_code,
                                                 period_of_interest_from,
                                                 period_of_interest_to,
                                                 additional_comments,
                                                 only_edition, ln=CFG_SITE_LANG):
 
     navtrail_previous_links = '<a class="navtrail" ' \
                     'href="%s/help/admin">Admin Area' \
                     '</a> &gt; <a class="navtrail" ' \
                     'href="%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s">'\
                     'Circulation Management' \
                     '</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     request_details = (budget_code, period_of_interest_from,
                        period_of_interest_to, additional_comments, only_edition)
 
     book_info = (title, authors, place, publisher, year, edition, isbn)
 
     if user_info is None:
         return register_ill_request_with_no_recid_step2(req, title, authors,
                             place, publisher, year, edition, isbn, budget_code,
                             period_of_interest_from, period_of_interest_to,
                             additional_comments, only_edition, 'name', None,
                             None, ln)
 
     else:
         body = bc_templates.tmpl_register_ill_request_with_no_recid_step3(
                                                 book_info=book_info,
                                                 user_info=user_info,
                                                 request_details=request_details,
                                                 admin=True,
                                                 ln=ln)
 
         return page(title=_("Register ILL request"),
                     uid=id_user,
                     req=req,
                     body=body, language=ln,
                     navtrail=navtrail_previous_links,
                     lastupdated=__lastupdated__)
 
 def register_ill_request_with_no_recid_step4(req, book_info, borrower_id,
                                              request_details, ln):
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                     'href="%s/help/admin">Admin Area' \
                     '</a> &gt; <a class="navtrail" ' \
                     'href="%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s">'\
                     'Circulation Management' \
                     '</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
 
     _ = gettext_set_language(ln)
 
     (title, authors, place, publisher, year, edition, isbn) = book_info
     #create_ill_record(book_info))
 
     (budget_code, period_of_interest_from,
      period_of_interest_to, library_notes, only_edition) = request_details
 
     ill_request_notes = {}
     if library_notes:
         ill_request_notes[time.strftime("%Y-%m-%d %H:%M:%S")] = \
                                                             str(library_notes)
 
 ### budget_code ###
     if db.get_borrower_data_by_id(borrower_id) == None:
         _ = gettext_set_language(ln)
         infos = []
         infos.append(_("<strong>Request not registered:</strong> wrong borrower id"))
         body = bc_templates.tmpl_register_ill_request_with_no_recid_step2(
                                 book_info=book_info,
                                 request_details=request_details, result=[],
                                 key='name', string=None, infos=infos, ln=ln)
 
         return page(title=_("Register ILL request"),
                     uid=id_user,
                     req=req,
                     body=body, language=ln,
                     navtrail=navtrail_previous_links,
                     lastupdated=__lastupdated__)
     else:
         book_info = {'title': title, 'authors': authors, 'place': place,
                      'publisher': publisher,'year' : year,  'edition': edition,
                      'isbn' : isbn}
         db.ill_register_request_on_desk(borrower_id, book_info,
                                     period_of_interest_from,
                                     period_of_interest_to,
                                     CFG_BIBCIRCULATION_ILL_STATUS_NEW,
                                     str(ill_request_notes),
                                     only_edition, 'book', budget_code)
 
     return list_ill_request(req, CFG_BIBCIRCULATION_ILL_STATUS_NEW, ln)
 
 
 def get_borrower_ill_details(req, borrower_id, ln=CFG_SITE_LANG):
     """
     Display ILL details of a borrower.
 
     @type  borrower_id: integer.
     @param borrower_id: identify the borrower. It is also the primary key of
                         the table crcBORROWER.
 
     @type  ill_id:  integer.
     @param ill_id:  identify the ILL request. It is also the primary key
                     of the table crcILLREQUEST.
 
     @return:        borrower ILL details.
     """
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     result = db.get_ill_requests_details(borrower_id)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     name = db.get_borrower_name(borrower_id)
 
     title = _("ILL details") + "- %s" % (name)
     body = bc_templates.tmpl_borrower_ill_details(result=result,
                                                   borrower_id=borrower_id,
                                                   ln=ln)
 
     return page(title=title,
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def bor_ill_historical_overview(req, borrower_id, ln):
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     result = db.bor_ill_historical_overview(borrower_id)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     name = db.get_borrower_name(borrower_id)
 
     title = _("ILL historical overview") + " - %s" % (name)
     body = bc_templates.tmpl_borrower_ill_details(result=result,
                                                   borrower_id=borrower_id,
                                                   ln=ln)
 
     return page(title=title,
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def get_ill_library_notes(req, ill_id, delete_key, library_notes,
                           ln=CFG_SITE_LANG):
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     if delete_key and ill_id:
         ill_notes = eval(db.get_ill_notes(ill_id))
         del ill_notes[delete_key]
         db.update_ill_notes(ill_id, ill_notes)
 
     elif library_notes:
         if db.get_ill_notes(ill_id):
             ill_notes = eval(db.get_ill_notes(ill_id))
         else:
             ill_notes = {}
 
         ill_notes[time.strftime("%Y-%m-%d %H:%M:%S")] = str(library_notes)
         db.update_ill_notes(ill_id, ill_notes)
 
     ill_notes = db.get_ill_notes(ill_id)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     body = bc_templates.tmpl_ill_notes(ill_notes=ill_notes,
                                                    ill_id=ill_id,
                                                    ln=ln)
     return page(title=_("ILL notes"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def get_expired_loans_with_requests(req, request_id, ln=CFG_SITE_LANG):
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     if request_id:
         db.update_loan_request_status(request_id,
                                     CFG_BIBCIRCULATION_REQUEST_STATUS_CANCELLED)
         #update_request_data(request_id)
         result = db.get_expired_loans_with_requests()
 
     else:
         result = db.get_expired_loans_with_requests()
 
     navtrail_previous_links = '<a class="navtrail" ' \
                     'href="%s/help/admin">Admin Area' \
                     '</a> &gt; <a class="navtrail" ' \
                     'href="%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s">'\
                     'Circulation Management' \
                     '</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
 
     body = bc_templates.tmpl_get_expired_loans_with_requests(result=result,
                                                              ln=ln)
 
     return page(title=_("Overdue loans with holds"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def register_ill_book_request(req, borrower_id, ln=CFG_SITE_LANG):
     """
     Display a form where is possible to searh for an item.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                     'href="%s/help/admin">Admin Area' \
                     '</a> &gt; <a class="navtrail" ' \
                     'href="%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s">'\
                     'Circulation Management' \
                     '</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
 
     _ = gettext_set_language(ln)
 
     infos = []
 
     body = bc_templates.tmpl_register_ill_book_request(infos=infos,
                                                        borrower_id=borrower_id,
                                                        ln=ln)
 
     return page(title=_("Register ILL Book request"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def register_ill_book_request_result(req, borrower_id, p, f,  ln=CFG_SITE_LANG):
     """
     Search an item and return a list with all the possible results. To retrieve
     the information desired, we use the method 'perform_request_search' (from
     search_engine.py). In the case of BibCirculation, we are just looking for
     books (items) inside the collection 'Books'.
 
     @type p:   string
     @param p:  search pattern
 
     @type f:   string
     @param f:  search field
 
     @return:   list of recids
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     infos = []
     if p == '':
         infos.append(_('Empty string.') + ' ' + _('Please, try again.'))
         body = bc_templates.tmpl_register_ill_book_request(infos=infos,
                                                         borrower_id=borrower_id,
                                                         ln=ln)
     else:
         if f == 'barcode':
             p = p.strip('\'" \t')
             recid = db.get_recid(p)
 
             if recid is None:
                 infos.append(_('The barcode %(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s does not exist on BibCirculation database.') % {'x_barcode': p, 'x_strong_tag_open': '<strong>', 'x_strong_tag_close': '</strong>'})
                 body = bc_templates.tmpl_register_ill_book_request(infos=infos,
                                                         borrower_id=borrower_id,
                                                         ln=ln)
             else:
                 body = bc_templates.tmpl_register_ill_book_request_result(
                                                         result=[recid],
                                                         borrower_id=borrower_id,
                                                         ln=ln)
         else:
             result = perform_request_search(cc="Books", sc="1", p=p, f=f)
             if len(result) == 0:
                 return register_ill_request_with_no_recid_step1(req,
                                                                 borrower_id, ln)
             else:
                 body = bc_templates.tmpl_register_ill_book_request_result(
                                                         result=result,
                                                         borrower_id=borrower_id,
                                                         ln=ln)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                     'href="%s/help/admin">Admin Area' \
                     '</a> &gt; <a class="navtrail" ' \
                     'href="%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s">'\
                     'Circulation Management' \
                     '</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
 
     return page(title=_("Register ILL Book request"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def register_ill_book_request_from_borrower_page(req, borrower_id,
                                                  ln=CFG_SITE_LANG):
     """
     Display a form where is possible to searh for an item.
     """
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                     'href="%s/help/admin">Admin Area' \
                     '</a> &gt; <a class="navtrail" ' \
                     'href="%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s">'\
                     'Circulation Management' \
                     '</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
 
     _ = gettext_set_language(ln)
 
     infos = []
 
     body = bc_templates.tmpl_register_ill_book_request_from_borrower_page(
                                                         infos=infos,
                                                         borrower_id=borrower_id,
                                                         ln=ln)
 
     return page(title=_("Register ILL Book request"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def register_ill_request_from_borrower_page_step1(req, borrower_id,
                                                   ln=CFG_SITE_LANG):
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
     infos = []
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     _ = gettext_set_language(ln)
 
     body = bc_templates.tmpl_register_ill_request_from_borrower_page_step1(
                                                         infos=infos,
                                                         borrower_id=borrower_id,
                                                         ln=ln)
 
     return page(title=_("Register ILL request"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def register_ill_request_from_borrower_page_step2(req, borrower_id, title,
                                     authors, place, publisher, year, edition,
                                     isbn, period_of_interest_from,
                                     period_of_interest_to, additional_comments,
                                     only_edition, ln=CFG_SITE_LANG):
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     infos = []
 
     if validate_date_format(period_of_interest_from) is False:
 
         infos.append(_("The period of interest %(x_strong_tag_open)sFrom: %(x_date)s%(x_strong_tag_close)s is not a valid date or date format") % {'x_date': period_of_interest_from, 'x_strong_tag_open': '<strong>', 'x_strong_tag_close': '</strong>'})
 
         body = bc_templates.tmpl_register_ill_request_from_borrower_page_step1(
                                                         infos=infos,
                                                         borrower_id=borrower_id,
                                                         ln=ln)
 
     elif validate_date_format(period_of_interest_to) is False:
         infos.append(_("The period of interest %(x_strong_tag_open)sTo: %(x_date)s%(x_strong_tag_close)s is not a valid date or date format") % {'x_date': period_of_interest_to, 'x_strong_tag_open': '<strong>', 'x_strong_tag_close': '</strong>'})
 
         body = bc_templates.tmpl_register_ill_request_from_borrower_page_step1(
                                                         infos=infos,
                                                         borrower_id=borrower_id,
                                                         ln=ln)
     else:
         book_info = (title, authors, place, publisher, year, edition, isbn)
         user_info = db.get_borrower_details(borrower_id)
         request_details = (period_of_interest_from, period_of_interest_to,
                            additional_comments, only_edition)
 
         body = bc_templates.tmpl_register_ill_request_with_no_recid_step3(
                                                 book_info=book_info,
                                                 user_info=user_info,
                                                 request_details=request_details,
                                                 admin=True, ln=ln)
 
 
     navtrail_previous_links = '<a class="navtrail" ' \
                     'href="%s/help/admin">Admin Area' \
                     '</a> &gt; <a class="navtrail" ' \
                     'href="%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s">'\
                     'Circulation Management' \
                     '</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
 
     return page(title=_("Register ILL request"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
-def register_purchase_request_step1(req, recid, req_type, title, authors,
+def register_purchase_request_step1(req, recid, request_type, title, authors,
                         place, publisher, year, edition, this_edition_only,
                         isbn, standard_number,
                         budget_code, cash, period_of_interest_from,
                         period_of_interest_to, additional_comments,
                         ln=CFG_SITE_LANG):
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     infos = []
 
     navtrail_previous_links = '<a class="navtrail" ' \
                     'href="%s/help/admin">Admin Area' \
                     '</a> &gt; <a class="navtrail" ' \
                     'href="%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s">'\
                     'Circulation Management' \
                     '</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
 
     if recid != '':
         (title, year, authors,
          isbn, publisher) = book_information_from_MARC(int(recid))
 
     body = bc_templates.tmpl_register_purchase_request_step1(infos=infos,
-                                fields=(req_type, title, authors, place, publisher,
+                                fields=(request_type, title, authors, place, publisher,
                                         year, edition, this_edition_only,
                                         isbn, standard_number,
                                         budget_code, cash,
                                         period_of_interest_from,
                                         period_of_interest_to,
                                         additional_comments),
                                 ln=ln)
 
     return page(title=_("Register purchase request"),
                 uid=id_user,
                 req=req,
                 body=body,
                 language=ln,
                 metaheaderadd='<link rel="stylesheet" ' \
                                     'href="%s/img/jquery-ui.css" ' \
                                     'type="text/css" />' % CFG_SITE_SECURE_URL,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
-def register_purchase_request_step2(req, type, title, authors,
+def register_purchase_request_step2(req, request_type, title, authors,
                         place, publisher, year, edition, this_edition_only,
                         isbn, standard_number,
                         budget_code, cash, period_of_interest_from,
                         period_of_interest_to, additional_comments,
                         p, f, ln=CFG_SITE_LANG):
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                     'href="%s/help/admin">Admin Area' \
                     '</a> &gt; <a class="navtrail" ' \
                     'href="%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s">'\
                     'Circulation Management' \
                     '</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
 
     infos = []
 
     if cash and budget_code == '':
         budget_code = 'cash'
 
-    fields = (type, title, authors, place, publisher, year, edition,
+    fields = (request_type, title, authors, place, publisher, year, edition,
               this_edition_only, isbn, standard_number, budget_code,
               cash, period_of_interest_from, period_of_interest_to,
               additional_comments)
 
     if budget_code == '' and not cash:
         infos.append(_("Payment method information is mandatory. Please, type your budget code or tick the 'cash' checkbox."))
         body = bc_templates.tmpl_register_purchase_request_step1(infos=infos,
                                                            fields=fields, ln=ln)
 
     else:
 
 ########################
 ########################
         if p and not f:
             infos.append(_('Empty string.') + ' ' + _('Please, try again.'))
 
             body = bc_templates.tmpl_register_purchase_request_step2(
                                                 infos=infos, fields=fields,
                                                 result=None, p=p, f=f, ln=ln)
 
             navtrail_previous_links = '<a class="navtrail" ' \
                         'href="%s/help/admin">Admin Area' \
                         '</a> &gt; <a class="navtrail" ' \
                         'href="%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s">'\
                         'Circulation Management' \
                         '</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
 
             return page(title=_("Register ILL request"),
                         uid=id_user,
                         req=req,
                         body=body, language=ln,
                         navtrail=navtrail_previous_links,
                         lastupdated=__lastupdated__)
 
         result = search_user(f, p)
         borrowers_list = []
 
         if len(result) == 0 and f:
             if CFG_CERN_SITE:
                 infos.append(_("0 borrowers found.") + ' ' +_("Search by CCID."))
             else:
                 new_borrower_link = create_html_link(CFG_SITE_SECURE_URL +
                                 '/admin2/bibcirculation/add_new_borrower_step1',
                                 {'ln': ln}, _("Register new borrower."))
                 message = _("0 borrowers found.") + ' ' + new_borrower_link
                 infos.append(message)
         else:
             for user in result:
                 borrower_data = db.get_borrower_data_by_id(user[0])
                 borrowers_list.append(borrower_data)
 
         body = bc_templates.tmpl_register_purchase_request_step2(
                                                 infos=infos, fields=fields,
                                                 result=borrowers_list, p=p,
                                                 f=f, ln=ln)
 ########################
 ########################
 
     return page(title=_("Register purchase request"),
                 uid=id_user,
                 req=req,
                 body=body,
                 language=ln,
                 metaheaderadd='<link rel="stylesheet" ' \
                                     'href="%s/img/jquery-ui.css" ' \
                                     'type="text/css" />' % CFG_SITE_SECURE_URL,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
-def register_purchase_request_step3(req, type, title, authors,
+def register_purchase_request_step3(req, request_type, title, authors,
                         place, publisher, year, edition, this_edition_only,
                         isbn, standard_number,
                         budget_code, cash, period_of_interest_from,
                         period_of_interest_to, additional_comments,
                         borrower_id, ln=CFG_SITE_LANG):
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                     'href="%s/help/admin">Admin Area' \
                     '</a> &gt; <a class="navtrail" ' \
                     'href="%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s">'\
                     'Circulation Management' \
                     '</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
 
     infos = []
 
     if budget_code == '' and not cash:
         infos.append(_("Payment method information is mandatory. Please, type your budget code or tick the 'cash' checkbox."))
         body = bc_templates.tmpl_register_purchase_request_step1(infos=infos,
-                                fields=(type, title, authors, place, publisher,
+                                fields=(request_type, title, authors, place, publisher,
                                         year, edition, this_edition_only,
                                         isbn, standard_number,
                                         budget_code, cash,
                                         period_of_interest_from,
                                         period_of_interest_to,
                                         additional_comments),
                                 ln=ln)
     else:
         if borrower_id == '':
             borrower_id = db.get_borrower_id_by_email(db.get_invenio_user_email(id_user))
 
         item_info = {'title': title, 'authors': authors, 'place': place,
                      'publisher': publisher, 'year' : year,  'edition': edition,
                      'isbn' : isbn, 'standard_number': standard_number}
 
         ill_request_notes = {}
         if additional_comments:
             ill_request_notes[time.strftime("%Y-%m-%d %H:%M:%S")] \
                                                       = str(additional_comments)
 
         if cash and budget_code == '':
             budget_code = 'cash'
 
         db.ill_register_request_on_desk(borrower_id, item_info,
                                         period_of_interest_from,
                                         period_of_interest_to,
                                         CFG_BIBCIRCULATION_ACQ_STATUS_NEW,
                                         str(ill_request_notes),
-                                        this_edition_only, type, budget_code)
+                                        this_edition_only, request_type, budget_code)
 
         return redirect_to_url(req,
                 '%s/admin2/bibcirculation/list_acquisition?ln=%s&status=%s' % \
                                             (CFG_SITE_SECURE_URL, ln,
                                              CFG_BIBCIRCULATION_ACQ_STATUS_NEW))
 
     return page(title=_("Register purchase request"),
                 uid=id_user,
                 req=req,
                 body=body,
                 language=ln,
                 metaheaderadd='<link rel="stylesheet" ' \
                                     'href="%s/img/jquery-ui.css" ' \
                                     'type="text/css" />' % CFG_SITE_SECURE_URL,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def register_ill_article_request_step1(req, ln=CFG_SITE_LANG):
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     infos = []
 
     navtrail_previous_links = '<a class="navtrail" ' \
                    'href="%s/help/admin">Admin Area' \
                    '</a> &gt; <a class="navtrail" ' \
                    'href="%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s">' \
                    'Circulation Management' \
                    '</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
 
     body = bc_templates.tmpl_register_ill_article_request_step1(infos=infos,
                                                                 ln=ln)
 
     return page(title=_("Register ILL Article request"),
                 uid=id_user,
                 req=req,
                 body=body,
                 metaheaderadd = "<link rel=\"stylesheet\" href=\"%s/img/jquery/jquery-ui.css\" type=\"text/css\" />"%(CFG_SITE_SECURE_URL),
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def register_ill_article_request_step2(req, periodical_title, article_title,
                                        author, report_number, volume, issue,
                                        pages, year, budget_code, issn,
                                        period_of_interest_from,
                                        period_of_interest_to,
                                        additional_comments, key, string,
                                        ln=CFG_SITE_LANG):
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     infos = []
 
     if key and not string:
         infos.append(_('Empty string.') + ' ' + _('Please, try again.'))
         article_info = (periodical_title, article_title, author, report_number,
                         volume, issue, pages, year, issn)
         request_details = (period_of_interest_from, period_of_interest_to,
                            budget_code, additional_comments)
 
         body = bc_templates.tmpl_register_ill_article_request_step2(
                                                 article_info=article_info,
                                                 request_details=request_details,
                                                 result=None, key=key,
                                                 string=string, infos=infos,
                                                 ln=ln)
 
         navtrail_previous_links = '<a class="navtrail" ' \
                     'href="%s/help/admin">Admin Area' \
                     '</a> &gt; <a class="navtrail" ' \
                     'href="%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s">'\
                     'Circulation Management' \
                     '</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
 
         return page(title=_("Register ILL request"),
                     uid=id_user,
                     req=req,
                     body=body, language=ln,
                     navtrail=navtrail_previous_links,
                     lastupdated=__lastupdated__)
 
     result = search_user(key, string)
     borrowers_list = []
 
     if len(result) == 0 and key:
         if CFG_CERN_SITE:
             infos.append(_("0 borrowers found.") + ' ' +_("Search by CCID."))
         else:
             new_borrower_link = create_html_link(CFG_SITE_SECURE_URL +
                                 '/admin2/bibcirculation/add_new_borrower_step1',
                                 {'ln': ln}, _("Register new borrower."))
             message = _("0 borrowers found.") + ' ' + new_borrower_link
             infos.append(message)
     else:
         for user in result:
             borrower_data = db.get_borrower_data_by_id(user[0])
             borrowers_list.append(borrower_data)
 
     if validate_date_format(period_of_interest_from) is False:
         infos = []
 
         infos.append(_("The period of interest %(x_strong_tag_open)sFrom: %(x_date)s%(x_strong_tag_close)s is not a valid date or date format") % {'x_date': period_of_interest_from, 'x_strong_tag_open': '<strong>', 'x_strong_tag_close': '</strong>'})
 
         body = bc_templates.tmpl_register_ill_article_request_step1(infos=infos,
                                                                     ln=ln)
 
     elif validate_date_format(period_of_interest_to) is False:
         infos = []
         infos.append(_("The period of interest %(x_strong_tag_open)sTo: %(x_date)s%(x_strong_tag_close)s is not a valid date or date format") % {'x_date': period_of_interest_to, 'x_strong_tag_open': '<strong>', 'x_strong_tag_close': '</strong>'})
 
         body = bc_templates.tmpl_register_ill_article_request_step1(infos=infos,
                                                                     ln=ln)
 
     else:
         article_info = (periodical_title, article_title, author, report_number,
                         volume, issue, pages, year, issn)
 
         request_details = (period_of_interest_from, period_of_interest_to,
                            budget_code, additional_comments)
 
         body = bc_templates.tmpl_register_ill_article_request_step2(
                                                 article_info=article_info,
                                                 request_details=request_details,
                                                 result=borrowers_list,
                                                 key=key, string=string,
                                                 infos=infos, ln=ln)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                     'href="%s/help/admin">Admin Area' \
                     '</a> &gt; <a class="navtrail" ' \
                     'href="%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s">'\
                     'Circulation Management' \
                     '</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
 
     return invenio.webpage.page(title=_("Register ILL request"),
                 uid=id_user,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def register_ill_article_request_step3(req, periodical_title, title, authors,
                                        report_number, volume, issue,
                                        page_number, year, issn, user_info,
                                        request_details, ln=CFG_SITE_LANG):
 
     #id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     #info = (title, authors, "", "", year, "", issn)
 
     #create_ill_record(info)
 
     item_info = {'periodical_title': periodical_title, 'title': title,
                  'authors': authors, 'place': "", 'publisher': "",
                  'year' : year,  'edition': "", 'issn' : issn,
                  'volume': volume, 'issue': issue, 'page': page_number }
 
 
     (period_of_interest_from, period_of_interest_to, budget_code,
      library_notes) = request_details
 
     only_edition = ""
 
     if user_info is None:
         return register_ill_article_request_step2(req, periodical_title, title,
                                         authors, report_number, volume, issue,
                                         page_number, year, budget_code, issn,
                                         period_of_interest_from,
                                         period_of_interest_to,
                                         library_notes, 'name', None, ln)
     else:
         borrower_id = user_info[0]
 
         ill_request_notes = {}
         if library_notes:
             ill_request_notes[time.strftime("%Y-%m-%d %H:%M:%S")] \
                                                            = str(library_notes)
 
         db.ill_register_request_on_desk(borrower_id, item_info,
                                         period_of_interest_from,
                                         period_of_interest_to,
                                         CFG_BIBCIRCULATION_ILL_STATUS_NEW,
                                         str(ill_request_notes),
                                         only_edition, 'article', budget_code)
 
         return list_ill_request(req, CFG_BIBCIRCULATION_ILL_STATUS_NEW, ln)
 
 def ill_search(req, ln=CFG_SITE_LANG):
 
     infos = []
 
     navtrail_previous_links = '<a class="navtrail" ' \
                     'href="%s/help/admin">Admin Area' \
                     '</a> &gt; <a class="navtrail" ' \
                     'href="%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s">'\
                     'Circulation Management' \
                     '</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
 
     id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     body = bc_templates.tmpl_ill_search(infos=infos, ln=ln)
 
     return page(title=_("ILL search"),
                 uid=id_user,
                 req=req,
                 body=body,
                 language=ln,
             metaheaderadd='<link rel="stylesheet" href="%s/img/jquery-ui.css" '\
                                 'type="text/css" />' % CFG_SITE_SECURE_URL,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def ill_search_result(req, p, f, date_from, date_to, ln):
     """
     Search an item and return a list with all the possible results. To retrieve
     the information desired, we use the method 'perform_request_search' (from
     search_engine.py). In the case of BibCirculation, we are just looking for
     books (items) inside the collection 'Books'.
 
     @type p:   string
     @param p:  search pattern
 
     @type f:   string
     @param f:  search field
 
     @return:   list of recids
     """
 
     navtrail_previous_links = '<a class="navtrail" ' \
                     'href="%s/help/admin">Admin Area' \
                     '</a> &gt; <a class="navtrail" ' \
                     'href="%s/admin2/bibcirculation/loan_on_desk_step1?ln=%s">'\
                     'Circulation Management' \
                     '</a> ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
 
     #id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     if not has_date_format(date_from):
         date_from = '0000-00-00'
     if not has_date_format(date_to):
         date_to = '9999-12-31'
 
     if f == 'title':
         ill_req = db.search_ill_requests_title(p, date_from, date_to)
         body = bc_templates.tmpl_list_ill_request(ill_req=ill_req, ln=ln)
 
     elif f == 'ILL_request_ID':
         ill_req = db.search_ill_requests_id(p, date_from, date_to)
         body = bc_templates.tmpl_list_ill_request(ill_req=ill_req, ln=ln)
 
     elif f == 'cost':
         ill_req = db.search_acq_requests_cost(p, date_from, date_to)
         body = bc_templates.tmpl_list_acquisition(ill_req=ill_req, ln=ln)
 
     elif f == 'notes':
         ill_req = db.search_acq_requests_notes(p, date_from, date_to)
         body = bc_templates.tmpl_list_acquisition(ill_req=ill_req, ln=ln)
 
 
     #body = bc_templates.tmpl_list_ill_request(ill_req=ill_req, ln=ln)
 
     return page(title=_("List of ILL requests"),
                 req=req,
                 body=body,
                 language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 
 def delete_copy_step1(req, barcode, ln):
     #id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     infos = []
 
     navtrail_previous_links = '<a class="navtrail" ' \
                                  'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
 
     barcode = barcode.strip('\'" \t')
     recid = db.get_recid(barcode)
     if recid:
         #recid = recid[0]
 
         infos.append(_("Do you really want to delete this copy of the book?"))
 
         copies = db.get_item_copies_details(recid)
 
         title = _("Delete copy")
         body = bc_templates.tmpl_delete_copy_step1(barcode_to_delete=barcode,
                                                    recid=recid,
                                                    result=copies,
                                                    infos=infos,
                                                    ln=ln)
 
     else:
         message = _("""The barcode <strong>%s</strong> was not found""") % (barcode)
         infos.append(message)
         title = _("Item search")
         body = bc_templates.tmpl_item_search(infos=infos, ln=ln)
 
     return page(title=title,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)
 
 def delete_copy_step2(req, barcode, ln):
 
     #id_user = getUid(req)
     (auth_code, auth_message) = is_adminuser(req)
     if auth_code != 0:
         return mustloginpage(req, auth_message)
 
     _ = gettext_set_language(ln)
 
     infos = []
 
     barcode = barcode.strip('\'" \t')
     recid = db.get_recid(barcode)
 
     if recid:
         #recid = recid[0]
 
         if db.delete_copy(barcode)==1:
             message = _("The copy with barcode <strong>%s</strong> has been deleted.") % (barcode)
         else:
             message = _('It was NOT possible to delete the copy with barcode <strong>%s</strong>') % (barcode)
 
         infos.append(message)
 
         copies = db.get_item_copies_details(recid)
         requests = db.get_item_requests(recid)
         loans = db.get_item_loans(recid)
         req_hist_overview = db.get_item_requests_historical_overview(recid)
         loans_hist_overview = db.get_item_loans_historical_overview(recid)
 
         title = _("Item details")
         body = bc_templates.tmpl_get_item_details(
                                         recid=recid, copies=copies,
                                         requests=requests, loans=loans,
                                         req_hist_overview=req_hist_overview,
                                         loans_hist_overview=loans_hist_overview,
                                         infos=infos, ln=ln)
 
     else:
         message = _("The barcode <strong>%s</strong> was not found") % (barcode)
         infos.append(message)
         title = _("Item search")
         body = bc_templates.tmpl_item_search(infos=infos, ln=ln)
 
     navtrail_previous_links = '<a class="navtrail" ' \
                               'href="%s/help/admin">Admin Area' \
                               '</a>' % (CFG_SITE_SECURE_URL,)
     return page(title=title,
                 req=req,
                 body=body, language=ln,
                 navtrail=navtrail_previous_links,
                 lastupdated=__lastupdated__)