Index: WAeUP_SRP/base/Accommodation.py
===================================================================
--- WAeUP_SRP/base/Accommodation.py	(revision 2839)
+++ WAeUP_SRP/base/Accommodation.py	(revision 2845)
@@ -10,5 +10,5 @@
 from Products.CPSDocument.CPSDocument import CPSDocument
 from Products.CPSCore.CPSBase import CPSBaseBTreeFolder as BaseBTreeFolder
-from Products.WAeUP_SRP.WAeUPTables import AccommodationTable
+from Products.WAeUP_SRP.WAeUPTables import AccommodationTable,NOT_OCCUPIED
 import logging
 import csv,re,os
@@ -18,4 +18,5 @@
 p_home = Globals.package_home(globals())
 i_home = Globals.INSTANCE_HOME
+
 
 class AccoFolder(CPSDocument): ###(
@@ -47,43 +48,51 @@
         for hall in halls:
             #import pdb;pdb.set_trace()
-            h = hall.getContent()
+            hall_doc = hall.getContent()
             hall_gen = {}
             hall_gen['name'] = hall.Title
             count = 0
-            reserved = [(r.split('/')[0],int(r.split('/')[1])) for r in re.split(',|\.| ',h.reserved_rooms)
+            reserved = [(r.split('/')[0],int(r.split('/')[1])) for r in re.split(',|\.| ',hall_doc.reserved_rooms)
                                      if r]
-            #for block in range(1,int(h.nr_of_blocks)+1):
-            # for block in 'ABCDEFGHIJ'[:int(h.nr_of_blocks)]:
-            if set(h.blocks_for_female).intersection(set(h.blocks_for_male)):
+            #for block in range(1,int(hall_doc.nr_of_blocks)+1):
+            # for block in 'ABCDEFGHIJ'[:int(hall_doc.nr_of_blocks)]:
+            if set(hall_doc.blocks_for_female).intersection(set(hall_doc.blocks_for_male)):
                 return self.accommodation.acco_folder_view(beds_generated=beds_generated)
-            for block in h.blocks_for_female + h.blocks_for_male:
+            for block in hall_doc.blocks_for_female + hall_doc.blocks_for_male:
                 sex = 'male'
-                if block in h.blocks_for_female:
+                if block in hall_doc.blocks_for_female:
                     sex = 'female'
-                for floor in range(1,int(h.nr_of_floors)+1):
-                    for room in range(1,int(h.rooms_per_floor)+1):
-                        for bed in 'ABCDEFGH'[:int(h.beds_per_room)]:
+                for floor in range(1,int(hall_doc.nr_of_floors)+1):
+                    for room in range(1,int(hall_doc.rooms_per_floor)+1):
+                        for bed in 'ABCDEFGH'[:int(hall_doc.beds_per_room)]:
                             room_nr = floor*100 + room
                             bt = 're'
                             if (block,room_nr) in reserved:
                                 bt = "reserved"
-                            elif h.special_handling and not h.special_handling.startswith("no"):
-                                bt = h.special_handling
-                            elif bed in h.beds_for_fresh:
+                            elif hall_doc.special_handling and not hall_doc.special_handling.startswith("no"):
+                                bt = hall_doc.special_handling
+                            elif bed in hall_doc.beds_for_fresh:
                                 bt = 'fr'
-                            elif bed in h.beds_for_pre:
+                            elif bed in hall_doc.beds_for_pre:
                                 bt = 'pr'
-                            elif bed in h.beds_for_final:
+                            elif bed in hall_doc.beds_for_final:
                                 bt = 'fi'
-                            if h.special_handling.startswith("no_"):
-                                bt += "_" + h.special_handling[3:]
+                            if hall_doc.special_handling.startswith("no_"):
+                                bt += "_" + hall_doc.special_handling[3:]
                             bt = "%(sex)s_%(bt)s" % vars()
                             uid = '%s_%s_%d_%s' % (hall.getId(),block,room_nr,bed)
+                            d = {}
+                            d['bed'] = uid
+                            d['bed_type'] = bt
+                            d['sort_id'] = getattr(hall_doc,'sort_id')
+                            d['hall'] = hall.getId()
+                            d['student'] = NOT_OCCUPIED
                             try:
-                                freelist.addRecord(bed = uid, bed_type = bt,hall = hall.getId())
+                                #freelist.addRecord(bed = uid, bed_type = bt,hall = hall.getId())
+                                freelist.addRecord(**d)
                                 count +=1
                                 generated.append('"%(uid)s","%(bt)s"' % vars())
                             except ValueError:
                                 #freelist.modifyRecord(bed = uid, bed_type = bt,hall =hall.getId())
+                                #freelist.modifyRecord(**d)
                                 pass
             hall_gen['count']= count
@@ -239,7 +248,9 @@
 ###)
 
+###)
+
 class AccoHall(CPSDocument): ###(
     """
-    WAeUP AccoHall containing Departments
+    WAeUP AccoHall
     """
     meta_type = 'AccoHall'
Index: WAeUP_SRP/base/WAeUPTables.py
===================================================================
--- WAeUP_SRP/base/WAeUPTables.py	(revision 2839)
+++ WAeUP_SRP/base/WAeUPTables.py	(revision 2845)
@@ -41,4 +41,5 @@
 ADDING_SHEDULED = "adding_sheduled"
 OBJECT_CREATED = "object_created"
+NOT_OCCUPIED = 'not_occupied'
 
 from interfaces import IWAeUPTable
@@ -486,12 +487,15 @@
             name = self.name
         WAeUPTable.__init__(self, name)
-
+    
     def searchAndReserveBed(self, student_id,bed_type):
-        records = self.searchResults({'student' : student_id})
+        #records = self.searchResults({'student' : student_id})
+        import pdb;pdb.set_trace()
+        records = self.evalAdvancedQuery(Eq('student',student_id))
         if len(records) > 0:
             return -1,"Student with Id %s already booked bed %s." % (student_id,records[0].bed)
 
-        records = [r for r in self.searchResults({'bed_type' : bed_type}) if not r.student]
-        #import pdb;pdb.set_trace()
+        #records = [r for r in self.searchResults({'bed_type' : bed_type}) if not r.student]
+        query = Eq('bed_type',bed_type) & Eq('student',NOT_OCCUPIED)
+        records = self.evalAdvancedQuery(query,sortSpecs=('sort_id','bed'))
         if len(records) == 0:
             return -2,"No bed available"
Index: WAeUP_SRP/base/skins/waeup_accommodation/acco_folder_view.pt
===================================================================
--- WAeUP_SRP/base/skins/waeup_accommodation/acco_folder_view.pt	(revision 2839)
+++ WAeUP_SRP/base/skins/waeup_accommodation/acco_folder_view.pt	(revision 2845)
@@ -53,7 +53,7 @@
               <strong tal:content="row/title" /></a> </td>
             <td tal:content="row/id"> </td>
-            
+            <td tal:content="row/sort_id"> </td>
             <td> 
-            <a tal:condition="row/is_editable"
+              <a tal:condition="row/is_editable"
                 href="edit" tal:attributes="href string:/${row/url}/external_edit_form"
                 target="edit"
Index: WAeUP_SRP/base/skins/waeup_accommodation/getAccoFolderInfo.py
===================================================================
--- WAeUP_SRP/base/skins/waeup_accommodation/getAccoFolderInfo.py	(revision 2839)
+++ WAeUP_SRP/base/skins/waeup_accommodation/getAccoFolderInfo.py	(revision 2845)
@@ -12,4 +12,9 @@
 return Info about the Accommodation-Folder
 """
+try:
+    from Products.zdb import set_trace
+except:
+    def set_trace():
+        pass
 request = context.REQUEST
 
@@ -23,15 +28,18 @@
 items = []
 is_editable = mtool.checkPermission('Modify portal content', context)
-is_editable = False
-halls = context.portal_catalog(portal_type='AccoHall')
-for f in halls:
+#is_editable = False
+#halls = context.portal_catalog(portal_type='AccoHall')
+for id,hall in context.objectItems():
+    hall_doc = hall.getContent()
     row = {}
-    row['id'] = f.id
-    row['title'] = f.Title
-    row['url'] = "%s/%s" % (context.absolute_url(),f.id)
+    row['id'] = id
+    row['title'] = hall_doc.Title()
+    row['sort_id'] = getattr(hall_doc,'sort_id',0)
+    row['url'] = "%s/%s" % (context.absolute_url(),id)
     #fo = f.getObject()
     #row['is_editable'] = mtool.checkPermission('Modify portal content', fo)
     row['is_editable'] = is_editable
     items.append(row)
+items.sort(cmp=lambda x,y: cmp( x['sort_id'],y['sort_id']))
 info['items'] = items
 return info
Index: WAeUP_SRP/base/skins/waeup_accommodation/getAccoHallInfo.py
===================================================================
--- WAeUP_SRP/base/skins/waeup_accommodation/getAccoHallInfo.py	(revision 2839)
+++ WAeUP_SRP/base/skins/waeup_accommodation/getAccoHallInfo.py	(revision 2845)
@@ -12,4 +12,11 @@
 return Info about a Accommodation Hall
 """
+try:
+    from Products.zdb import set_trace
+except:
+    def set_trace():
+        pass
+    
+from Products.AdvancedQuery import Eq, Between, Le,In
 
 def cmp_bed(a,b):
@@ -23,5 +30,6 @@
 path_info = request.get('PATH_INFO').split('/')
 mtool = context.portal_membership
-pa = context.portal_accommodation
+portal_accommodation = context.portal_accommodation
+aq_accommodation = portal_accommodation.evalAdvancedQuery
 info = {}
 #dep_id = request.get('PATH_TRANSLATED').split('/')[-2]
@@ -30,16 +38,15 @@
 info['choosen_ids'] = request.get('ids',[])
 info['doc'] = context.getContent()
-bed_types = pa.uniqueValuesFor('bed_type')
+bed_types = portal_accommodation.uniqueValuesFor('bed_type')
 bt_list = []
 bt_names =  context.getBedTypeNames()
-res = pa.uniqueValuesFor('student')
-all_booked = [st for st in res if st]
+res = portal_accommodation.uniqueValuesFor('student')
+all_booked = [st for st in res if st and st != 'not_occupied']
 booked_list = []
-#from Products.zdb import set_trace;set_trace()
 for bt in bed_types:
-    total = len(pa(bed_type=bt,hall=context.getId()))
+    total = len(portal_accommodation(bed_type=bt,hall=context.getId()))
     if total <= 1:
         continue
-    booked = pa.searchResults({'bed_type': bt,
+    booked = portal_accommodation.searchResults({'bed_type': bt,
                                  'student':all_booked,
                                  'hall': context.getId()})
@@ -49,4 +56,18 @@
                     })
     booked_list.extend(booked)
+# query = ~Eq('student','not_occupied') 
+# beds = aq_accommodation(query,sortSpecs=('bed_type',))
+# bt_list = []
+# bt_names =  context.getBedTypeNames()
+# bt = 'xxx' 
+# for bed in beds:
+#     if bt != bed.bed_type:
+#         bt = bed.bed_type
+#         total = len(aq_accommodation(Eq('bed_type',bt)))
+#         bt_list.append({'name': bt_names[bt],
+#                         'total': total,
+#                         'reserved': len(booked),
+#                        })
+      
 info['bed_types'] = bt_list
 res_list = []
