merge and fix cubicwebSortValueExtraction pb which disappeared when tablesorter.js has been updated
authorSylvain Thénault <sylvain.thenault@logilab.fr>
Fri, 14 Oct 2011 09:21:45 +0200
changeset 7953 a37531c8a4a6
parent 7951 b7c825b00f64 (diff)
parent 7952 48330faf4cd7 (current diff)
child 7954 a3d3220669d6
merge and fix cubicwebSortValueExtraction pb which disappeared when tablesorter.js has been updated
server/migractions.py
web/data/cubicweb.js
web/data/jquery.tablesorter.js
web/facet.py
web/views/actions.py
web/views/facets.py
web/views/tableview.py
--- a/__pkginfo__.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/__pkginfo__.py	Fri Oct 14 09:21:45 2011 +0200
@@ -22,7 +22,7 @@
 
 modname = distname = "cubicweb"
 
-numversion = (3, 13, 8)
+numversion = (3, 14, 0)
 version = '.'.join(str(num) for num in numversion)
 
 description = "a repository of entities / relations for knowledge management"
@@ -40,10 +40,10 @@
 ]
 
 __depends__ = {
-    'logilab-common': '>= 0.56.2',
+    'logilab-common': '>= 0.56.3',
     'logilab-mtconverter': '>= 0.8.0',
     'rql': '>= 0.28.0',
-    'yams': '>= 0.33.0',
+    'yams': '>= 0.34.0',
     'docutils': '>= 0.6',
     #gettext                    # for xgettext, msgcat, etc...
     # web dependancies
--- a/bin/clone_deps.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/bin/clone_deps.py	Fri Oct 14 09:21:45 2011 +0200
@@ -63,7 +63,7 @@
     elif len(sys.argv) == 2:
         base_url = sys.argv[1]
     else:
-        print >> sys.stderr, 'usage %s [base_url]' %  sys.argv[0]
+        sys.stderr.write('usage %s [base_url]\n' %  sys.argv[0])
         sys.exit(1)
     print len(to_clone), 'repositories will be cloned'
     base_dir = normpath(join(dirname(__file__), pardir, pardir))
@@ -104,9 +104,9 @@
 To get started you may read http://docs.cubicweb.org/tutorials/base/index.html.
 """ % {'basedir': os.getcwd(), 'baseurl': base_url, 'sep': os.sep}
     if not_updated:
-        print >> sys.stderr, 'WARNING: The following repositories were not updated (no debian tag found):'
+        sys.stderr.write('WARNING: The following repositories were not updated (no debian tag found):\n')
         for path in not_updated:
-            print >> sys.stderr, '\t-', path
+            sys.stderr.write('\t-%s\n' % path)
 
 if __name__ == '__main__':
     main()
--- a/cwctl.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/cwctl.py	Fri Oct 14 09:21:45 2011 +0200
@@ -155,7 +155,7 @@
             try:
                 status = max(status, self.run_arg(appid))
             except (KeyboardInterrupt, SystemExit):
-                print >> sys.stderr, '%s aborted' % self.name
+                sys.stderr.write('%s aborted\n' % self.name)
                 return 2 # specific error code
         sys.exit(status)
 
@@ -164,14 +164,14 @@
         try:
             status = cmdmeth(appid)
         except (ExecutionError, ConfigurationError), ex:
-            print >> sys.stderr, 'instance %s not %s: %s' % (
-                appid, self.actionverb, ex)
+            sys.stderr.write('instance %s not %s: %s\n' % (
+                    appid, self.actionverb, ex))
             status = 4
         except Exception, ex:
             import traceback
             traceback.print_exc()
-            print >> sys.stderr, 'instance %s not %s: %s' % (
-                appid, self.actionverb, ex)
+            sys.stderr.write('instance %s not %s: %s\n' % (
+                    appid, self.actionverb, ex))
             status = 8
         return status
 
@@ -548,20 +548,19 @@
         helper.poststop() # do this anyway
         pidf = config['pid-file']
         if not exists(pidf):
-            print >> sys.stderr, "%s doesn't exist." % pidf
+            sys.stderr.write("%s doesn't exist.\n" % pidf)
             return
         import signal
         pid = int(open(pidf).read().strip())
         try:
             kill(pid, signal.SIGTERM)
         except Exception:
-            print >> sys.stderr, "process %s seems already dead." % pid
+            sys.stderr.write("process %s seems already dead.\n" % pid)
         else:
             try:
                 wait_process_end(pid)
             except ExecutionError, ex:
-                print >> sys.stderr, ex
-                print >> sys.stderr, 'trying SIGKILL'
+                sys.stderr.write('%s\ntrying SIGKILL\n' % ex)
                 try:
                     kill(pid, signal.SIGKILL)
                 except Exception:
--- a/dbapi.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/dbapi.py	Fri Oct 14 09:21:45 2011 +0200
@@ -223,13 +223,32 @@
     return repo_connect(repo, login, cnxprops=cnxprops, **kwargs)
 
 def in_memory_repo_cnx(config, login, **kwargs):
-    """usefull method for testing and scripting to get a dbapi.Connection
+    """useful method for testing and scripting to get a dbapi.Connection
     object connected to an in-memory repository instance
     """
     # connection to the CubicWeb repository
     repo = in_memory_repo(config)
     return repo, in_memory_cnx(repo, login, **kwargs)
 
+
+def anonymous_session(vreg):
+    """return a new anonymous session
+
+    raises an AuthenticationError if anonymous usage is not allowed
+    """
+    anoninfo = vreg.config.anonymous_user()
+    if anoninfo is None: # no anonymous user
+        raise AuthenticationError('anonymous access is not authorized')
+    anon_login, anon_password = anoninfo
+    cnxprops = ConnectionProperties(vreg.config.repo_method)
+    # use vreg's repository cache
+    repo = vreg.config.repository(vreg)
+    anon_cnx = repo_connect(repo, anon_login,
+                            cnxprops=cnxprops, password=anon_password)
+    anon_cnx.vreg = vreg
+    return DBAPISession(anon_cnx, anon_login)
+
+
 class _NeedAuthAccessMock(object):
     def __getattribute__(self, attr):
         raise AuthenticationError()
--- a/debian/control	Fri Oct 14 09:04:39 2011 +0200
+++ b/debian/control	Fri Oct 14 09:21:45 2011 +0200
@@ -35,7 +35,7 @@
 Conflicts: cubicweb-multisources
 Replaces: cubicweb-multisources
 Provides: cubicweb-multisources
-Depends: ${misc:Depends}, ${python:Depends}, cubicweb-common (= ${source:Version}), cubicweb-ctl (= ${source:Version}), python-logilab-database (>= 1.5.0), cubicweb-postgresql-support | cubicweb-mysql-support | python-pysqlite2, python-logilab-common (>= 0.56.2)
+Depends: ${misc:Depends}, ${python:Depends}, cubicweb-common (= ${source:Version}), cubicweb-ctl (= ${source:Version}), python-logilab-database (>= 1.5.0), cubicweb-postgresql-support | cubicweb-mysql-support | python-pysqlite2
 Recommends: pyro (<< 4.0.0), cubicweb-documentation (= ${source:Version})
 Description: server part of the CubicWeb framework
  CubicWeb is a semantic web application framework.
@@ -70,7 +70,7 @@
 Architecture: all
 XB-Python-Version: ${python:Versions}
 Provides: cubicweb-web-frontend
-Depends: ${misc:Depends}, ${python:Depends}, cubicweb-web (= ${source:Version}), cubicweb-ctl (= ${source:Version}), python-twisted-web, python-logilab-common (>= 0.56.2)
+Depends: ${misc:Depends}, ${python:Depends}, cubicweb-web (= ${source:Version}), cubicweb-ctl (= ${source:Version}), python-twisted-web
 Recommends: pyro (<< 4.0.0), cubicweb-documentation (= ${source:Version})
 Description: twisted-based web interface for the CubicWeb framework
  CubicWeb is a semantic web application framework.
@@ -99,7 +99,7 @@
 Package: cubicweb-common
 Architecture: all
 XB-Python-Version: ${python:Versions}
-Depends: ${misc:Depends}, ${python:Depends}, graphviz, gettext, python-logilab-mtconverter (>= 0.8.0), python-logilab-common (>= 0.55.2), python-yams (>= 0.33.0), python-rql (>= 0.28.0), python-lxml
+Depends: ${misc:Depends}, ${python:Depends}, graphviz, gettext, python-logilab-mtconverter (>= 0.8.0), python-logilab-common (>= 0.56.3), python-yams (>= 0.34.0), python-rql (>= 0.28.0), python-lxml
 Recommends: python-simpletal (>= 4.0), python-crypto
 Conflicts: cubicweb-core
 Replaces: cubicweb-core
--- a/devtools/__init__.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/devtools/__init__.py	Fri Oct 14 09:21:45 2011 +0200
@@ -581,7 +581,7 @@
         except BaseException:
             if self.dbcnx is not None:
                 self.dbcnx.rollback()
-            print >> sys.stderr, 'building', self.dbname, 'failed'
+            sys.stderr.write('building %s failed\n' % self.dbname)
             #self._drop(self.dbname)
             raise
 
--- a/devtools/test/unittest_dbfill.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/devtools/test/unittest_dbfill.py	Fri Oct 14 09:21:45 2011 +0200
@@ -72,7 +72,7 @@
         """test value generation from a given domain value"""
         firstname = self.person_valgen.generate_attribute_value({}, 'firstname', 12)
         possible_choices = self._choice_func('Person', 'firstname')
-        self.failUnless(firstname in possible_choices,
+        self.assertTrue(firstname in possible_choices,
                         '%s not in %s' % (firstname, possible_choices))
 
     def test_choice(self):
@@ -80,21 +80,21 @@
         # Test for random index
         for index in range(5):
             sx_value = self.person_valgen.generate_attribute_value({}, 'civility', index)
-            self.failUnless(sx_value in ('Mr', 'Mrs', 'Ms'))
+            self.assertTrue(sx_value in ('Mr', 'Mrs', 'Ms'))
 
     def test_integer(self):
         """test integer generation"""
         # Test for random index
         for index in range(5):
             cost_value = self.bug_valgen.generate_attribute_value({}, 'cost', index)
-            self.failUnless(cost_value in range(index+1))
+            self.assertTrue(cost_value in range(index+1))
 
     def test_date(self):
         """test date generation"""
         # Test for random index
         for index in range(10):
             date_value = self.person_valgen.generate_attribute_value({}, 'birthday', index)
-            self.failUnless(isinstance(date_value, datetime.date))
+            self.assertTrue(isinstance(date_value, datetime.date))
 
     def test_phone(self):
         """tests make_tel utility"""
--- a/devtools/test/unittest_fill.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/devtools/test/unittest_fill.py	Fri Oct 14 09:21:45 2011 +0200
@@ -41,31 +41,31 @@
 
 
     def test_autoextend(self):
-        self.failIf('generate_server' in dir(ValueGenerator))
+        self.assertFalse('generate_server' in dir(ValueGenerator))
         class MyValueGenerator(ValueGenerator):
             def generate_server(self, index):
                 return attrname
-        self.failUnless('generate_server' in dir(ValueGenerator))
+        self.assertTrue('generate_server' in dir(ValueGenerator))
 
 
     def test_bad_signature_detection(self):
-        self.failIf('generate_server' in dir(ValueGenerator))
+        self.assertFalse('generate_server' in dir(ValueGenerator))
         try:
             class MyValueGenerator(ValueGenerator):
                 def generate_server(self):
                     pass
         except TypeError:
-            self.failIf('generate_server' in dir(ValueGenerator))
+            self.assertFalse('generate_server' in dir(ValueGenerator))
         else:
             self.fail('TypeError not raised')
 
 
     def test_signature_extension(self):
-        self.failIf('generate_server' in dir(ValueGenerator))
+        self.assertFalse('generate_server' in dir(ValueGenerator))
         class MyValueGenerator(ValueGenerator):
             def generate_server(self, index, foo):
                 pass
-        self.failUnless('generate_server' in dir(ValueGenerator))
+        self.assertTrue('generate_server' in dir(ValueGenerator))
 
 
 if __name__ == '__main__':
--- a/devtools/testlib.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/devtools/testlib.py	Fri Oct 14 09:21:45 2011 +0200
@@ -387,31 +387,6 @@
                 req.cnx.commit()
         return user
 
-    @iclassmethod # XXX turn into a class method
-    def grant_permission(self, session, entity, group, pname=None, plabel=None):
-        """insert a permission on an entity. Will have to commit the main
-        connection to be considered
-        """
-        if not isinstance(session, Session):
-            warn('[3.12] grant_permission arguments are now (session, entity, group, pname[, plabel])',
-                 DeprecationWarning, stacklevel=2)
-            plabel = pname
-            pname = group
-            group = entity
-            entity = session
-            assert not isinstance(self, type)
-            session = self.session
-        pname = unicode(pname)
-        plabel = plabel and unicode(plabel) or unicode(group)
-        e = getattr(entity, 'eid', entity)
-        with security_enabled(session, False, False):
-            peid = session.execute(
-            'INSERT CWPermission X: X name %(pname)s, X label %(plabel)s,'
-            'X require_group G, E require_permission X '
-            'WHERE G name %(group)s, E eid %(e)s',
-            locals())[0][0]
-        return peid
-
     def login(self, login, **kwargs):
         """return a connection for the given login/password"""
         if login == self.admlogin:
@@ -851,7 +826,7 @@
         output = output.strip()
         validator = self.get_validator(view, output=output)
         if validator is None:
-            return
+            return output # return raw output if no validator is defined
         if isinstance(validator, htmlparser.DTDValidator):
             # XXX remove <canvas> used in progress widget, unknown in html dtd
             output = re.sub('<canvas.*?></canvas>', '', output)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/doc/3.14.rst	Fri Oct 14 09:21:45 2011 +0200
@@ -0,0 +1,101 @@
+Whats new in CubicWeb 3.14
+==========================
+
+API changes
+-----------
+
+* `Entity.fetch_rql` `restriction` argument has been deprecated and should be
+  replaced with a call to the new `Entity.fetch_rqlst` method, get the returned
+  value (a rql `Select` node) and use the RQL syntax tree API to include the
+  above-mentionned restrictions.
+
+  Backward compat is kept with proper warning.
+
+* `Entity.fetch_order` and `Entity.fetch_unrelated_order` class methods have been
+  replaced by `Entity.cw_fetch_order` and `Entity.cw_fetch_unrelated_order` with
+  a different prototype:
+
+  - instead of taking (attr, var) as two string argument, they now take (select,
+    attr, var) where select is the rql syntax tree beinx constructed and var the
+    variable *node*.
+
+  - instead of returning some string to be inserted in the ORDERBY clause, it has
+    to modify the syntax tree
+
+  Backward compat is kept with proper warning, BESIDE cases below:
+
+  - custom order method return **something else the a variable name with or
+    without the sorting order** (e.g. cases where you sort on the value of a
+    registered procedure as it was done in the tracker for instance). In such
+    case, an error is logged telling that this sorting is ignored until API
+    upgrade.
+
+  - client code use direct access to one of those methods on an entity (no code
+    known to do that)
+
+* `Entity._rest_attr_info` class method has been renamed to
+  `Entity.cw_rest_attr_info`
+
+  No backward compat yet since this is a protected method an no code is known to
+  use it outside cubicweb itself.
+
+* `AnyEntity.linked_to` has been removed as part of a refactoring of this
+  functionality (link a entity to another one at creation step). It was replaced
+  by a `EntityFieldsForm.linked_to` property.
+
+  In the same refactoring, `cubicweb.web.formfield.relvoc_linkedto`,
+  `cubicweb.web.formfield.relvoc_init` and
+  `cubicweb.web.formfield.relvoc_unrelated` were removed and replaced by
+  RelationField methods with the same names, that take a form as a parameter.
+
+  **No backward compatibility yet**. It's still time to cry for it.
+  Cubes known to be affected: tracker, vcsfile, vcreview
+
+* `CWPermission` entity type and its associated require_permission relation type
+  (abstract) and require_group relation definitions have been moved to a new
+  `localperms` cube. With this have gone some functions from the
+  `cubicweb.schemas` package as well as some views. This makes cubicweb itself
+  smaller while you get all the local permissions stuff into a single,
+  documented, place.
+
+  Backward compat is kept for existing instances, **though you should have
+  installed the localperms cubes**. A proper error should be displayed when
+  trying to migrate to 3.14 an instance the use `CWPermission` without the new
+  cube installed. For new instances / test, you should add a dependancy on the
+  new cube in cubes using this feature, along with a dependancy on cubicweb >=
+  3.14.
+
+* jQuery has been updated to 1.6.4. No backward compat issue known (yet...)
+
+
+Unintrusive API changes
+-----------------------
+
+* refactored properties forms (eg user preferences and site wide properties) to
+  ease overridding
+
+* table view allows to set None in 'headers', meaning the label should be fetched
+  from the result set as done by default
+
+* new `anonymized_request` decorator to temporary run stuff as an anonymous
+  user, whatever the currently logged in user
+
+* new 'verbatimattr' attribute view
+
+
+User interface changes
+----------------------
+
+* breadcrumb is properly kept when creating an entity with __linkto
+
+* users and groups management now really lead to that (i.e. includes *groups*
+  management)
+
+* new 'jsonp' controller with 'jsonexport' and 'ejsonexport' views
+
+
+Configuration
+------------
+
+* add option 'resources-concat' to make javascript/css files concatenation
+  optional
--- a/doc/book/en/devrepo/datamodel/baseschema.rst	Fri Oct 14 09:04:39 2011 +0200
+++ b/doc/book/en/devrepo/datamodel/baseschema.rst	Fri Oct 14 09:21:45 2011 +0200
@@ -19,7 +19,6 @@
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 * _`CWUser`, system users
 * _`CWGroup`, users groups
-* _`CWPermission`, used to configure the security of the instance
 
 Entity types used to manage workflows
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--- a/doc/book/en/devrepo/datamodel/definition.rst	Fri Oct 14 09:04:39 2011 +0200
+++ b/doc/book/en/devrepo/datamodel/definition.rst	Fri Oct 14 09:21:45 2011 +0200
@@ -646,68 +646,7 @@
   RelationType declaration which offers some advantages in the context
   of reusable cubes.
 
-Definition of permissions
-~~~~~~~~~~~~~~~~~~~~~~~~~~
-The entity type `CWPermission` from the standard library
-allows to build very complex and dynamic security architectures. The schema of
-this entity type is as follow:
-
-.. sourcecode:: python
-
-    class CWPermission(EntityType):
-        """entity type that may be used to construct some advanced security configuration
-        """
-        name = String(required=True, indexed=True, internationalizable=True, maxsize=100)
-        require_group = SubjectRelation('CWGroup', cardinality='+*',
-                                        description=_('groups to which the permission is granted'))
-        require_state = SubjectRelation('State',
-                                        description=_("entity's state in which the permission is applicable"))
-        # can be used on any entity
-        require_permission = ObjectRelation('**', cardinality='*1', composite='subject',
-                                            description=_("link a permission to the entity. This "
-                                                          "permission should be used in the security "
-                                                          "definition of the entity's type to be useful."))
-
-
-Example of configuration:
-
-.. sourcecode:: python
-
-    class Version(EntityType):
-        """a version is defining the content of a particular project's release"""
-
-        __permissions__ = {'read':   ('managers', 'users', 'guests',),
-                           'update': ('managers', 'logilab', 'owners',),
-                           'delete': ('managers', ),
-                           'add':    ('managers', 'logilab',
-                                       ERQLExpression('X version_of PROJ, U in_group G,'
-                                                 'PROJ require_permission P, P name "add_version",'
-                                                 'P require_group G'),)}
-
-
-    class version_of(RelationType):
-        """link a version to its project. A version is necessarily linked to one and only one project.
-        """
-        __permissions__ = {'read':   ('managers', 'users', 'guests',),
-                           'delete': ('managers', ),
-                           'add':    ('managers', 'logilab',
-                                  RRQLExpression('O require_permission P, P name "add_version",'
-                                                 'U in_group G, P require_group G'),)
-                       }
-        inlined = True
-
-
-This configuration indicates that an entity `CWPermission` named
-"add_version" can be associated to a project and provides rights to create
-new versions on this project to specific groups. It is important to notice that:
-
-* in such case, we have to protect both the entity type "Version" and the relation
-  associating a version to a project ("version_of")
-
-* because of the genericity of the entity type `CWPermission`, we have to execute
-  a unification with the groups and/or the states if necessary in the expression
-  ("U in_group G, P require_group G" in the above example)
-
+  
 
 
 Handling schema changes
--- a/doc/book/en/devrepo/entityclasses/application-logic.rst	Fri Oct 14 09:04:39 2011 +0200
+++ b/doc/book/en/devrepo/entityclasses/application-logic.rst	Fri Oct 14 09:21:45 2011 +0200
@@ -67,8 +67,8 @@
 
     class Project(AnyEntity):
         __regid__ = 'Project'
-        fetch_attrs, fetch_order = fetch_config(('name', 'description',
-                                                 'description_format', 'summary'))
+        fetch_attrs, cw_fetch_order = fetch_config(('name', 'description',
+                                                    'description_format', 'summary'))
 
         TICKET_DEFAULT_STATE_RESTR = 'S name IN ("created","identified","released","scheduled")'
 
@@ -95,11 +95,9 @@
 about the transitive closure of the child relation). This is a further
 argument to implement it at entity class level.
 
-The fetch_attrs, fetch_order class attributes are parameters of the
-`ORM`_ layer. They tell which attributes should be loaded at once on
-entity object instantiation (by default, only the eid is known, other
-attributes are loaded on demand), and which attribute is to be used to
-order the .related() and .unrelated() methods output.
+`fetch_attrs` configures which attributes should be prefetched when using ORM
+methods retrieving entity of this type. In a same manner, the `cw_fetch_order` is
+a class method allowing to control sort order. More on this in :ref:FetchAttrs.
 
 We can observe the big TICKET_DEFAULT_STATE_RESTR is a pure
 application domain piece of data. There is, of course, no limitation
--- a/doc/book/en/devrepo/entityclasses/load-sort.rst	Fri Oct 14 09:04:39 2011 +0200
+++ b/doc/book/en/devrepo/entityclasses/load-sort.rst	Fri Oct 14 09:21:45 2011 +0200
@@ -4,50 +4,36 @@
 Loaded attributes and default sorting management
 ````````````````````````````````````````````````
 
-* The class attribute `fetch_attrs` allows to define in an entity class a list
-  of names of attributes or relations that should be automatically loaded when
-  entities of this type are fetched from the database. In the case of relations,
-  we are limited to *subject of cardinality `?` or `1`* relations.
+* The class attribute `fetch_attrs` allows to define in an entity class a list of
+  names of attributes that should be automatically loaded when entities of this
+  type are fetched from the database using ORM methods retrieving entity of this
+  type (such as :meth:`related` and :meth:`unrelated`). You can also put relation
+  names in there, but we are limited to *subject relations of cardinality `?` or
+  `1`*.
 
-* The class method `fetch_order(attr, var)` expects an attribute (or relation)
-  name as a parameter and a variable name, and it should return a string
-  to use in the requirement `ORDERBY` of an RQL query to automatically
-  sort the list of entities of such type according to this attribute, or
-  `None` if we do not want to sort on the attribute given in the parameter.
-  By default, the entities are sorted according to their creation date.
+* The :meth:`cw_fetch_order` and :meth:`cw_fetch_unrelated_order` class methods
+  are respectively responsible to control how entities will be sorted when:
 
-* The class method `fetch_unrelated_order(attr, var)` is similar to
-  the method `fetch_order` except that it is essentially used to
-  control the sorting of drop-down lists enabling relations creation
-  in the editing view of an entity. The default implementation uses
-  the modification date. Here's how to adapt it for one entity (sort
-  on the name attribute): ::
+  - retrieving all entities of a given type, or entities related to another
 
-   class MyEntity(AnyEntity):
-       __regid__ = 'MyEntity'
-       fetch_attrs = ('modification_date', 'name')
+  - retrieving a list of entities for use in drop-down lists enabling relations
+    creation in the editing view of an entity
 
-       @classmethod
-       def fetch_unrelated_order(cls, attr, var):
-           if attr == 'name':
-              return '%s ASC' % var
-           return None
+By default entities will be listed on their modification date descending,
+i.e. you'll get entities recently modified first. While this is usually a good
+default in drop-down list, you'll probably want to change `cw_fetch_order`.
 
+This may easily be done using the :func:`~cubicweb.entities.fetch_config`
+function, which simplifies the definition of attributes to load and sorting by
+returning a list of attributes to pre-load (considering automatically the
+attributes of `AnyEntity`) and a sorting function as described below:
 
-The function `fetch_config(fetchattrs, mainattr=None)` simplifies the
-definition of the attributes to load and the sorting by returning a
-list of attributes to pre-load (considering automatically the
-attributes of `AnyEntity`) and a sorting function based on the main
-attribute (the second parameter if specified, otherwise the first
-attribute from the list `fetchattrs`). This function is defined in
-`cubicweb.entities`.
+.. autofunction:: cubicweb.entities.fetch_config
+
+In you want something else (such as sorting on the result of a registered
+procedure), here is the prototype of those methods:
 
-For example: ::
+.. autofunction:: cubicweb.entity.Entity.cw_fetch_order
 
-  class Transition(AnyEntity):
-    """..."""
-    __regid__ = 'Transition'
-    fetch_attrs, fetch_order = fetch_config(['name'])
+.. autofunction:: cubicweb.entity.Entity.cw_fetch_unrelated_order
 
-Indicates that for the entity type "Transition", you have to pre-load
-the attribute `name` and sort by default on this attribute.
--- a/doc/book/en/devweb/controllers.rst	Fri Oct 14 09:04:39 2011 +0200
+++ b/doc/book/en/devweb/controllers.rst	Fri Oct 14 09:21:45 2011 +0200
@@ -26,9 +26,23 @@
   typically using JSON as a serialization format for input, and
   sometimes using either JSON or XML for output;
 
+* the JSonpController is a wrapper around the ``ViewController`` that
+  provides jsonp_ services. Padding can be specified with the
+  ``callback`` request parameter. Only *jsonexport* / *ejsonexport*
+  views can be used. If another ``vid`` is specified, it will be
+  ignored and replaced by *jsonexport*. Request is anonymized
+  to avoid returning sensitive data and reduce the risks of CSRF attacks;
+
 * the Login/Logout controllers make effective user login or logout
   requests
 
+.. warning::
+
+  JsonController will probably be renamed into AjaxController soon since
+  it has nothing to do with json per se.
+
+.. _jsonp: http://en.wikipedia.org/wiki/JSONP
+
 `Edition`:
 
 * the Edit controller (see :ref:`edit_controller`) handles CRUD
--- a/doc/book/en/devweb/edition/form.rst	Fri Oct 14 09:04:39 2011 +0200
+++ b/doc/book/en/devweb/edition/form.rst	Fri Oct 14 09:21:45 2011 +0200
@@ -87,15 +87,15 @@
     def ticket_done_in_choices(form, field):
         entity = form.edited_entity
         # first see if its specified by __linkto form parameters
-        linkedto = formfields.relvoc_linkedto(entity, 'done_in', 'subject')
+        linkedto = form.linked_to[('done_in', 'subject')]
         if linkedto:
             return linkedto
         # it isn't, get initial values
-        vocab = formfields.relvoc_init(entity, 'done_in', 'subject')
+        vocab = field.relvoc_init(form)
         veid = None
         # try to fetch the (already or pending) related version and project
         if not entity.has_eid():
-            peids = entity.linked_to('concerns', 'subject')
+            peids = form.linked_to[('concerns', 'subject')]
             peid = peids and peids[0]
         else:
             peid = entity.project.eid
@@ -112,29 +112,28 @@
                       and v.eid != veid]
         return vocab
 
-The first thing we have to do is fetch potential values from the
-``__linkto`` url parameter that is often found in entity creation
-contexts (the creation action provides such a parameter with a
-predetermined value; for instance in this case, ticket creation could
-occur in the context of a `Version` entity). The
-:mod:`cubicweb.web.formfields` module provides a ``relvoc_linkedto``
-utility function that gets a list suitably filled with vocabulary
-values.
+The first thing we have to do is fetch potential values from the ``__linkto`` url
+parameter that is often found in entity creation contexts (the creation action
+provides such a parameter with a predetermined value; for instance in this case,
+ticket creation could occur in the context of a `Version` entity). The
+:class:`~cubicweb.web.formfields.RelationField` field class provides a
+:meth:`~cubicweb.web.formfields.RelationField.relvoc_linkedto` method that gets a
+list suitably filled with vocabulary values.
 
 .. sourcecode:: python
 
-        linkedto = formfields.relvoc_linkedto(entity, 'done_in', 'subject')
+        linkedto = field.relvoc_linkedto(form)
         if linkedto:
             return linkedto
 
-Then, if no ``__linkto`` argument was given, we must prepare the
-vocabulary with an initial empty value (because `done_in` is not
-mandatory, we must allow the user to not select a verson) and already
-linked values. This is done with the ``relvoc_init`` function.
+Then, if no ``__linkto`` argument was given, we must prepare the vocabulary with
+an initial empty value (because `done_in` is not mandatory, we must allow the
+user to not select a verson) and already linked values. This is done with the
+:meth:`~cubicweb.web.formfields.RelationField.relvoc_init` method.
 
 .. sourcecode:: python
 
-        vocab = formfields.relvoc_init(entity, 'done_in', 'subject')
+        vocab = field.relvoc_init(form)
 
 But then, we have to give more: if the ticket is related to a project,
 we should provide all the non published versions of this project
@@ -169,7 +168,7 @@
 
         veid = None
         if not entity.has_eid():
-            peids = entity.linked_to('concerns', 'subject')
+            peids = form.linked_to[('concerns', 'subject')]
             peid = peids and peids[0]
         else:
             peid = entity.project.eid
--- a/doc/book/en/tutorials/advanced/part04_ui-base.rst	Fri Oct 14 09:04:39 2011 +0200
+++ b/doc/book/en/tutorials/advanced/part04_ui-base.rst	Fri Oct 14 09:21:45 2011 +0200
@@ -138,20 +138,21 @@
 * Also, when viewing an image, there is no clue about the folder to which this
   image belongs to.
 
-I will first try to explain the ordering problem. By default, when accessing related
-entities by using the ORM's API, you should get them ordered according to the target's
-class `fetch_order`. If we take a look at the file cube'schema, we can see:
+I will first try to explain the ordering problem. By default, when accessing
+related entities by using the ORM's API, you should get them ordered according to
+the target's class `cw_fetch_order`. If we take a look at the file cube'schema,
+we can see:
 
 .. sourcecode:: python
 
-
     class File(AnyEntity):
 	"""customized class for File entities"""
 	__regid__ = 'File'
-	fetch_attrs, fetch_order = fetch_config(['data_name', 'title'])
+	fetch_attrs, cw_fetch_order = fetch_config(['data_name', 'title'])
+
 
-By default, `fetch_config` will return a `fetch_order` method that will order on
-the first attribute in the list. So, we could expect to get files ordered by
+By default, `fetch_config` will return a `cw_fetch_order` method that will order
+on the first attribute in the list. So, we could expect to get files ordered by
 their name. But we don't.  What's up doc ?
 
 The problem is that files are related to folder using the `filed_under` relation.
--- a/doc/book/en/tutorials/base/customizing-the-application.rst	Fri Oct 14 09:04:39 2011 +0200
+++ b/doc/book/en/tutorials/base/customizing-the-application.rst	Fri Oct 14 09:21:45 2011 +0200
@@ -389,7 +389,7 @@
         """customized class for Community entities"""
         __regid__ = 'Community'
 
-        fetch_attrs, fetch_order = fetch_config(['name'])
+        fetch_attrs, cw_fetch_order = fetch_config(['name'])
 
         def dc_title(self):
             return self.name
--- a/entities/__init__.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/entities/__init__.py	Fri Oct 14 09:21:45 2011 +0200
@@ -118,54 +118,35 @@
             return self.printable_value(rtype, format='text/plain').lower()
         return value
 
-    # edition helper functions ################################################
-
-    def linked_to(self, rtype, role, remove=True):
-        """if entity should be linked to another using '__linkto' form param for
-        the given relation/role, return eids of related entities
-
-        This method is consuming matching link-to information from form params
-        if `remove` is True (by default). Computed values are stored into a
-        `cw_linkto` attribute, a dictionary with (relation, role) as key and
-        linked eids as value.
-        """
-        try:
-            return self.cw_linkto[(rtype, role)]
-        except AttributeError:
-            self.cw_linkto = {}
-        except KeyError:
-            pass
-        linktos = list(self._cw.list_form_param('__linkto'))
-        linkedto = []
-        for linkto in linktos[:]:
-            ltrtype, eid, ltrole = linkto.split(':')
-            if rtype == ltrtype and role == ltrole:
-                # delete __linkto from form param to avoid it being added as
-                # hidden input
-                if remove:
-                    linktos.remove(linkto)
-                    self._cw.form['__linkto'] = linktos
-                linkedto.append(typed_eid(eid))
-        self.cw_linkto[(rtype, role)] = linkedto
-        return linkedto
-
-    # server side helpers #####################################################
-
-# XXX:  store a reference to the AnyEntity class since it is hijacked in goa
-#       configuration and we need the actual reference to avoid infinite loops
-#       in mro
-ANYENTITY = AnyEntity
 
 def fetch_config(fetchattrs, mainattr=None, pclass=AnyEntity, order='ASC'):
-    if pclass is ANYENTITY:
-        pclass = AnyEntity # AnyEntity and ANYENTITY may be different classes
+    """function to ease basic configuration of an entity class ORM. Basic usage
+    is:
+
+    .. sourcecode:: python
+
+      class MyEntity(AnyEntity):
+
+          fetch_attrs, cw_fetch_order = fetch_config(['attr1', 'attr2'])
+          # uncomment line below if you want the same sorting for 'unrelated' entities
+          # cw_fetch_unrelated_order = cw_fetch_order
+
+    Using this, when using ORM methods retrieving this type of entity, 'attr1'
+    and 'attr2' will be automatically prefetched and results will be sorted on
+    'attr1' ascending (ie the first attribute in the list).
+
+    This function will automatically add to fetched attributes those defined in
+    parent class given using the `pclass` argument.
+
+    Also, You can use `mainattr` and `order` argument to have a different
+    sorting.
+    """
     if pclass is not None:
         fetchattrs += pclass.fetch_attrs
     if mainattr is None:
         mainattr = fetchattrs[0]
     @classmethod
-    def fetch_order(cls, attr, var):
+    def fetch_order(cls, select, attr, var):
         if attr == mainattr:
-            return '%s %s' % (var, order)
-        return None
+            select.add_sort_var(var, order=='ASC')
     return fetchattrs, fetch_order
--- a/entities/authobjs.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/entities/authobjs.py	Fri Oct 14 09:21:45 2011 +0200
@@ -26,30 +26,14 @@
 
 class CWGroup(AnyEntity):
     __regid__ = 'CWGroup'
-    fetch_attrs, fetch_order = fetch_config(['name'])
-    fetch_unrelated_order = fetch_order
-
-    def grant_permission(self, entity, pname, plabel=None):
-        """grant local `pname` permission on `entity` to this group using
-        :class:`CWPermission`.
-
-        If a similar permission already exists, add the group to it, else create
-        a new one.
-        """
-        if not self._cw.execute(
-            'SET X require_group G WHERE E eid %(e)s, G eid %(g)s, '
-            'E require_permission X, X name %(name)s, X label %(label)s',
-            {'e': entity.eid, 'g': self.eid,
-             'name': pname, 'label': plabel}):
-            self._cw.create_entity('CWPermission', name=pname, label=plabel,
-                                   require_group=self,
-                                   reverse_require_permission=entity)
+    fetch_attrs, cw_fetch_order = fetch_config(['name'])
+    cw_fetch_unrelated_order = cw_fetch_order
 
 
 class CWUser(AnyEntity):
     __regid__ = 'CWUser'
-    fetch_attrs, fetch_order = fetch_config(['login', 'firstname', 'surname'])
-    fetch_unrelated_order = fetch_order
+    fetch_attrs, cw_fetch_order = fetch_config(['login', 'firstname', 'surname'])
+    cw_fetch_unrelated_order = cw_fetch_order
 
     # used by repository to check if  the user can log in or not
     AUTHENTICABLE_STATES = ('activated',)
@@ -139,18 +123,6 @@
             return False
     owns = cached(owns, keyarg=1)
 
-    def has_permission(self, pname, contexteid=None):
-        rql = 'Any P WHERE P is CWPermission, U eid %(u)s, U in_group G, '\
-              'P name %(pname)s, P require_group G'
-        kwargs = {'pname': pname, 'u': self.eid}
-        if contexteid is not None:
-            rql += ', X require_permission P, X eid %(x)s'
-            kwargs['x'] = contexteid
-        try:
-            return self._cw.execute(rql, kwargs)
-        except Unauthorized:
-            return False
-
     # presentation utilities ##################################################
 
     def name(self):
--- a/entities/lib.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/entities/lib.py	Fri Oct 14 09:21:45 2011 +0200
@@ -39,7 +39,7 @@
 
 class EmailAddress(AnyEntity):
     __regid__ = 'EmailAddress'
-    fetch_attrs, fetch_order = fetch_config(['address', 'alias'])
+    fetch_attrs, cw_fetch_order = fetch_config(['address', 'alias'])
     rest_attr = 'eid'
 
     def dc_title(self):
@@ -94,7 +94,7 @@
 class Bookmark(AnyEntity):
     """customized class for Bookmark entities"""
     __regid__ = 'Bookmark'
-    fetch_attrs, fetch_order = fetch_config(['title', 'path'])
+    fetch_attrs, cw_fetch_order = fetch_config(['title', 'path'])
 
     def actual_url(self):
         url = self._cw.build_url(self.path)
@@ -114,7 +114,7 @@
 class CWProperty(AnyEntity):
     __regid__ = 'CWProperty'
 
-    fetch_attrs, fetch_order = fetch_config(['pkey', 'value'])
+    fetch_attrs, cw_fetch_order = fetch_config(['pkey', 'value'])
     rest_attr = 'pkey'
 
     def typed_value(self):
@@ -130,7 +130,7 @@
 class CWCache(AnyEntity):
     """Cache"""
     __regid__ = 'CWCache'
-    fetch_attrs, fetch_order = fetch_config(['name'])
+    fetch_attrs, cw_fetch_order = fetch_config(['name'])
 
     def touch(self):
         self._cw.execute('SET X timestamp %(t)s WHERE X eid %(x)s',
--- a/entities/schemaobjs.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/entities/schemaobjs.py	Fri Oct 14 09:21:45 2011 +0200
@@ -31,7 +31,7 @@
 
 class CWEType(AnyEntity):
     __regid__ = 'CWEType'
-    fetch_attrs, fetch_order = fetch_config(['name'])
+    fetch_attrs, cw_fetch_order = fetch_config(['name'])
 
     def dc_title(self):
         return u'%s (%s)' % (self.name, self._cw._(self.name))
@@ -48,7 +48,7 @@
 
 class CWRType(AnyEntity):
     __regid__ = 'CWRType'
-    fetch_attrs, fetch_order = fetch_config(['name'])
+    fetch_attrs, cw_fetch_order = fetch_config(['name'])
 
     def dc_title(self):
         return u'%s (%s)' % (self.name, self._cw._(self.name))
@@ -139,7 +139,7 @@
 
 class CWConstraint(AnyEntity):
     __regid__ = 'CWConstraint'
-    fetch_attrs, fetch_order = fetch_config(['value'])
+    fetch_attrs, cw_fetch_order = fetch_config(['value'])
 
     def dc_title(self):
         return '%s(%s)' % (self.cstrtype[0].name, self.value or u'')
@@ -151,7 +151,7 @@
 
 class RQLExpression(AnyEntity):
     __regid__ = 'RQLExpression'
-    fetch_attrs, fetch_order = fetch_config(['exprtype', 'mainvars', 'expression'])
+    fetch_attrs, cw_fetch_order = fetch_config(['exprtype', 'mainvars', 'expression'])
 
     def dc_title(self):
         return self.expression or u''
@@ -176,13 +176,3 @@
 
     def check_expression(self, *args, **kwargs):
         return self._rqlexpr().check(*args, **kwargs)
-
-
-class CWPermission(AnyEntity):
-    __regid__ = 'CWPermission'
-    fetch_attrs, fetch_order = fetch_config(['name', 'label'])
-
-    def dc_title(self):
-        if self.label:
-            return '%s (%s)' % (self._cw._(self.name), self.label)
-        return self._cw._(self.name)
--- a/entities/sources.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/entities/sources.py	Fri Oct 14 09:21:45 2011 +0200
@@ -54,7 +54,7 @@
 
 class CWSource(_CWSourceCfgMixIn, AnyEntity):
     __regid__ = 'CWSource'
-    fetch_attrs, fetch_order = fetch_config(['name', 'type'])
+    fetch_attrs, cw_fetch_order = fetch_config(['name', 'type'])
 
     @property
     def host_config(self):
@@ -107,7 +107,7 @@
 
 class CWSourceHostConfig(_CWSourceCfgMixIn, AnyEntity):
     __regid__ = 'CWSourceHostConfig'
-    fetch_attrs, fetch_order = fetch_config(['match_host', 'config'])
+    fetch_attrs, cw_fetch_order = fetch_config(['match_host', 'config'])
 
     @property
     def cwsource(self):
@@ -119,7 +119,7 @@
 
 class CWSourceSchemaConfig(AnyEntity):
     __regid__ = 'CWSourceSchemaConfig'
-    fetch_attrs, fetch_order = fetch_config(['cw_for_source', 'cw_schema', 'options'])
+    fetch_attrs, cw_fetch_order = fetch_config(['cw_for_source', 'cw_schema', 'options'])
 
     def dc_title(self):
         return self._cw._(self.__regid__) + ' #%s' % self.eid
--- a/entities/test/unittest_base.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/entities/test/unittest_base.py	Fri Oct 14 09:21:45 2011 +0200
@@ -88,10 +88,10 @@
 
     def test_matching_groups(self):
         e = self.execute('CWUser X WHERE X login "admin"').get_entity(0, 0)
-        self.failUnless(e.matching_groups('managers'))
-        self.failIf(e.matching_groups('xyz'))
-        self.failUnless(e.matching_groups(('xyz', 'managers')))
-        self.failIf(e.matching_groups(('xyz', 'abcd')))
+        self.assertTrue(e.matching_groups('managers'))
+        self.assertFalse(e.matching_groups('xyz'))
+        self.assertTrue(e.matching_groups(('xyz', 'managers')))
+        self.assertFalse(e.matching_groups(('xyz', 'abcd')))
 
     def test_dc_title_and_name(self):
         e = self.execute('CWUser U WHERE U login "member"').get_entity(0, 0)
@@ -131,12 +131,12 @@
         self.vreg['etypes'].initialization_completed()
         MyUser_ = self.vreg['etypes'].etype_class('CWUser')
         # a copy is done systematically
-        self.failUnless(issubclass(MyUser_, MyUser))
-        self.failUnless(implements(MyUser_, IMileStone))
-        self.failUnless(implements(MyUser_, ICalendarable))
+        self.assertTrue(issubclass(MyUser_, MyUser))
+        self.assertTrue(implements(MyUser_, IMileStone))
+        self.assertTrue(implements(MyUser_, ICalendarable))
         # original class should not have beed modified, only the copy
-        self.failUnless(implements(MyUser, IMileStone))
-        self.failIf(implements(MyUser, ICalendarable))
+        self.assertTrue(implements(MyUser, IMileStone))
+        self.assertFalse(implements(MyUser, ICalendarable))
 
 
 class SpecializedEntityClassesTC(CubicWebTC):
@@ -149,7 +149,7 @@
     def test_etype_class_selection_and_specialization(self):
         # no specific class for Subdivisions, the default one should be selected
         eclass = self.select_eclass('SubDivision')
-        self.failUnless(eclass.__autogenerated__)
+        self.assertTrue(eclass.__autogenerated__)
         #self.assertEqual(eclass.__bases__, (AnyEntity,))
         # build class from most generic to most specific and make
         # sure the most specific is always selected
@@ -159,8 +159,8 @@
                 __regid__ = etype
             self.vreg.register(Foo)
             eclass = self.select_eclass('SubDivision')
-            self.failUnless(eclass.__autogenerated__)
-            self.failIf(eclass is Foo)
+            self.assertTrue(eclass.__autogenerated__)
+            self.assertFalse(eclass is Foo)
             if etype == 'SubDivision':
                 self.assertEqual(eclass.__bases__, (Foo,))
             else:
--- a/entities/test/unittest_wfobjs.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/entities/test/unittest_wfobjs.py	Fri Oct 14 09:21:45 2011 +0200
@@ -567,7 +567,7 @@
         # test initial state is set
         rset = self.execute('Any N WHERE S name N, X in_state S, X eid %(x)s',
                             {'x' : ueid})
-        self.failIf(rset, rset.rows)
+        self.assertFalse(rset, rset.rows)
         self.commit()
         initialstate = self.execute('Any N WHERE S name N, X in_state S, X eid %(x)s',
                                     {'x' : ueid})[0][0]
--- a/entities/wfobjs.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/entities/wfobjs.py	Fri Oct 14 09:21:45 2011 +0200
@@ -183,7 +183,7 @@
     fired by the logged user
     """
     __regid__ = 'BaseTransition'
-    fetch_attrs, fetch_order = fetch_config(['name', 'type'])
+    fetch_attrs, cw_fetch_order = fetch_config(['name', 'type'])
 
     def __init__(self, *args, **kwargs):
         if self.__regid__ == 'BaseTransition':
@@ -347,7 +347,7 @@
 class State(AnyEntity):
     """customized class for State entities"""
     __regid__ = 'State'
-    fetch_attrs, fetch_order = fetch_config(['name'])
+    fetch_attrs, cw_fetch_order = fetch_config(['name'])
     rest_attr = 'eid'
 
     @property
@@ -360,8 +360,8 @@
     """customized class for Transition information entities
     """
     __regid__ = 'TrInfo'
-    fetch_attrs, fetch_order = fetch_config(['creation_date', 'comment'],
-                                            pclass=None) # don't want modification_date
+    fetch_attrs, cw_fetch_order = fetch_config(['creation_date', 'comment'],
+                                               pclass=None) # don't want modification_date
     @property
     def for_entity(self):
         return self.wf_info_for[0]
--- a/entity.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/entity.py	Fri Oct 14 09:21:45 2011 +0200
@@ -27,8 +27,12 @@
 from logilab.mtconverter import TransformData, TransformError, xml_escape
 
 from rql.utils import rqlvar_maker
+from rql.stmts import Select
+from rql.nodes import (Not, VariableRef, Constant, make_relation,
+                       Relation as RqlRelation)
 
 from cubicweb import Unauthorized, typed_eid, neg_role
+from cubicweb.utils import support_args
 from cubicweb.rset import ResultSet
 from cubicweb.selectors import yes
 from cubicweb.appobject import AppObject
@@ -36,7 +40,7 @@
 from cubicweb.schema import RQLVocabularyConstraint, RQLConstraint
 from cubicweb.rqlrewrite import RQLRewriter
 
-from cubicweb.uilib import printable_value, soup2xhtml
+from cubicweb.uilib import soup2xhtml
 from cubicweb.mixins import MI_REL_TRIGGERS
 from cubicweb.mttransforms import ENGINE
 
@@ -62,23 +66,6 @@
     return True
 
 
-def remove_ambiguous_rels(attr_set, subjtypes, schema):
-    '''remove from `attr_set` the relations of entity types `subjtypes` that have
-    different entity type sets as target'''
-    for attr in attr_set.copy():
-        rschema = schema.rschema(attr)
-        if rschema.final:
-            continue
-        ttypes = None
-        for subjtype in subjtypes:
-            cur_ttypes = rschema.objects(subjtype)
-            if ttypes is None:
-                ttypes = cur_ttypes
-            elif cur_ttypes != ttypes:
-                attr_set.remove(attr)
-                break
-
-
 class Entity(AppObject):
     """an entity instance has e_schema automagically set on
     the class and instances has access to their issuing cursor.
@@ -91,16 +78,16 @@
     :type e_schema: `cubicweb.schema.EntitySchema`
     :ivar e_schema: the entity's schema
 
-    :type rest_var: str
-    :cvar rest_var: indicates which attribute should be used to build REST urls
-                    If None is specified, the first non-meta attribute will
-                    be used
+    :type rest_attr: str
+    :cvar rest_attr: indicates which attribute should be used to build REST urls
+       If `None` is specified (the default), the first unique attribute will
+       be used ('eid' if none found)
 
-    :type skip_copy_for: list
-    :cvar skip_copy_for: a list of relations that should be skipped when copying
-                         this kind of entity. Note that some relations such
-                         as composite relations or relations that have '?1' as object
-                         cardinality are always skipped.
+    :type cw_skip_copy_for: list
+    :cvar cw_skip_copy_for: a list of couples (rtype, role) for each relation
+       that should be skipped when copying this kind of entity. Note that some
+       relations such as composite relations or relations that have '?1' as
+       object cardinality are always skipped.
     """
     __registry__ = 'etypes'
     __select__ = yes()
@@ -108,7 +95,8 @@
     # class attributes that must be set in class definition
     rest_attr = None
     fetch_attrs = None
-    skip_copy_for = ('in_state',) # XXX turn into a set
+    skip_copy_for = () # bw compat (< 3.14), use cw_skip_copy_for instead
+    cw_skip_copy_for = [('in_state', 'subject')]
     # class attributes set automatically at registration time
     e_schema = None
 
@@ -153,50 +141,131 @@
             cls.info('plugged %s mixins on %s', mixins, cls)
 
     fetch_attrs = ('modification_date',)
-    @classmethod
-    def fetch_order(cls, attr, var):
-        """class method used to control sort order when multiple entities of
-        this type are fetched
-        """
-        return cls.fetch_unrelated_order(attr, var)
 
     @classmethod
-    def fetch_unrelated_order(cls, attr, var):
-        """class method used to control sort order when multiple entities of
-        this type are fetched to use in edition (eg propose them to create a
+    def cw_fetch_order(cls, select, attr, var):
+        """This class method may be used to control sort order when multiple
+        entities of this type are fetched through ORM methods. Its arguments
+        are:
+
+        * `select`, the RQL syntax tree
+
+        * `attr`, the attribute being watched
+
+        * `var`, the variable through which this attribute's value may be
+          accessed in the query
+
+        When you want to do some sorting on the given attribute, you should
+        modify the syntax tree accordingly. For instance:
+
+        .. sourcecode:: python
+
+          from rql import nodes
+
+          class Version(AnyEntity):
+              __regid__ = 'Version'
+
+              fetch_attrs = ('num', 'description', 'in_state')
+
+              @classmethod
+              def cw_fetch_order(cls, select, attr, var):
+                  if attr == 'num':
+                      func = nodes.Function('version_sort_value')
+                      func.append(nodes.variable_ref(var))
+                      sterm = nodes.SortTerm(func, asc=False)
+                      select.add_sort_term(sterm)
+
+        The default implementation call
+        :meth:`~cubicweb.entity.Entity.cw_fetch_unrelated_order`
+        """
+        cls.cw_fetch_unrelated_order(select, attr, var)
+
+    @classmethod
+    def cw_fetch_unrelated_order(cls, select, attr, var):
+        """This class method may be used to control sort order when multiple entities of
+        this type are fetched to use in edition (e.g. propose them to create a
         new relation on an edited entity).
+
+        See :meth:`~cubicweb.entity.Entity.cw_fetch_unrelated_order` for a
+        description of its arguments and usage.
+
+        By default entities will be listed on their modification date descending,
+        i.e. you'll get entities recently modified first.
         """
         if attr == 'modification_date':
-            return '%s DESC' % var
-        return None
+            select.add_sort_var(var, asc=False)
 
     @classmethod
     def fetch_rql(cls, user, restriction=None, fetchattrs=None, mainvar='X',
                   settype=True, ordermethod='fetch_order'):
-        """return a rql to fetch all entities of the class type"""
-        # XXX update api and implementation to AST manipulation (see unrelated rql)
-        restrictions = restriction or []
-        if settype:
-            restrictions.append('%s is %s' % (mainvar, cls.__regid__))
-        if fetchattrs is None:
-            fetchattrs = cls.fetch_attrs
-        selection = [mainvar]
-        orderby = []
-        # start from 26 to avoid possible conflicts with X
-        # XXX not enough to be sure it'll be no conflicts
-        varmaker = rqlvar_maker(index=26)
-        cls._fetch_restrictions(mainvar, varmaker, fetchattrs, selection,
-                                orderby, restrictions, user, ordermethod)
-        rql = 'Any %s' % ','.join(selection)
-        if orderby:
-            rql +=  ' ORDERBY %s' % ','.join(orderby)
-        rql += ' WHERE %s' % ', '.join(restrictions)
+        st = cls.fetch_rqlst(user, mainvar=mainvar, fetchattrs=fetchattrs,
+                             settype=settype, ordermethod=ordermethod)
+        rql = st.as_string()
+        if restriction:
+            # cannot use RQLRewriter API to insert 'X rtype %(x)s' restriction
+            warn('[3.14] fetch_rql: use of `restriction` parameter is '
+                 'deprecated, please use fetch_rqlst and supply a syntax'
+                 'tree with your restriction instead', DeprecationWarning)
+            insert = ' WHERE ' + ','.join(restriction)
+            if ' WHERE ' in rql:
+                select, where = rql.split(' WHERE ', 1)
+                rql = select + insert + ',' + where
+            else:
+                rql += insert
         return rql
 
     @classmethod
-    def _fetch_restrictions(cls, mainvar, varmaker, fetchattrs,
-                            selection, orderby, restrictions, user,
-                            ordermethod='fetch_order', visited=None):
+    def fetch_rqlst(cls, user, select=None, mainvar='X', fetchattrs=None,
+                    settype=True, ordermethod='fetch_order'):
+        if select is None:
+            select = Select()
+            mainvar = select.get_variable(mainvar)
+            select.add_selected(mainvar)
+        elif isinstance(mainvar, basestring):
+            assert mainvar in select.defined_vars
+            mainvar = select.get_variable(mainvar)
+        # eases string -> syntax tree test transition: please remove once stable
+        select._varmaker = rqlvar_maker(defined=select.defined_vars,
+                                        aliases=select.aliases, index=26)
+        if settype:
+            select.add_type_restriction(mainvar, cls.__regid__)
+        if fetchattrs is None:
+            fetchattrs = cls.fetch_attrs
+        cls._fetch_restrictions(mainvar, select, fetchattrs, user, ordermethod)
+        return select
+
+    @classmethod
+    def _fetch_ambiguous_rtypes(cls, select, var, fetchattrs, subjtypes, schema):
+        """find rtypes in `fetchattrs` that relate different subject etypes
+        taken from (`subjtypes`) to different target etypes; these so called
+        "ambiguous" relations, are added directly to the `select` syntax tree
+        selection but removed from `fetchattrs` to avoid the fetch recursion
+        because we have to choose only one targettype for the recursion and
+        adding its own fetch attrs to the selection -when we recurse- would
+        filter out the other possible target types from the result set
+        """
+        for attr in fetchattrs.copy():
+            rschema = schema.rschema(attr)
+            if rschema.final:
+                continue
+            ttypes = None
+            for subjtype in subjtypes:
+                cur_ttypes = set(rschema.objects(subjtype))
+                if ttypes is None:
+                    ttypes = cur_ttypes
+                elif cur_ttypes != ttypes:
+                    # we found an ambiguous relation: remove it from fetchattrs
+                    fetchattrs.remove(attr)
+                    # ... and add it to the selection
+                    targetvar = select.make_variable()
+                    select.add_selected(targetvar)
+                    rel = make_relation(var, attr, (targetvar,), VariableRef)
+                    select.add_restriction(rel)
+                    break
+
+    @classmethod
+    def _fetch_restrictions(cls, mainvar, select, fetchattrs,
+                            user, ordermethod='fetch_order', visited=None):
         eschema = cls.e_schema
         if visited is None:
             visited = set((eschema.type,))
@@ -216,51 +285,85 @@
             rdef = eschema.rdef(attr)
             if not user.matching_groups(rdef.get_groups('read')):
                 continue
-            var = varmaker.next()
-            selection.append(var)
-            restriction = '%s %s %s' % (mainvar, attr, var)
-            restrictions.append(restriction)
+            if rschema.final or rdef.cardinality[0] in '?1':
+                var = select.make_variable()
+                select.add_selected(var)
+                rel = make_relation(mainvar, attr, (var,), VariableRef)
+                select.add_restriction(rel)
+            else:
+                cls.warning('bad relation %s specified in fetch attrs for %s',
+                            attr, cls)
+                continue
             if not rschema.final:
-                card = rdef.cardinality[0]
-                if card not in '?1':
-                    cls.warning('bad relation %s specified in fetch attrs for %s',
-                                 attr, cls)
-                    selection.pop()
-                    restrictions.pop()
-                    continue
                 # XXX we need outer join in case the relation is not mandatory
                 # (card == '?')  *or if the entity is being added*, since in
                 # that case the relation may still be missing. As we miss this
                 # later information here, systematically add it.
-                restrictions[-1] += '?'
+                rel.change_optional('right')
                 targettypes = rschema.objects(eschema.type)
-                # XXX user._cw.vreg iiiirk
-                etypecls = user._cw.vreg['etypes'].etype_class(targettypes[0])
+                vreg = user._cw.vreg # XXX user._cw.vreg iiiirk
+                etypecls = vreg['etypes'].etype_class(targettypes[0])
                 if len(targettypes) > 1:
                     # find fetch_attrs common to all destination types
-                    fetchattrs = user._cw.vreg['etypes'].fetch_attrs(targettypes)
-                    remove_ambiguous_rels(fetchattrs, targettypes, user._cw.vreg.schema)
+                    fetchattrs = vreg['etypes'].fetch_attrs(targettypes)
+                    # ... and handle ambiguous relations
+                    cls._fetch_ambiguous_rtypes(select, var, fetchattrs,
+                                                targettypes, vreg.schema)
                 else:
                     fetchattrs = etypecls.fetch_attrs
-                etypecls._fetch_restrictions(var, varmaker, fetchattrs,
-                                             selection, orderby, restrictions,
+                etypecls._fetch_restrictions(var, select, fetchattrs,
                                              user, ordermethod, visited=visited)
             if ordermethod is not None:
-                orderterm = getattr(cls, ordermethod)(attr, var)
-                if orderterm:
-                    orderby.append(orderterm)
-        return selection, orderby, restrictions
+                try:
+                    cmeth = getattr(cls, ordermethod)
+                    warn('[3.14] %s %s class method should be renamed to cw_%s'
+                         % (cls.__regid__, ordermethod, ordermethod),
+                         DeprecationWarning)
+                except AttributeError:
+                    cmeth = getattr(cls, 'cw_' + ordermethod)
+                if support_args(cmeth, 'select'):
+                    cmeth(select, attr, var)
+                else:
+                    warn('[3.14] %s should now take (select, attr, var) and '
+                         'modify the syntax tree when desired instead of '
+                         'returning something' % cmeth, DeprecationWarning)
+                    orderterm = cmeth(attr, var.name)
+                    if orderterm is not None:
+                        try:
+                            var, order = orderterm.split()
+                        except ValueError:
+                            if '(' in orderterm:
+                                self.error('ignore %s until %s is upgraded',
+                                           orderterm, cmeth)
+                                orderterm = None
+                            elif not ' ' in orderterm.strip():
+                                var = orderterm
+                                order = 'ASC'
+                        if orderterm is not None:
+                            select.add_sort_var(select.get_variable(var),
+                                                order=='ASC')
 
     @classmethod
     @cached
-    def _rest_attr_info(cls):
+    def cw_rest_attr_info(cls):
+        """this class method return an attribute name to be used in URL for
+        entities of this type and a boolean flag telling if its value should be
+        checked for uniqness.
+
+        The attribute returned is, in order of priority:
+
+        * class's `rest_attr` class attribute
+        * an attribute defined as unique in the class'schema
+        * 'eid'
+        """
         mainattr, needcheck = 'eid', True
         if cls.rest_attr:
             mainattr = cls.rest_attr
             needcheck = not cls.e_schema.has_unique_values(mainattr)
         else:
             for rschema in cls.e_schema.subject_relations():
-                if rschema.final and rschema != 'eid' and cls.e_schema.has_unique_values(rschema):
+                if rschema.final and rschema != 'eid' \
+                        and cls.e_schema.has_unique_values(rschema):
                     mainattr = str(rschema)
                     needcheck = False
                     break
@@ -354,7 +457,7 @@
         """custom json dumps hook to dump the entity's eid
         which is not part of dict structure itself
         """
-        dumpable = dict(self)
+        dumpable = self.cw_attr_cache.copy()
         dumpable['eid'] = self.eid
         return dumpable
 
@@ -452,7 +555,7 @@
 
     def rest_path(self, use_ext_eid=False): # XXX cw_rest_path
         """returns a REST-like (relative) path for this entity"""
-        mainattr, needcheck = self._rest_attr_info()
+        mainattr, needcheck = self.cw_rest_attr_info()
         etype = str(self.e_schema)
         path = etype.lower()
         if mainattr != 'eid':
@@ -516,8 +619,8 @@
                 return self._cw_mtc_transform(value.getvalue(), attrformat, format,
                                               encoding)
             return u''
-        value = printable_value(self._cw, attrtype, value, props,
-                                displaytime=displaytime)
+        value = self._cw.printable_value(attrtype, value, props,
+                                         displaytime=displaytime)
         if format == 'text/html':
             value = xml_escape(value)
         return value
@@ -542,13 +645,22 @@
         """
         assert self.has_eid()
         execute = self._cw.execute
+        skip_copy_for = {'subject': set(), 'object': set()}
+        for rtype in self.skip_copy_for:
+            skip_copy_for['subject'].add(rtype)
+            warn('[3.14] skip_copy_for on entity classes (%s) is deprecated, '
+                 'use cw_skip_for instead with list of couples (rtype, role)' % self.__regid__,
+                 DeprecationWarning)
+        for rtype, role in self.cw_skip_copy_for:
+            assert role in ('subject', 'object'), role
+            skip_copy_for[role].add(rtype)
         for rschema in self.e_schema.subject_relations():
             if rschema.final or rschema.meta:
                 continue
             # skip already defined relations
             if getattr(self, rschema.type):
                 continue
-            if rschema.type in self.skip_copy_for:
+            if rschema.type in skip_copy_for['subject']:
                 continue
             # skip composite relation
             rdef = self.e_schema.rdef(rschema)
@@ -568,6 +680,8 @@
             # skip already defined relations
             if self.related(rschema.type, 'object'):
                 continue
+            if rschema.type in skip_copy_for['object']:
+                continue
             rdef = self.e_schema.rdef(rschema, 'object')
             # skip composite relation
             if rdef.composite:
@@ -738,6 +852,7 @@
           if True, an empty rset/list of entities will be returned in case of
           :exc:`Unauthorized`, else (the default), the exception is propagated
         """
+        rtype = str(rtype)
         try:
             return self._cw_relation_cache(rtype, role, entities, limit)
         except KeyError:
@@ -757,51 +872,61 @@
         return self.related(rtype, role, limit, entities)
 
     def cw_related_rql(self, rtype, role='subject', targettypes=None):
-        rschema = self._cw.vreg.schema[rtype]
+        vreg = self._cw.vreg
+        rschema = vreg.schema[rtype]
+        select = Select()
+        mainvar, evar = select.get_variable('X'), select.get_variable('E')
+        select.add_selected(mainvar)
+        select.add_eid_restriction(evar, 'x', 'Substitute')
         if role == 'subject':
-            restriction = 'E eid %%(x)s, E %s X' % rtype
+            rel = make_relation(evar, rtype, (mainvar,), VariableRef)
+            select.add_restriction(rel)
             if targettypes is None:
                 targettypes = rschema.objects(self.e_schema)
             else:
-                restriction += ', X is IN (%s)' % ','.join(targettypes)
-            card = greater_card(rschema, (self.e_schema,), targettypes, 0)
+                select.add_constant_restriction(mainvar, 'is',
+                                                targettypes, 'etype')
+            gcard = greater_card(rschema, (self.e_schema,), targettypes, 0)
         else:
-            restriction = 'E eid %%(x)s, X %s E' % rtype
+            rel = make_relation(mainvar, rtype, (evar,), VariableRef)
+            select.add_restriction(rel)
             if targettypes is None:
                 targettypes = rschema.subjects(self.e_schema)
             else:
-                restriction += ', X is IN (%s)' % ','.join(targettypes)
-            card = greater_card(rschema, targettypes, (self.e_schema,), 1)
-        etypecls = self._cw.vreg['etypes'].etype_class(targettypes[0])
+                select.add_constant_restriction(mainvar, 'is', targettypes,
+                                                'String')
+            gcard = greater_card(rschema, targettypes, (self.e_schema,), 1)
+        etypecls = vreg['etypes'].etype_class(targettypes[0])
         if len(targettypes) > 1:
-            fetchattrs = self._cw.vreg['etypes'].fetch_attrs(targettypes)
-            # XXX we should fetch ambiguous relation objects too but not
-            # recurse on them in _fetch_restrictions; it is easier to remove
-            # them completely for now, as it would require an deeper api rewrite
-            remove_ambiguous_rels(fetchattrs, targettypes, self._cw.vreg.schema)
+            fetchattrs = vreg['etypes'].fetch_attrs(targettypes)
+            self._fetch_ambiguous_rtypes(select, mainvar, fetchattrs,
+                                         targettypes, vreg.schema)
         else:
             fetchattrs = etypecls.fetch_attrs
-        rql = etypecls.fetch_rql(self._cw.user, [restriction], fetchattrs,
-                                 settype=False)
+        etypecls.fetch_rqlst(self._cw.user, select, mainvar, fetchattrs,
+                             settype=False)
         # optimisation: remove ORDERBY if cardinality is 1 or ? (though
         # greater_card return 1 for those both cases)
-        if card == '1':
-            if ' ORDERBY ' in rql:
-                rql = '%s WHERE %s' % (rql.split(' ORDERBY ', 1)[0],
-                                       rql.split(' WHERE ', 1)[1])
-        elif not ' ORDERBY ' in rql:
-            args = rql.split(' WHERE ', 1)
-            # if modification_date already retrieved, we should use it instead
-            # of adding another variable for sort. This should be be problematic
-            # but it's actually with sqlserver, see ticket #694445
-            if 'X modification_date ' in args[1]:
-                var = args[1].split('X modification_date ', 1)[1].split(',', 1)[0]
-                args.insert(1, var.strip())
-                rql = '%s ORDERBY %s DESC WHERE %s' % tuple(args)
+        if gcard == '1':
+            select.remove_sort_terms()
+        elif not select.orderby:
+            # if modification_date is already retrieved, we use it instead
+            # of adding another variable for sorting. This should not be
+            # problematic, but it is with sqlserver, see ticket #694445
+            for rel in select.where.get_nodes(RqlRelation):
+                if (rel.r_type == 'modification_date'
+                    and rel.children[0].variable == mainvar
+                    and rel.children[1].operator == '='):
+                    var = rel.children[1].children[0].variable
+                    select.add_sort_var(var, asc=False)
+                    break
             else:
-                rql = '%s ORDERBY Z DESC WHERE X modification_date Z, %s' % \
-                      tuple(args)
-        return rql
+                mdvar = select.make_variable()
+                rel = make_relation(mainvar, 'modification_date',
+                                    (mdvar,), VariableRef)
+                select.add_restriction(rel)
+                select.add_sort_var(mdvar, asc=False)
+        return select.as_string()
 
     # generic vocabulary methods ##############################################
 
@@ -818,33 +943,36 @@
             rtype = self._cw.vreg.schema.rschema(rtype)
         rdef = rtype.role_rdef(self.e_schema, targettype, role)
         rewriter = RQLRewriter(self._cw)
+        select = Select()
         # initialize some variables according to the `role` of `self` in the
-        # relation:
-        # * variable for myself (`evar`) and searched entities (`searchvedvar`)
-        # * entity type of the subject (`subjtype`) and of the object
-        #   (`objtype`) of the relation
+        # relation (variable names must respect constraints conventions):
+        # * variable for myself (`evar`)
+        # * variable for searched entities (`searchvedvar`)
         if role == 'subject':
-            evar, searchedvar = 'S', 'O'
-            subjtype, objtype = self.e_schema, targettype
+            evar = subjvar = select.get_variable('S')
+            searchedvar = objvar = select.get_variable('O')
         else:
-            searchedvar, evar = 'S', 'O'
-            objtype, subjtype = self.e_schema, targettype
+            searchedvar = subjvar = select.get_variable('S')
+            evar = objvar = select.get_variable('O')
+        select.add_selected(searchedvar)
         # initialize some variables according to `self` existance
         if rdef.role_cardinality(neg_role(role)) in '?1':
             # if cardinality in '1?', we want a target entity which isn't
             # already linked using this relation
-            if searchedvar == 'S':
-                restriction = ['NOT S %s ZZ' % rtype]
+            var = select.get_variable('ZZ') # XXX unname when tests pass
+            if role == 'subject':
+                rel = make_relation(var, rtype.type, (searchedvar,), VariableRef)
             else:
-                restriction = ['NOT ZZ %s O' % rtype]
+                rel = make_relation(searchedvar, rtype.type, (var,), VariableRef)
+            select.add_restriction(Not(rel))
         elif self.has_eid():
             # elif we have an eid, we don't want a target entity which is
             # already linked to ourself through this relation
-            restriction = ['NOT S %s O' % rtype]
-        else:
-            restriction = []
+            rel = make_relation(subjvar, rtype.type, (objvar,), VariableRef)
+            select.add_restriction(Not(rel))
         if self.has_eid():
-            restriction += ['%s eid %%(x)s' % evar]
+            rel = make_relation(evar, 'eid', ('x', 'Substitute'), Constant)
+            select.add_restriction(rel)
             args = {'x': self.eid}
             if role == 'subject':
                 sec_check_args = {'fromeid': self.eid}
@@ -854,12 +982,15 @@
         else:
             args = {}
             sec_check_args = {}
-            existant = searchedvar
-        # retreive entity class for targettype to compute base rql
+            existant = searchedvar.name
+            # undefine unused evar, or the type resolver will consider it
+            select.undefine_variable(evar)
+        # retrieve entity class for targettype to compute base rql
         etypecls = self._cw.vreg['etypes'].etype_class(targettype)
-        rql = etypecls.fetch_rql(self._cw.user, restriction,
-                                 mainvar=searchedvar, ordermethod=ordermethod)
-        select = self._cw.vreg.parse(self._cw, rql, args).children[0]
+        etypecls.fetch_rqlst(self._cw.user, select, searchedvar,
+                             ordermethod=ordermethod)
+        # from now on, we need variable type resolving
+        self._cw.vreg.solutions(self._cw, select, args)
         # insert RQL expressions for schema constraints into the rql syntax tree
         if vocabconstraints:
             # RQLConstraint is a subclass for RQLVocabularyConstraint, so they
@@ -869,12 +1000,12 @@
             cstrcls = RQLConstraint
         for cstr in rdef.constraints:
             # consider constraint.mainvars to check if constraint apply
-            if isinstance(cstr, cstrcls) and searchedvar in cstr.mainvars:
-                if not self.has_eid() and evar in cstr.mainvars:
+            if isinstance(cstr, cstrcls) and searchedvar.name in cstr.mainvars:
+                if not self.has_eid() and evar.name in cstr.mainvars:
                     continue
                 # compute a varmap suitable to RQLRewriter.rewrite argument
-                varmap = dict((v, v) for v in 'SO' if v in select.defined_vars
-                              and v in cstr.mainvars)
+                varmap = dict((v, v) for v in (searchedvar.name, evar.name)
+                              if v in select.defined_vars and v in cstr.mainvars)
                 # rewrite constraint by constraint since we want a AND between
                 # expressions.
                 rewriter.rewrite(select, [(varmap, (cstr,))], select.solutions,
@@ -884,13 +1015,14 @@
         rqlexprs = rdef.get_rqlexprs('add')
         if rqlexprs and not rdef.has_perm(self._cw, 'add', **sec_check_args):
             # compute a varmap suitable to RQLRewriter.rewrite argument
-            varmap = dict((v, v) for v in 'SO' if v in select.defined_vars)
+            varmap = dict((v, v) for v in (searchedvar.name, evar.name)
+                          if v in select.defined_vars)
             # rewrite all expressions at once since we want a OR between them.
             rewriter.rewrite(select, [(varmap, rqlexprs)], select.solutions,
                              args, existant)
         # ensure we have an order defined
         if not select.orderby:
-            select.add_sort_var(select.defined_vars[searchedvar])
+            select.add_sort_var(select.defined_vars[searchedvar.name])
         # we're done, turn the rql syntax tree as a string
         rql = select.as_string()
         return rql, args
--- a/etwist/test/unittest_server.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/etwist/test/unittest_server.py	Fri Oct 14 09:21:45 2011 +0200
@@ -69,7 +69,7 @@
 
     def test_cache(self):
         concat = ConcatFiles(self.config, ('cubicweb.ajax.js', 'jquery.js'))
-        self.failUnless(osp.isfile(concat.path))
+        self.assertTrue(osp.isfile(concat.path))
 
     def test_404(self):
         # when not in debug mode, should not crash
--- a/hooks/test/unittest_bookmarks.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/hooks/test/unittest_bookmarks.py	Fri Oct 14 09:21:45 2011 +0200
@@ -28,10 +28,10 @@
         self.commit()
         self.execute('DELETE X bookmarked_by U WHERE U login "admin"')
         self.commit()
-        self.failUnless(self.execute('Any X WHERE X eid %(x)s', {'x': beid}))
+        self.assertTrue(self.execute('Any X WHERE X eid %(x)s', {'x': beid}))
         self.execute('DELETE X bookmarked_by U WHERE U login "anon"')
         self.commit()
-        self.failIf(self.execute('Any X WHERE X eid %(x)s', {'x': beid}))
+        self.assertFalse(self.execute('Any X WHERE X eid %(x)s', {'x': beid}))
 
 if __name__ == '__main__':
     unittest_main()
--- a/hooks/test/unittest_hooks.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/hooks/test/unittest_hooks.py	Fri Oct 14 09:21:45 2011 +0200
@@ -117,7 +117,7 @@
                           self.repo.connect, u'toto', password='hop')
         self.commit()
         cnxid = self.repo.connect(u'toto', password='hop')
-        self.failIfEqual(cnxid, self.session.id)
+        self.assertNotEqual(cnxid, self.session.id)
         self.execute('DELETE CWUser X WHERE X login "toto"')
         self.repo.execute(cnxid, 'State X')
         self.commit()
@@ -151,7 +151,7 @@
         eid = self.execute('INSERT EmailAddress X: X address "toto@logilab.fr"')[0][0]
         self.execute('DELETE EmailAddress X WHERE X eid %s' % eid)
         self.commit()
-        self.failIf(self.execute('Any X WHERE X created_by Y, X eid >= %(x)s', {'x': eid}))
+        self.assertFalse(self.execute('Any X WHERE X created_by Y, X eid >= %(x)s', {'x': eid}))
 
 
 
--- a/hooks/test/unittest_integrity.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/hooks/test/unittest_integrity.py	Fri Oct 14 09:21:45 2011 +0200
@@ -62,7 +62,7 @@
         self.execute('INSERT EmailPart X: X content_format "text/plain", X ordernum 1, X content "this is a test"')
         self.execute('INSERT Email X: X messageid "<1234>", X subject "test", X sender Y, X recipients Y, X parts P '
                      'WHERE Y is EmailAddress, P is EmailPart')
-        self.failUnless(self.execute('Email X WHERE X sender Y'))
+        self.assertTrue(self.execute('Email X WHERE X sender Y'))
         self.commit()
         self.execute('DELETE Email X')
         rset = self.execute('Any X WHERE X is EmailPart')
--- a/hooks/test/unittest_syncschema.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/hooks/test/unittest_syncschema.py	Fri Oct 14 09:21:45 2011 +0200
@@ -60,18 +60,18 @@
         self.session.set_cnxset()
         dbhelper = self.session.cnxset.source('system').dbhelper
         sqlcursor = self.session.cnxset['system']
-        self.failIf(schema.has_entity('Societe2'))
-        self.failIf(schema.has_entity('concerne2'))
+        self.assertFalse(schema.has_entity('Societe2'))
+        self.assertFalse(schema.has_entity('concerne2'))
         # schema should be update on insertion (after commit)
         eeid = self.execute('INSERT CWEType X: X name "Societe2", X description "", X final FALSE')[0][0]
         self._set_perms(eeid)
         self.execute('INSERT CWRType X: X name "concerne2", X description "", X final FALSE, X symmetric FALSE')
-        self.failIf(schema.has_entity('Societe2'))
-        self.failIf(schema.has_entity('concerne2'))
+        self.assertFalse(schema.has_entity('Societe2'))
+        self.assertFalse(schema.has_entity('concerne2'))
         # have to commit before adding definition relations
         self.commit()
-        self.failUnless(schema.has_entity('Societe2'))
-        self.failUnless(schema.has_relation('concerne2'))
+        self.assertTrue(schema.has_entity('Societe2'))
+        self.assertTrue(schema.has_relation('concerne2'))
         attreid = self.execute('INSERT CWAttribute X: X cardinality "11", X defaultval "noname", '
                                '   X indexed TRUE, X relation_type RT, X from_entity E, X to_entity F '
                                'WHERE RT name "name", E name "Societe2", F name "String"')[0][0]
@@ -80,13 +80,13 @@
             'INSERT CWRelation X: X cardinality "**", X relation_type RT, X from_entity E, X to_entity E '
             'WHERE RT name "concerne2", E name "Societe2"')[0][0]
         self._set_perms(concerne2_rdef_eid)
-        self.failIf('name' in schema['Societe2'].subject_relations())
-        self.failIf('concerne2' in schema['Societe2'].subject_relations())
-        self.failIf(self.index_exists('Societe2', 'name'))
+        self.assertFalse('name' in schema['Societe2'].subject_relations())
+        self.assertFalse('concerne2' in schema['Societe2'].subject_relations())
+        self.assertFalse(self.index_exists('Societe2', 'name'))
         self.commit()
-        self.failUnless('name' in schema['Societe2'].subject_relations())
-        self.failUnless('concerne2' in schema['Societe2'].subject_relations())
-        self.failUnless(self.index_exists('Societe2', 'name'))
+        self.assertTrue('name' in schema['Societe2'].subject_relations())
+        self.assertTrue('concerne2' in schema['Societe2'].subject_relations())
+        self.assertTrue(self.index_exists('Societe2', 'name'))
         # now we should be able to insert and query Societe2
         s2eid = self.execute('INSERT Societe2 X: X name "logilab"')[0][0]
         self.execute('Societe2 X WHERE X name "logilab"')
@@ -101,20 +101,20 @@
         self.commit()
         self.execute('DELETE CWRelation X WHERE X eid %(x)s', {'x': concerne2_rdef_eid})
         self.commit()
-        self.failUnless('concerne2' in schema['CWUser'].subject_relations())
-        self.failIf('concerne2' in schema['Societe2'].subject_relations())
-        self.failIf(self.execute('Any X WHERE X concerne2 Y'))
+        self.assertTrue('concerne2' in schema['CWUser'].subject_relations())
+        self.assertFalse('concerne2' in schema['Societe2'].subject_relations())
+        self.assertFalse(self.execute('Any X WHERE X concerne2 Y'))
         # schema should be cleaned on delete (after commit)
         self.execute('DELETE CWEType X WHERE X name "Societe2"')
         self.execute('DELETE CWRType X WHERE X name "concerne2"')
-        self.failUnless(self.index_exists('Societe2', 'name'))
-        self.failUnless(schema.has_entity('Societe2'))
-        self.failUnless(schema.has_relation('concerne2'))
+        self.assertTrue(self.index_exists('Societe2', 'name'))
+        self.assertTrue(schema.has_entity('Societe2'))
+        self.assertTrue(schema.has_relation('concerne2'))
         self.commit()
-        self.failIf(self.index_exists('Societe2', 'name'))
-        self.failIf(schema.has_entity('Societe2'))
-        self.failIf(schema.has_entity('concerne2'))
-        self.failIf('concerne2' in schema['CWUser'].subject_relations())
+        self.assertFalse(self.index_exists('Societe2', 'name'))
+        self.assertFalse(schema.has_entity('Societe2'))
+        self.assertFalse(schema.has_entity('concerne2'))
+        self.assertFalse('concerne2' in schema['CWUser'].subject_relations())
 
     def test_is_instance_of_insertions(self):
         seid = self.execute('INSERT Transition T: T name "subdiv"')[0][0]
@@ -123,15 +123,15 @@
         instanceof_etypes = [etype for etype, in self.execute('Any ETN WHERE X eid %s, X is_instance_of ET, ET name ETN' % seid)]
         self.assertEqual(sorted(instanceof_etypes), ['BaseTransition', 'Transition'])
         snames = [name for name, in self.execute('Any N WHERE S is BaseTransition, S name N')]
-        self.failIf('subdiv' in snames)
+        self.assertFalse('subdiv' in snames)
         snames = [name for name, in self.execute('Any N WHERE S is_instance_of BaseTransition, S name N')]
-        self.failUnless('subdiv' in snames)
+        self.assertTrue('subdiv' in snames)
 
 
     def test_perms_synchronization_1(self):
         schema = self.repo.schema
         self.assertEqual(schema['CWUser'].get_groups('read'), set(('managers', 'users')))
-        self.failUnless(self.execute('Any X, Y WHERE X is CWEType, X name "CWUser", Y is CWGroup, Y name "users"')[0])
+        self.assertTrue(self.execute('Any X, Y WHERE X is CWEType, X name "CWUser", Y is CWGroup, Y name "users"')[0])
         self.execute('DELETE X read_permission Y WHERE X is CWEType, X name "CWUser", Y name "users"')
         self.assertEqual(schema['CWUser'].get_groups('read'), set(('managers', 'users', )))
         self.commit()
@@ -173,13 +173,13 @@
         self.session.set_cnxset()
         dbhelper = self.session.cnxset.source('system').dbhelper
         sqlcursor = self.session.cnxset['system']
-        self.failUnless(self.schema['state_of'].inlined)
+        self.assertTrue(self.schema['state_of'].inlined)
         try:
             self.execute('SET X inlined FALSE WHERE X name "state_of"')
-            self.failUnless(self.schema['state_of'].inlined)
+            self.assertTrue(self.schema['state_of'].inlined)
             self.commit()
-            self.failIf(self.schema['state_of'].inlined)
-            self.failIf(self.index_exists('State', 'state_of'))
+            self.assertFalse(self.schema['state_of'].inlined)
+            self.assertFalse(self.index_exists('State', 'state_of'))
             rset = self.execute('Any X, Y WHERE X state_of Y')
             self.assertEqual(len(rset), 2) # user states
         except Exception:
@@ -187,10 +187,10 @@
             traceback.print_exc()
         finally:
             self.execute('SET X inlined TRUE WHERE X name "state_of"')
-            self.failIf(self.schema['state_of'].inlined)
+            self.assertFalse(self.schema['state_of'].inlined)
             self.commit()
-            self.failUnless(self.schema['state_of'].inlined)
-            self.failUnless(self.index_exists('State', 'state_of'))
+            self.assertTrue(self.schema['state_of'].inlined)
+            self.assertTrue(self.index_exists('State', 'state_of'))
             rset = self.execute('Any X, Y WHERE X state_of Y')
             self.assertEqual(len(rset), 2)
 
@@ -200,18 +200,18 @@
         sqlcursor = self.session.cnxset['system']
         try:
             self.execute('SET X indexed FALSE WHERE X relation_type R, R name "name"')
-            self.failUnless(self.schema['name'].rdef('Workflow', 'String').indexed)
-            self.failUnless(self.index_exists('Workflow', 'name'))
+            self.assertTrue(self.schema['name'].rdef('Workflow', 'String').indexed)
+            self.assertTrue(self.index_exists('Workflow', 'name'))
             self.commit()
-            self.failIf(self.schema['name'].rdef('Workflow', 'String').indexed)
-            self.failIf(self.index_exists('Workflow', 'name'))
+            self.assertFalse(self.schema['name'].rdef('Workflow', 'String').indexed)
+            self.assertFalse(self.index_exists('Workflow', 'name'))
         finally:
             self.execute('SET X indexed TRUE WHERE X relation_type R, R name "name"')
-            self.failIf(self.schema['name'].rdef('Workflow', 'String').indexed)
-            self.failIf(self.index_exists('Workflow', 'name'))
+            self.assertFalse(self.schema['name'].rdef('Workflow', 'String').indexed)
+            self.assertFalse(self.index_exists('Workflow', 'name'))
             self.commit()
-            self.failUnless(self.schema['name'].rdef('Workflow', 'String').indexed)
-            self.failUnless(self.index_exists('Workflow', 'name'))
+            self.assertTrue(self.schema['name'].rdef('Workflow', 'String').indexed)
+            self.assertTrue(self.index_exists('Workflow', 'name'))
 
     def test_unique_change(self):
         self.session.set_cnxset()
@@ -221,20 +221,20 @@
             self.execute('INSERT CWConstraint X: X cstrtype CT, DEF constrained_by X '
                          'WHERE CT name "UniqueConstraint", DEF relation_type RT, DEF from_entity E,'
                          'RT name "name", E name "Workflow"')
-            self.failIf(self.schema['Workflow'].has_unique_values('name'))
-            self.failIf(self.index_exists('Workflow', 'name', unique=True))
+            self.assertFalse(self.schema['Workflow'].has_unique_values('name'))
+            self.assertFalse(self.index_exists('Workflow', 'name', unique=True))
             self.commit()
-            self.failUnless(self.schema['Workflow'].has_unique_values('name'))
-            self.failUnless(self.index_exists('Workflow', 'name', unique=True))
+            self.assertTrue(self.schema['Workflow'].has_unique_values('name'))
+            self.assertTrue(self.index_exists('Workflow', 'name', unique=True))
         finally:
             self.execute('DELETE DEF constrained_by X WHERE X cstrtype CT, '
                          'CT name "UniqueConstraint", DEF relation_type RT, DEF from_entity E,'
                          'RT name "name", E name "Workflow"')
-            self.failUnless(self.schema['Workflow'].has_unique_values('name'))
-            self.failUnless(self.index_exists('Workflow', 'name', unique=True))
+            self.assertTrue(self.schema['Workflow'].has_unique_values('name'))
+            self.assertTrue(self.index_exists('Workflow', 'name', unique=True))
             self.commit()
-            self.failIf(self.schema['Workflow'].has_unique_values('name'))
-            self.failIf(self.index_exists('Workflow', 'name', unique=True))
+            self.assertFalse(self.schema['Workflow'].has_unique_values('name'))
+            self.assertFalse(self.index_exists('Workflow', 'name', unique=True))
 
     def test_required_change_1(self):
         self.execute('SET DEF cardinality "?1" '
@@ -267,8 +267,8 @@
                      {'x': attreid})
         self.commit()
         self.schema.rebuild_infered_relations()
-        self.failUnless('Transition' in self.schema['messageid'].subjects())
-        self.failUnless('WorkflowTransition' in self.schema['messageid'].subjects())
+        self.assertTrue('Transition' in self.schema['messageid'].subjects())
+        self.assertTrue('WorkflowTransition' in self.schema['messageid'].subjects())
         self.execute('Any X WHERE X is_instance_of BaseTransition, X messageid "hop"')
 
     def test_change_fulltextindexed(self):
@@ -283,7 +283,7 @@
                             'A from_entity E, A relation_type R, R name "subject"')
         self.commit()
         rset = req.execute('Any X WHERE X has_text "rick.roll"')
-        self.failIf(rset)
+        self.assertFalse(rset)
         assert req.execute('SET A fulltextindexed TRUE '
                            'WHERE A from_entity E, A relation_type R, '
                            'E name "Email", R name "subject"')
--- a/i18n.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/i18n.py	Fri Oct 14 09:21:45 2011 +0200
@@ -33,7 +33,7 @@
     output = open(output_file, 'w')
     for filepath in files:
         for match in re.finditer('i18n:(content|replace)="([^"]+)"', open(filepath).read()):
-            print >> output, '_("%s")' % match.group(2)
+            output.write('_("%s")' % match.group(2))
     output.close()
 
 
--- a/i18n/de.po	Fri Oct 14 09:04:39 2011 +0200
+++ b/i18n/de.po	Fri Oct 14 09:21:45 2011 +0200
@@ -344,12 +344,6 @@
 msgid "CWGroup_plural"
 msgstr "Gruppen"
 
-msgid "CWPermission"
-msgstr "Berechtigung"
-
-msgid "CWPermission_plural"
-msgstr "Berechtigungen"
-
 msgid "CWProperty"
 msgstr "Eigenschaft"
 
@@ -552,6 +546,9 @@
 msgid "Manage"
 msgstr ""
 
+msgid "Manage security"
+msgstr "Sicherheitsverwaltung"
+
 msgid "Most referenced classes"
 msgstr "meist-referenzierte Klassen"
 
@@ -579,9 +576,6 @@
 msgid "New CWGroup"
 msgstr "Neue Gruppe"
 
-msgid "New CWPermission"
-msgstr "Neue Berechtigung"
-
 msgid "New CWProperty"
 msgstr "Neue Eigenschaft"
 
@@ -648,6 +642,9 @@
 msgid "OR"
 msgstr "oder"
 
+msgid "Ownership"
+msgstr "Eigentum"
+
 msgid "Parent class:"
 msgstr "Elternklasse"
 
@@ -697,8 +694,8 @@
 msgid "Schema %s"
 msgstr "Schema %s"
 
-msgid "Schema of the data model"
-msgstr "Schema des Datenmodells"
+msgid "Schema's permissions definitions"
+msgstr "Im Schema definierte Rechte"
 
 msgid "Search for"
 msgstr "Suchen"
@@ -798,9 +795,6 @@
 msgid "This CWGroup"
 msgstr "Diese Gruppe"
 
-msgid "This CWPermission"
-msgstr "Diese Berechtigung"
-
 msgid "This CWProperty"
 msgstr "Diese Eigenschaft"
 
@@ -885,6 +879,9 @@
 msgid "Used by:"
 msgstr "benutzt von:"
 
+msgid "Users and groups management"
+msgstr ""
+
 msgid "Web server"
 msgstr "Web-Server"
 
@@ -948,7 +945,7 @@
 msgid ""
 "a RQL expression which should return some results, else the transition won't "
 "be available. This query may use X and U variables that will respectivly "
-"represents the current entity and the current user"
+"represents the current entity and the current user."
 msgstr ""
 "ein RQL-Ausdruck, der einige Treffer liefern sollte, sonst wird der Ãœbergang "
 "nicht verfügbar sein. Diese Abfrage kann X und U Variable benutzen, die "
@@ -1087,13 +1084,13 @@
 msgid "add a CWRType"
 msgstr "einen Relationstyp hinzufügen"
 
+msgid "add a CWSource"
+msgstr ""
+
 msgctxt "inlined:CWUser.use_email.subject"
 msgid "add a EmailAddress"
 msgstr "Email-Adresse hinzufügen"
 
-msgid "add a new permission"
-msgstr "eine Berechtigung hinzufügen"
-
 # subject and object forms for each relation type
 # (no object form for final relation types)
 msgid "add_permission"
@@ -1873,6 +1870,12 @@
 msgid "custom_workflow_object"
 msgstr "angepasster Workflow von"
 
+msgid "cw.groups-management"
+msgstr ""
+
+msgid "cw.users-management"
+msgstr ""
+
 msgid "cw_for_source"
 msgstr ""
 
@@ -2080,9 +2083,6 @@
 msgid "delete this bookmark"
 msgstr "dieses Lesezeichen löschen"
 
-msgid "delete this permission"
-msgstr "dieses Recht löschen"
-
 msgid "delete this relation"
 msgstr "diese Relation löschen"
 
@@ -2256,13 +2256,6 @@
 msgid "display the facet or not"
 msgstr "die Facette anzeigen oder nicht"
 
-msgid ""
-"distinct label to distinguate between other permission entity of the same "
-"name"
-msgstr ""
-"Zusätzliches Label, um von anderen Berechtigungsentitäten unterscheiden zu "
-"können."
-
 msgid "download"
 msgstr "Herunterladen"
 
@@ -2333,12 +2326,6 @@
 msgid "entity type"
 msgstr "Entitätstyp"
 
-msgid ""
-"entity type that may be used to construct some advanced security "
-"configuration"
-msgstr ""
-"Entitätstyp zum Aufbau einer fortgeschrittenen Sicherheitskonfiguration."
-
 msgid "entity types which may use this workflow"
 msgstr "Entitätstypen, die diesen Workflow benutzen können."
 
@@ -2631,9 +2618,6 @@
 msgid "groups grant permissions to the user"
 msgstr "die Gruppen geben dem Nutzer Rechte"
 
-msgid "groups to which the permission is granted"
-msgstr "Gruppen, denen dieses Recht verliehen ist"
-
 msgid "guests"
 msgstr "Gäste"
 
@@ -2828,9 +2812,6 @@
 msgid "instance home"
 msgstr "Startseite der Instanz"
 
-msgid "instance schema"
-msgstr "Schema der Instanz"
-
 msgid "internal entity uri"
 msgstr "interner URI"
 
@@ -2897,13 +2878,6 @@
 msgid "june"
 msgstr "Juni"
 
-msgid "label"
-msgstr "gekennzeichnet"
-
-msgctxt "CWPermission"
-msgid "label"
-msgstr "gekennzeichnet"
-
 msgid "language of the user interface"
 msgstr "Sprache der Nutzer-Schnittstelle"
 
@@ -2946,14 +2920,6 @@
 msgstr "links"
 
 msgid ""
-"link a permission to the entity. This permission should be used in the "
-"security definition of the entity's type to be useful."
-msgstr ""
-"verknüpft eine Berechtigung mit einer Entität. Um Nützlich zu sein, sollte "
-"diese Berechtigung in der Sicherheitsdefinition des Entitätstyps benutzt "
-"werden."
-
-msgid ""
 "link a property to the user which want this property customization. Unless "
 "you're a site manager, this relation will be handled automatically."
 msgstr ""
@@ -3037,9 +3003,6 @@
 msgid "manage permissions"
 msgstr "Rechte verwalten"
 
-msgid "manage security"
-msgstr "Sicherheitsverwaltung"
-
 msgid "managers"
 msgstr "Administratoren"
 
@@ -3131,10 +3094,6 @@
 msgid "name"
 msgstr "Name"
 
-msgctxt "CWPermission"
-msgid "name"
-msgstr "Name"
-
 msgctxt "CWRType"
 msgid "name"
 msgstr "Name"
@@ -3172,9 +3131,6 @@
 msgid "name of the source"
 msgstr ""
 
-msgid "name or identifier of the permission"
-msgstr "Name (oder Bezeichner) der Berechtigung"
-
 msgid "navbottom"
 msgstr "zum Seitenende"
 
@@ -3211,9 +3167,6 @@
 msgid "no"
 msgstr "Nein"
 
-msgid "no associated permissions"
-msgstr "keine entsprechende Berechtigung"
-
 msgid "no content next link"
 msgstr ""
 
@@ -3327,9 +3280,6 @@
 msgid "owners"
 msgstr "Besitzer"
 
-msgid "ownership"
-msgstr "Eigentum"
-
 msgid "ownerships have been changed"
 msgstr "Die Eigentumsrechte sind geändert worden."
 
@@ -3367,9 +3317,6 @@
 msgid "permissions"
 msgstr "Rechte"
 
-msgid "permissions for this entity"
-msgstr "Rechte für diese Entität"
-
 msgid "pick existing bookmarks"
 msgstr "Wählen Sie aus den bestehenden lesezeichen aus"
 
@@ -3567,10 +3514,6 @@
 msgid "require_group"
 msgstr "auf Gruppe beschränkt"
 
-msgctxt "CWPermission"
-msgid "require_group"
-msgstr "auf Gruppe beschränkt"
-
 msgctxt "Transition"
 msgid "require_group"
 msgstr "auf Gruppe beschränkt"
@@ -3586,12 +3529,6 @@
 msgid "require_group_object"
 msgstr "hat die Rechte"
 
-msgid "require_permission"
-msgstr "erfordert Berechtigung"
-
-msgid "require_permission_object"
-msgstr "Berechtigung von"
-
 msgid "required"
 msgstr "erforderlich"
 
@@ -3647,9 +3584,6 @@
 msgid "saturday"
 msgstr "Samstag"
 
-msgid "schema's permissions definitions"
-msgstr "Im Schema definierte Rechte"
-
 msgid "schema-diagram"
 msgstr "Diagramm"
 
@@ -3764,9 +3698,6 @@
 "Eine Eigenschaft für die gesamte Website kann nicht für einen Nutzer gesetzt "
 "werden."
 
-msgid "siteinfo"
-msgstr ""
-
 msgid "some later transaction(s) touch entity, undo them first"
 msgstr ""
 "Eine oder mehrere frühere Transaktion(en) betreffen die Tntität. Machen Sie "
@@ -4281,9 +4212,6 @@
 msgid "url"
 msgstr ""
 
-msgid "use template languages"
-msgstr "Verwenden Sie Templating-Sprachen"
-
 msgid ""
 "use to define a transition from one or multiple states to a destination "
 "states in workflow's definitions. Transition without destination state will "
@@ -4307,9 +4235,6 @@
 msgid "use_email_object"
 msgstr "verwendet von"
 
-msgid "use_template_format"
-msgstr "Benutzung des 'cubicweb template'-Formats"
-
 msgid ""
 "used for cubicweb configuration. Once a property has been created you can't "
 "change the key."
@@ -4323,9 +4248,6 @@
 "assoziiert einfache Zustände mit einem Entitätstyp und/oder definiert "
 "Workflows"
 
-msgid "used to grant a permission to a group"
-msgstr "gibt einer Gruppe eine Berechtigung"
-
 msgid "user"
 msgstr "Nutzer"
 
@@ -4352,9 +4274,6 @@
 msgid "users and groups"
 msgstr ""
 
-msgid "users and groups management"
-msgstr ""
-
 msgid "users using this bookmark"
 msgstr "Nutzer, die dieses Lesezeichen verwenden"
 
@@ -4544,3 +4463,9 @@
 #, python-format
 msgid "you should un-inline relation %s which is supported and may be crossed "
 msgstr ""
+
+#~ msgid "Schema of the data model"
+#~ msgstr "Schema des Datenmodells"
+
+#~ msgid "instance schema"
+#~ msgstr "Schema der Instanz"
--- a/i18n/en.po	Fri Oct 14 09:04:39 2011 +0200
+++ b/i18n/en.po	Fri Oct 14 09:21:45 2011 +0200
@@ -333,12 +333,6 @@
 msgid "CWGroup_plural"
 msgstr "Groups"
 
-msgid "CWPermission"
-msgstr "Permission"
-
-msgid "CWPermission_plural"
-msgstr "Permissions"
-
 msgid "CWProperty"
 msgstr "Property"
 
@@ -528,6 +522,9 @@
 msgid "Manage"
 msgstr ""
 
+msgid "Manage security"
+msgstr ""
+
 msgid "Most referenced classes"
 msgstr ""
 
@@ -555,9 +552,6 @@
 msgid "New CWGroup"
 msgstr "New group"
 
-msgid "New CWPermission"
-msgstr "New permission"
-
 msgid "New CWProperty"
 msgstr "New property"
 
@@ -622,6 +616,9 @@
 msgid "OR"
 msgstr ""
 
+msgid "Ownership"
+msgstr ""
+
 msgid "Parent class:"
 msgstr ""
 
@@ -671,7 +668,7 @@
 msgid "Schema %s"
 msgstr ""
 
-msgid "Schema of the data model"
+msgid "Schema's permissions definitions"
 msgstr ""
 
 msgid "Search for"
@@ -772,9 +769,6 @@
 msgid "This CWGroup"
 msgstr "This group"
 
-msgid "This CWPermission"
-msgstr "This permission"
-
 msgid "This CWProperty"
 msgstr "This property"
 
@@ -859,6 +853,9 @@
 msgid "Used by:"
 msgstr ""
 
+msgid "Users and groups management"
+msgstr ""
+
 msgid "Web server"
 msgstr ""
 
@@ -911,7 +908,7 @@
 msgid ""
 "a RQL expression which should return some results, else the transition won't "
 "be available. This query may use X and U variables that will respectivly "
-"represents the current entity and the current user"
+"represents the current entity and the current user."
 msgstr ""
 
 msgid "a URI representing an object in external data store"
@@ -1051,9 +1048,6 @@
 msgid "add a EmailAddress"
 msgstr "add an email address"
 
-msgid "add a new permission"
-msgstr ""
-
 # subject and object forms for each relation type
 # (no object form for final relation types)
 msgid "add_permission"
@@ -1828,6 +1822,12 @@
 msgid "custom_workflow_object"
 msgstr "custom workflow of"
 
+msgid "cw.groups-management"
+msgstr "groups"
+
+msgid "cw.users-management"
+msgstr "users"
+
 msgid "cw_for_source"
 msgstr "for source"
 
@@ -2031,9 +2031,6 @@
 msgid "delete this bookmark"
 msgstr ""
 
-msgid "delete this permission"
-msgstr ""
-
 msgid "delete this relation"
 msgstr ""
 
@@ -2203,11 +2200,6 @@
 msgid "display the facet or not"
 msgstr ""
 
-msgid ""
-"distinct label to distinguate between other permission entity of the same "
-"name"
-msgstr ""
-
 msgid "download"
 msgstr ""
 
@@ -2278,11 +2270,6 @@
 msgid "entity type"
 msgstr ""
 
-msgid ""
-"entity type that may be used to construct some advanced security "
-"configuration"
-msgstr ""
-
 msgid "entity types which may use this workflow"
 msgstr ""
 
@@ -2566,9 +2553,6 @@
 msgid "groups grant permissions to the user"
 msgstr ""
 
-msgid "groups to which the permission is granted"
-msgstr ""
-
 msgid "guests"
 msgstr ""
 
@@ -2753,9 +2737,6 @@
 msgid "instance home"
 msgstr ""
 
-msgid "instance schema"
-msgstr ""
-
 msgid "internal entity uri"
 msgstr ""
 
@@ -2817,13 +2798,6 @@
 msgid "june"
 msgstr ""
 
-msgid "label"
-msgstr ""
-
-msgctxt "CWPermission"
-msgid "label"
-msgstr "label"
-
 msgid "language of the user interface"
 msgstr ""
 
@@ -2866,11 +2840,6 @@
 msgstr ""
 
 msgid ""
-"link a permission to the entity. This permission should be used in the "
-"security definition of the entity's type to be useful."
-msgstr ""
-
-msgid ""
 "link a property to the user which want this property customization. Unless "
 "you're a site manager, this relation will be handled automatically."
 msgstr ""
@@ -2950,9 +2919,6 @@
 msgid "manage permissions"
 msgstr ""
 
-msgid "manage security"
-msgstr ""
-
 msgid "managers"
 msgstr ""
 
@@ -3044,10 +3010,6 @@
 msgid "name"
 msgstr "name"
 
-msgctxt "CWPermission"
-msgid "name"
-msgstr "name"
-
 msgctxt "CWRType"
 msgid "name"
 msgstr "name"
@@ -3083,9 +3045,6 @@
 msgid "name of the source"
 msgstr ""
 
-msgid "name or identifier of the permission"
-msgstr ""
-
 msgid "navbottom"
 msgstr "page bottom"
 
@@ -3122,9 +3081,6 @@
 msgid "no"
 msgstr ""
 
-msgid "no associated permissions"
-msgstr ""
-
 msgid "no content next link"
 msgstr ""
 
@@ -3238,9 +3194,6 @@
 msgid "owners"
 msgstr ""
 
-msgid "ownership"
-msgstr ""
-
 msgid "ownerships have been changed"
 msgstr ""
 
@@ -3277,9 +3230,6 @@
 msgid "permissions"
 msgstr ""
 
-msgid "permissions for this entity"
-msgstr ""
-
 msgid "pick existing bookmarks"
 msgstr ""
 
@@ -3477,10 +3427,6 @@
 msgid "require_group"
 msgstr "require group"
 
-msgctxt "CWPermission"
-msgid "require_group"
-msgstr "require group"
-
 msgctxt "Transition"
 msgid "require_group"
 msgstr "require group"
@@ -3496,12 +3442,6 @@
 msgid "require_group_object"
 msgstr "required by"
 
-msgid "require_permission"
-msgstr "require permission"
-
-msgid "require_permission_object"
-msgstr "required by"
-
 msgid "required"
 msgstr ""
 
@@ -3554,9 +3494,6 @@
 msgid "saturday"
 msgstr ""
 
-msgid "schema's permissions definitions"
-msgstr ""
-
 msgid "schema-diagram"
 msgstr "diagram"
 
@@ -3666,9 +3603,6 @@
 msgid "site-wide property can't be set for user"
 msgstr ""
 
-msgid "siteinfo"
-msgstr "site information"
-
 msgid "some later transaction(s) touch entity, undo them first"
 msgstr ""
 
@@ -4176,9 +4110,6 @@
 msgid "url"
 msgstr "url"
 
-msgid "use template languages"
-msgstr ""
-
 msgid ""
 "use to define a transition from one or multiple states to a destination "
 "states in workflow's definitions. Transition without destination state will "
@@ -4199,9 +4130,6 @@
 msgid "use_email_object"
 msgstr "used by"
 
-msgid "use_template_format"
-msgstr "use template format"
-
 msgid ""
 "used for cubicweb configuration. Once a property has been created you can't "
 "change the key."
@@ -4211,9 +4139,6 @@
 "used to associate simple states to an entity type and/or to define workflows"
 msgstr ""
 
-msgid "used to grant a permission to a group"
-msgstr ""
-
 msgid "user"
 msgstr ""
 
@@ -4238,9 +4163,6 @@
 msgid "users and groups"
 msgstr ""
 
-msgid "users and groups management"
-msgstr ""
-
 msgid "users using this bookmark"
 msgstr ""
 
--- a/i18n/es.po	Fri Oct 14 09:04:39 2011 +0200
+++ b/i18n/es.po	Fri Oct 14 09:21:45 2011 +0200
@@ -345,12 +345,6 @@
 msgid "CWGroup_plural"
 msgstr "Grupos"
 
-msgid "CWPermission"
-msgstr "Autorización"
-
-msgid "CWPermission_plural"
-msgstr "Autorizaciones"
-
 msgid "CWProperty"
 msgstr "Propiedad"
 
@@ -552,6 +546,9 @@
 msgid "Manage"
 msgstr "Administración"
 
+msgid "Manage security"
+msgstr "Gestión de seguridad"
+
 msgid "Most referenced classes"
 msgstr "Clases más referenciadas"
 
@@ -579,9 +576,6 @@
 msgid "New CWGroup"
 msgstr "Nuevo grupo"
 
-msgid "New CWPermission"
-msgstr "Agregar autorización"
-
 msgid "New CWProperty"
 msgstr "Agregar Propiedad"
 
@@ -646,6 +640,9 @@
 msgid "OR"
 msgstr "O"
 
+msgid "Ownership"
+msgstr "Propiedad"
+
 msgid "Parent class:"
 msgstr "Clase padre:"
 
@@ -695,8 +692,8 @@
 msgid "Schema %s"
 msgstr "Esquema %s"
 
-msgid "Schema of the data model"
-msgstr "Esquema del modelo de datos"
+msgid "Schema's permissions definitions"
+msgstr "Definiciones de permisos del esquema"
 
 msgid "Search for"
 msgstr "Buscar"
@@ -799,9 +796,6 @@
 msgid "This CWGroup"
 msgstr "Este grupo"
 
-msgid "This CWPermission"
-msgstr "Este permiso"
-
 msgid "This CWProperty"
 msgstr "Esta propiedad"
 
@@ -888,6 +882,9 @@
 msgid "Used by:"
 msgstr "Utilizado por :"
 
+msgid "Users and groups management"
+msgstr "Usuarios y grupos de administradores"
+
 msgid "Web server"
 msgstr "Servidor web"
 
@@ -953,7 +950,7 @@
 msgid ""
 "a RQL expression which should return some results, else the transition won't "
 "be available. This query may use X and U variables that will respectivly "
-"represents the current entity and the current user"
+"represents the current entity and the current user."
 msgstr ""
 "una expresión RQL que debe haber enviado resultados, para que la transición "
 "pueda ser realizada. Esta expresión puede utilizar las variables X y U que "
@@ -1101,9 +1098,6 @@
 msgid "add a EmailAddress"
 msgstr "Agregar correo electrónico"
 
-msgid "add a new permission"
-msgstr "Agregar una autorización"
-
 # subject and object forms for each relation type
 # (no object form for final relation types)
 msgid "add_permission"
@@ -1902,6 +1896,12 @@
 msgid "custom_workflow_object"
 msgstr "Workflow de"
 
+msgid "cw.groups-management"
+msgstr ""
+
+msgid "cw.users-management"
+msgstr ""
+
 msgid "cw_for_source"
 msgstr "fuente"
 
@@ -2116,9 +2116,6 @@
 msgid "delete this bookmark"
 msgstr "Eliminar este favorito"
 
-msgid "delete this permission"
-msgstr "Eliminar esta autorización"
-
 msgid "delete this relation"
 msgstr "Eliminar esta relación"
 
@@ -2295,13 +2292,6 @@
 msgid "display the facet or not"
 msgstr "Mostrar o no la faceta"
 
-msgid ""
-"distinct label to distinguate between other permission entity of the same "
-"name"
-msgstr ""
-"Etiqueta que permite distinguir esta autorización de otras que posean el "
-"mismo nombre"
-
 msgid "download"
 msgstr "Descargar"
 
@@ -2374,13 +2364,6 @@
 msgid "entity type"
 msgstr "Tipo de entidad"
 
-msgid ""
-"entity type that may be used to construct some advanced security "
-"configuration"
-msgstr ""
-"Tipo de entidad utilizada para definir una configuración de seguridad "
-"avanzada"
-
 msgid "entity types which may use this workflow"
 msgstr "Tipos de entidades que pueden utilizar este Workflow"
 
@@ -2673,9 +2656,6 @@
 msgid "groups grant permissions to the user"
 msgstr "Los grupos otorgan los permisos al usuario"
 
-msgid "groups to which the permission is granted"
-msgstr "Grupos quienes tienen otorgada esta autorización"
-
 msgid "guests"
 msgstr "Invitados"
 
@@ -2872,9 +2852,6 @@
 msgid "instance home"
 msgstr "Repertorio de la Instancia"
 
-msgid "instance schema"
-msgstr "Esquema de la Instancia"
-
 msgid "internal entity uri"
 msgstr "Uri Interna"
 
@@ -2940,13 +2917,6 @@
 msgid "june"
 msgstr "Junio"
 
-msgid "label"
-msgstr "Etiqueta"
-
-msgctxt "CWPermission"
-msgid "label"
-msgstr "Etiqueta"
-
 msgid "language of the user interface"
 msgstr "Idioma que se utilizará por defecto en la interfaz usuario"
 
@@ -2989,13 +2959,6 @@
 msgstr "izquierda"
 
 msgid ""
-"link a permission to the entity. This permission should be used in the "
-"security definition of the entity's type to be useful."
-msgstr ""
-"Relacionar un permiso con la entidad. Este permiso debe ser integrado en la "
-"definición de seguridad de la entidad para poder ser utilizado."
-
-msgid ""
 "link a property to the user which want this property customization. Unless "
 "you're a site manager, this relation will be handled automatically."
 msgstr ""
@@ -3078,9 +3041,6 @@
 msgid "manage permissions"
 msgstr "Gestión de permisos"
 
-msgid "manage security"
-msgstr "Gestión de seguridad"
-
 msgid "managers"
 msgstr "Administradores"
 
@@ -3172,10 +3132,6 @@
 msgid "name"
 msgstr "Nombre"
 
-msgctxt "CWPermission"
-msgid "name"
-msgstr "Nombre"
-
 msgctxt "CWRType"
 msgid "name"
 msgstr "Nombre"
@@ -3213,9 +3169,6 @@
 msgid "name of the source"
 msgstr "nombre de la fuente"
 
-msgid "name or identifier of the permission"
-msgstr "Nombre o identificador del permiso"
-
 msgid "navbottom"
 msgstr "Pie de página"
 
@@ -3252,9 +3205,6 @@
 msgid "no"
 msgstr "No"
 
-msgid "no associated permissions"
-msgstr "No existe permiso asociado"
-
 msgid "no content next link"
 msgstr ""
 
@@ -3368,9 +3318,6 @@
 msgid "owners"
 msgstr "Proprietarios"
 
-msgid "ownership"
-msgstr "Propiedad"
-
 msgid "ownerships have been changed"
 msgstr "Derechos de propiedad modificados"
 
@@ -3408,9 +3355,6 @@
 msgid "permissions"
 msgstr "Permisos"
 
-msgid "permissions for this entity"
-msgstr "Permisos para esta entidad"
-
 msgid "pick existing bookmarks"
 msgstr "Seleccionar favoritos existentes"
 
@@ -3616,10 +3560,6 @@
 msgid "require_group"
 msgstr "Restringida al Grupo"
 
-msgctxt "CWPermission"
-msgid "require_group"
-msgstr "Restringida al Grupo"
-
 msgctxt "Transition"
 msgid "require_group"
 msgstr "Restringida al Grupo"
@@ -3635,12 +3575,6 @@
 msgid "require_group_object"
 msgstr "Posee derechos sobre"
 
-msgid "require_permission"
-msgstr "Requiere Permisos"
-
-msgid "require_permission_object"
-msgstr "Requerido por autorización"
-
 msgid "required"
 msgstr "Requerido"
 
@@ -3697,9 +3631,6 @@
 msgid "saturday"
 msgstr "Sábado"
 
-msgid "schema's permissions definitions"
-msgstr "Definiciones de permisos del esquema"
-
 msgid "schema-diagram"
 msgstr "Gráfica"
 
@@ -3813,9 +3744,6 @@
 msgid "site-wide property can't be set for user"
 msgstr "Una propiedad específica al Sistema no puede ser propia al usuario"
 
-msgid "siteinfo"
-msgstr "información"
-
 msgid "some later transaction(s) touch entity, undo them first"
 msgstr ""
 "Las transacciones más recientes modificaron esta entidad, anúlelas primero"
@@ -4331,9 +4259,6 @@
 msgid "url"
 msgstr "url"
 
-msgid "use template languages"
-msgstr "Utilizar plantillas de lenguaje"
-
 msgid ""
 "use to define a transition from one or multiple states to a destination "
 "states in workflow's definitions. Transition without destination state will "
@@ -4357,9 +4282,6 @@
 msgid "use_email_object"
 msgstr "Utilizado por"
 
-msgid "use_template_format"
-msgstr "Utilización del formato 'cubicweb template'"
-
 msgid ""
 "used for cubicweb configuration. Once a property has been created you can't "
 "change the key."
@@ -4373,9 +4295,6 @@
 "Se utiliza para asociar estados simples a un tipo de entidad y/o para "
 "definir Workflows"
 
-msgid "used to grant a permission to a group"
-msgstr "Se utiliza para otorgar permisos a un grupo"
-
 msgid "user"
 msgstr "Usuario"
 
@@ -4402,9 +4321,6 @@
 msgid "users and groups"
 msgstr "usuarios y grupos"
 
-msgid "users and groups management"
-msgstr "usuarios y grupos de administradores"
-
 msgid "users using this bookmark"
 msgstr "Usuarios utilizando este Favorito"
 
@@ -4595,3 +4511,15 @@
 msgstr ""
 "usted debe  quitar la puesta en línea de la relación %s que es aceptada y "
 "puede ser cruzada"
+
+#~ msgid "Schema of the data model"
+#~ msgstr "Esquema del modelo de datos"
+
+#~ msgid "add a CWSourceSchemaConfig"
+#~ msgstr "agregar una parte de mapeo"
+
+#~ msgid "instance schema"
+#~ msgstr "Esquema de la Instancia"
+
+#~ msgid "siteinfo"
+#~ msgstr "información"
--- a/i18n/fr.po	Fri Oct 14 09:04:39 2011 +0200
+++ b/i18n/fr.po	Fri Oct 14 09:21:45 2011 +0200
@@ -345,12 +345,6 @@
 msgid "CWGroup_plural"
 msgstr "Groupes"
 
-msgid "CWPermission"
-msgstr "Permission"
-
-msgid "CWPermission_plural"
-msgstr "Permissions"
-
 msgid "CWProperty"
 msgstr "Propriété"
 
@@ -552,6 +546,9 @@
 msgid "Manage"
 msgstr "Administration"
 
+msgid "Manage security"
+msgstr "Gestion de la sécurité"
+
 msgid "Most referenced classes"
 msgstr "Classes les plus référencées"
 
@@ -579,9 +576,6 @@
 msgid "New CWGroup"
 msgstr "Nouveau groupe"
 
-msgid "New CWPermission"
-msgstr "Nouvelle permission"
-
 msgid "New CWProperty"
 msgstr "Nouvelle propriété"
 
@@ -646,6 +640,9 @@
 msgid "OR"
 msgstr "OU"
 
+msgid "Ownership"
+msgstr "Propriété"
+
 msgid "Parent class:"
 msgstr "Classe parente"
 
@@ -695,8 +692,8 @@
 msgid "Schema %s"
 msgstr "Schéma %s"
 
-msgid "Schema of the data model"
-msgstr "Schéma du modèle de données"
+msgid "Schema's permissions definitions"
+msgstr "Permissions définies dans le schéma"
 
 msgid "Search for"
 msgstr "Rechercher"
@@ -799,9 +796,6 @@
 msgid "This CWGroup"
 msgstr "Ce groupe"
 
-msgid "This CWPermission"
-msgstr "Cette permission"
-
 msgid "This CWProperty"
 msgstr "Cette propriété"
 
@@ -888,6 +882,9 @@
 msgid "Used by:"
 msgstr "Utilisé par :"
 
+msgid "Users and groups management"
+msgstr "Gestion des utilisateurs et groupes"
+
 msgid "Web server"
 msgstr "Serveur web"
 
@@ -952,7 +949,7 @@
 msgid ""
 "a RQL expression which should return some results, else the transition won't "
 "be available. This query may use X and U variables that will respectivly "
-"represents the current entity and the current user"
+"represents the current entity and the current user."
 msgstr ""
 "une expression RQL devant retourner des résultats pour que la transition "
 "puisse être passée. Cette expression peut utiliser les variables X et U qui "
@@ -1101,9 +1098,6 @@
 msgid "add a EmailAddress"
 msgstr "ajouter une adresse électronique"
 
-msgid "add a new permission"
-msgstr "ajouter une permission"
-
 # subject and object forms for each relation type
 # (no object form for final relation types)
 msgid "add_permission"
@@ -1908,6 +1902,12 @@
 msgid "custom_workflow_object"
 msgstr "workflow de"
 
+msgid "cw.groups-management"
+msgstr "groupes"
+
+msgid "cw.users-management"
+msgstr "utilisateurs"
+
 msgid "cw_for_source"
 msgstr "source"
 
@@ -2118,9 +2118,6 @@
 msgid "delete this bookmark"
 msgstr "supprimer ce signet"
 
-msgid "delete this permission"
-msgstr "supprimer cette permission"
-
 msgid "delete this relation"
 msgstr "supprimer cette relation"
 
@@ -2297,13 +2294,6 @@
 msgid "display the facet or not"
 msgstr "afficher la facette ou non"
 
-msgid ""
-"distinct label to distinguate between other permission entity of the same "
-"name"
-msgstr ""
-"libellé permettant de distinguer cette permission des autres ayant le même "
-"nom"
-
 msgid "download"
 msgstr "télécharger"
 
@@ -2376,12 +2366,6 @@
 msgid "entity type"
 msgstr "type d'entité"
 
-msgid ""
-"entity type that may be used to construct some advanced security "
-"configuration"
-msgstr ""
-"type d'entité à utiliser pour définir une configuration de sécurité avancée"
-
 msgid "entity types which may use this workflow"
 msgstr "types d'entité pouvant utiliser ce workflow"
 
@@ -2675,9 +2659,6 @@
 msgid "groups grant permissions to the user"
 msgstr "les groupes donnent des permissions à l'utilisateur"
 
-msgid "groups to which the permission is granted"
-msgstr "groupes auquels cette permission est donnée"
-
 msgid "guests"
 msgstr "invités"
 
@@ -2873,9 +2854,6 @@
 msgid "instance home"
 msgstr "répertoire de l'instance"
 
-msgid "instance schema"
-msgstr "schéma de l'instance"
-
 msgid "internal entity uri"
 msgstr "uri interne"
 
@@ -2942,13 +2920,6 @@
 msgid "june"
 msgstr "juin"
 
-msgid "label"
-msgstr "libellé"
-
-msgctxt "CWPermission"
-msgid "label"
-msgstr "libellé"
-
 msgid "language of the user interface"
 msgstr "langue pour l'interface utilisateur"
 
@@ -2991,13 +2962,6 @@
 msgstr "gauche"
 
 msgid ""
-"link a permission to the entity. This permission should be used in the "
-"security definition of the entity's type to be useful."
-msgstr ""
-"lie une permission à une entité. Cette permission doit généralement être "
-"utilisée dans la définition de sécurité du type d'entité pour être utile."
-
-msgid ""
 "link a property to the user which want this property customization. Unless "
 "you're a site manager, this relation will be handled automatically."
 msgstr ""
@@ -3080,9 +3044,6 @@
 msgid "manage permissions"
 msgstr "gestion des permissions"
 
-msgid "manage security"
-msgstr "gestion de la sécurité"
-
 msgid "managers"
 msgstr "administrateurs"
 
@@ -3174,10 +3135,6 @@
 msgid "name"
 msgstr "nom"
 
-msgctxt "CWPermission"
-msgid "name"
-msgstr "nom"
-
 msgctxt "CWRType"
 msgid "name"
 msgstr "nom"
@@ -3215,9 +3172,6 @@
 msgid "name of the source"
 msgstr "nom de la source"
 
-msgid "name or identifier of the permission"
-msgstr "nom (identifiant) de la permission"
-
 msgid "navbottom"
 msgstr "bas de page"
 
@@ -3254,9 +3208,6 @@
 msgid "no"
 msgstr "non"
 
-msgid "no associated permissions"
-msgstr "aucune permission associée"
-
 msgid "no content next link"
 msgstr "pas de lien 'suivant'"
 
@@ -3370,9 +3321,6 @@
 msgid "owners"
 msgstr "propriétaires"
 
-msgid "ownership"
-msgstr "propriété"
-
 msgid "ownerships have been changed"
 msgstr "les droits de propriété ont été modifiés"
 
@@ -3412,9 +3360,6 @@
 msgid "permissions"
 msgstr "permissions"
 
-msgid "permissions for this entity"
-msgstr "permissions pour cette entité"
-
 msgid "pick existing bookmarks"
 msgstr "récupérer des signets existants"
 
@@ -3619,10 +3564,6 @@
 msgid "require_group"
 msgstr "restreinte au groupe"
 
-msgctxt "CWPermission"
-msgid "require_group"
-msgstr "restreinte au groupe"
-
 msgctxt "Transition"
 msgid "require_group"
 msgstr "restreinte au groupe"
@@ -3638,12 +3579,6 @@
 msgid "require_group_object"
 msgstr "a les droits"
 
-msgid "require_permission"
-msgstr "require permission"
-
-msgid "require_permission_object"
-msgstr "permission of"
-
 msgid "required"
 msgstr "requis"
 
@@ -3702,9 +3637,6 @@
 msgid "saturday"
 msgstr "samedi"
 
-msgid "schema's permissions definitions"
-msgstr "permissions définies dans le schéma"
-
 msgid "schema-diagram"
 msgstr "diagramme"
 
@@ -3817,9 +3749,6 @@
 msgid "site-wide property can't be set for user"
 msgstr "une propriété spécifique au site ne peut être propre à un utilisateur"
 
-msgid "siteinfo"
-msgstr "informations"
-
 msgid "some later transaction(s) touch entity, undo them first"
 msgstr ""
 "des transactions plus récentes modifient cette entité, annulez les d'abord"
@@ -4337,9 +4266,6 @@
 msgid "url"
 msgstr "url"
 
-msgid "use template languages"
-msgstr "utiliser les langages de template"
-
 msgid ""
 "use to define a transition from one or multiple states to a destination "
 "states in workflow's definitions. Transition without destination state will "
@@ -4363,9 +4289,6 @@
 msgid "use_email_object"
 msgstr "utilisée par"
 
-msgid "use_template_format"
-msgstr "utilisation du format 'cubicweb template'"
-
 msgid ""
 "used for cubicweb configuration. Once a property has been created you can't "
 "change the key."
@@ -4377,9 +4300,6 @@
 "used to associate simple states to an entity type and/or to define workflows"
 msgstr "associe les états à un type d'entité pour définir un workflow"
 
-msgid "used to grant a permission to a group"
-msgstr "utiliser pour donner une permission à un groupe"
-
 msgid "user"
 msgstr "utilisateur"
 
@@ -4406,9 +4326,6 @@
 msgid "users and groups"
 msgstr "utilisateurs et groupes"
 
-msgid "users and groups management"
-msgstr "gestion des utilisateurs et groupes"
-
 msgid "users using this bookmark"
 msgstr "utilisateurs utilisant ce signet"
 
--- a/misc/cwdesklets/rqlsensor/__init__.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/misc/cwdesklets/rqlsensor/__init__.py	Fri Oct 14 09:21:45 2011 +0200
@@ -56,8 +56,6 @@
     def call_action(self, action, path, args=[]):
         index = path[-1]
         output = self._new_output()
-#        import sys
-#        print >>sys.stderr, action, path, args
         if action=="enter-line":
             # change background
             output.set('resultbg[%s]' % index, 'yellow')
--- a/misc/migration/bootstrapmigration_repository.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/misc/migration/bootstrapmigration_repository.py	Fri Oct 14 09:21:45 2011 +0200
@@ -41,6 +41,15 @@
         'FROM cw_CWSource, cw_source_relation '
         'WHERE entities.eid=cw_source_relation.eid_from AND cw_source_relation.eid_to=cw_CWSource.cw_eid')
 
+if applcubicwebversion <= (3, 14, 0) and cubicwebversion >= (3, 14, 0):
+    if 'require_permission' in schema and not 'localperms'in repo.config.cubes():
+        from cubicweb import ExecutionError
+        try:
+            add_cube('localperms', update_database=False)
+        except ImportError:
+            raise ExecutionError('In cubicweb 3.14, CWPermission and related stuff '
+                                 'has been moved to cube localperms. Install it first.')
+
 if applcubicwebversion == (3, 6, 0) and cubicwebversion >= (3, 6, 0):
     CSTRMAP = dict(rql('Any T, X WHERE X is CWConstraintType, X name T',
                        ask_confirm=False))
--- a/misc/migration/postcreate.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/misc/migration/postcreate.py	Fri Oct 14 09:21:45 2011 +0200
@@ -1,4 +1,4 @@
-# copyright 2003-2010 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
+# copyright 2003-2011 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
 # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
 #
 # This file is part of CubicWeb.
@@ -69,10 +69,3 @@
             if value != default:
                 rql('INSERT CWProperty X: X pkey %(k)s, X value %(v)s',
                     {'k': key, 'v': value})
-
-# add PERM_USE_TEMPLATE_FORMAT permission
-from cubicweb.schema import PERM_USE_TEMPLATE_FORMAT
-usetmplperm = create_entity('CWPermission', name=PERM_USE_TEMPLATE_FORMAT,
-                            label=_('use template languages'))
-rql('SET X require_group G WHERE G name "managers", X eid %(x)s',
-    {'x': usetmplperm.eid})
--- a/req.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/req.py	Fri Oct 14 09:21:45 2011 +0200
@@ -29,7 +29,7 @@
 from logilab.common.deprecation import deprecated
 from logilab.common.date import ustrftime, strptime, todate, todatetime
 
-from cubicweb import Unauthorized, NoSelectableObject, typed_eid
+from cubicweb import Unauthorized, NoSelectableObject, typed_eid, uilib
 from cubicweb.rset import ResultSet
 
 ONESECOND = timedelta(0, 1, 0)
@@ -343,6 +343,18 @@
                                                  rset=rset, **initargs)
         return view.render(w=w, **kwargs)
 
+    def printable_value(self, attrtype, value, props=None, displaytime=True,
+                        formatters=uilib.PRINTERS):
+        """return a displayablye value (i.e. unicode string)"""
+        if value is None:
+            return u''
+        try:
+            as_string = formatters[attrtype]
+        except KeyError:
+            self.error('given bad attrtype %s', attrtype)
+            return unicode(value)
+        return as_string(value, self, props, displaytime)
+
     def format_date(self, date, date_format=None, time=False):
         """return a string for a date time according to instance's
         configuration
--- a/schema.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/schema.py	Fri Oct 14 09:21:45 2011 +0200
@@ -59,12 +59,11 @@
                            'from_state', 'to_state', 'condition',
                            'subworkflow', 'subworkflow_state', 'subworkflow_exit',
                            ))
-SYSTEM_RTYPES = set(('in_group', 'require_group', 'require_permission',
+SYSTEM_RTYPES = set(('in_group', 'require_group',
                      # cwproperty
                      'for_user',
                      )) | WORKFLOW_RTYPES
 NO_I18NCONTEXT = META_RTYPES | WORKFLOW_RTYPES
-NO_I18NCONTEXT.add('require_permission')
 
 SKIP_COMPOSITE_RELS = [('cw_source', 'subject')]
 
@@ -85,7 +84,7 @@
                       'WorkflowTransition', 'BaseTransition',
                       'SubWorkflowExitPoint'))
 
-INTERNAL_TYPES = set(('CWProperty', 'CWPermission', 'CWCache', 'ExternalUri',
+INTERNAL_TYPES = set(('CWProperty', 'CWCache', 'ExternalUri',
                       'CWSource', 'CWSourceHostConfig', 'CWSourceSchemaConfig'))
 
 
@@ -171,11 +170,10 @@
     if form:
         key = key + '_' + form
     # ensure unicode
-    # .lower() in case no translation are available XXX done whatever a translation is there or not!
     if context is not None:
-        return unicode(req.pgettext(context, key)).lower()
+        return unicode(req.pgettext(context, key))
     else:
-        return unicode(req._(key)).lower()
+        return unicode(req._(key))
 
 __builtins__['display_name'] = deprecated('[3.4] display_name should be imported from cubicweb.schema')(display_name)
 
@@ -1176,7 +1174,7 @@
 
 # _() is just there to add messages to the catalog, don't care about actual
 # translation
-PERM_USE_TEMPLATE_FORMAT = _('use_template_format')
+MAY_USE_TEMPLATE_FORMAT = set(('managers',))
 NEED_PERM_FORMATS = [_('text/cubicweb-page-template')]
 
 @monkeypatch(FormatConstraint)
@@ -1191,9 +1189,9 @@
             # cw is a server session
             hasperm = not cw.write_security or \
                       not cw.is_hook_category_activated('integrity') or \
-                      cw.user.has_permission(PERM_USE_TEMPLATE_FORMAT)
+                      cw.user.matching_groups(MAY_USE_TEMPLATE_FORMAT)
         else:
-            hasperm = cw.user.has_permission(PERM_USE_TEMPLATE_FORMAT)
+            hasperm = cw.user.matching_groups(MAY_USE_TEMPLATE_FORMAT)
         if hasperm:
             return self.regular_formats + tuple(NEED_PERM_FORMATS)
     return self.regular_formats
--- a/schemas/__init__.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/schemas/__init__.py	Fri Oct 14 09:21:45 2011 +0200
@@ -1,4 +1,4 @@
-# copyright 2003-2010 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
+# copyright 2003-2011 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
 # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
 #
 # This file is part of CubicWeb.
@@ -15,12 +15,10 @@
 #
 # You should have received a copy of the GNU Lesser General Public License along
 # with CubicWeb.  If not, see <http://www.gnu.org/licenses/>.
-"""some utilities to define schema permissions
+"""some constants and classes to define schema permissions"""
 
-"""
 __docformat__ = "restructuredtext en"
 
-from rql.utils import quote
 from cubicweb.schema import RO_REL_PERMS, RO_ATTR_PERMS, \
      PUB_SYSTEM_ENTITY_PERMS, PUB_SYSTEM_REL_PERMS, \
      ERQLExpression, RRQLExpression
@@ -35,59 +33,19 @@
 # execute, readable by anyone
 HOOKS_RTYPE_PERMS = RO_REL_PERMS # XXX deprecates
 
-def _perm(names):
-    if isinstance(names, (list, tuple)):
-        if len(names) == 1:
-            names = quote(names[0])
-        else:
-            names = 'IN (%s)' % (','.join(quote(name) for name in names))
-    else:
-        names = quote(names)
-    #return u' require_permission P, P name %s, U in_group G, P require_group G' % names
-    return u' require_permission P, P name %s, U has_group_permission P' % names
 
-
-def xperm(*names):
-    return 'X' + _perm(names)
-
-def xexpr(*names):
-    return ERQLExpression(xperm(*names))
-
-def xrexpr(relation, *names):
-    return ERQLExpression('X %s Y, Y %s' % (relation, _perm(names)))
-
-def xorexpr(relation, etype, *names):
-    return ERQLExpression('Y %s X, X is %s, Y %s' % (relation, etype, _perm(names)))
-
-
-def sexpr(*names):
-    return RRQLExpression('S' + _perm(names), 'S')
+from logilab.common.modutils import LazyObject
+from logilab.common.deprecation import deprecated
+class MyLazyObject(LazyObject):
 
-def restricted_sexpr(restriction, *names):
-    rql = '%s, %s' % (restriction, 'S' + _perm(names))
-    return RRQLExpression(rql, 'S')
-
-def restricted_oexpr(restriction, *names):
-    rql = '%s, %s' % (restriction, 'O' + _perm(names))
-    return RRQLExpression(rql, 'O')
-
-def oexpr(*names):
-    return RRQLExpression('O' + _perm(names), 'O')
-
+    def _getobj(self):
+        try:
+            return super(MyLazyObject, self)._getobj()
+        except ImportError:
+            raise ImportError('In cubicweb 3.14, function %s has been moved to '
+                              'cube localperms. Install it first.' % self.obj)
 
-# def supdate_perm():
-#     return RRQLExpression('U has_update_permission S', 'S')
-
-# def oupdate_perm():
-#     return RRQLExpression('U has_update_permission O', 'O')
-
-def relxperm(rel, role, *names):
-    assert role in ('subject', 'object')
-    if role == 'subject':
-        zxrel = ', X %s Z' % rel
-    else:
-        zxrel = ', Z %s X' % rel
-    return 'Z' + _perm(names) + zxrel
-
-def relxexpr(rel, role, *names):
-    return ERQLExpression(relxperm(rel, role, *names))
+for name in ('xperm', 'xexpr', 'xrexpr', 'xorexpr', 'sexpr', 'restricted_sexpr',
+             'restricted_oexpr', 'oexpr', 'relxperm', 'relxexpr', '_perm'):
+    msg = '[3.14] import %s from cubes.localperms' % name
+    globals()[name] = deprecated(msg, name=name, doc='deprecated')(MyLazyObject('cubes.localperms', name))
--- a/schemas/base.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/schemas/base.py	Fri Oct 14 09:21:45 2011 +0200
@@ -181,31 +181,6 @@
     cardinality = '?*'
 
 
-class CWPermission(EntityType):
-    """entity type that may be used to construct some advanced security configuration
-    """
-    __permissions__ = PUB_SYSTEM_ENTITY_PERMS
-
-    name = String(required=True, indexed=True, internationalizable=True, maxsize=100,
-                  description=_('name or identifier of the permission'))
-    label = String(required=True, internationalizable=True, maxsize=100,
-                   description=_('distinct label to distinguate between other '
-                                 'permission entity of the same name'))
-    require_group = SubjectRelation('CWGroup',
-                                    description=_('groups to which the permission is granted'))
-
-# explicitly add X require_permission CWPermission for each entity that should have
-# configurable security
-class require_permission(RelationType):
-    """link a permission to the entity. This permission should be used in the
-    security definition of the entity's type to be useful.
-    """
-    __permissions__ = PUB_SYSTEM_REL_PERMS
-
-class require_group(RelationType):
-    """used to grant a permission to a group"""
-    __permissions__ = PUB_SYSTEM_REL_PERMS
-
 
 class ExternalUri(EntityType):
     """a URI representing an object in external data store"""
@@ -382,3 +357,5 @@
         'add':    ('managers', RRQLExpression('U has_update_permission S'),),
         'delete': ('managers', RRQLExpression('U has_update_permission S'),),
         }
+
+
--- a/schemas/workflow.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/schemas/workflow.py	Fri Oct 14 09:21:45 2011 +0200
@@ -1,4 +1,4 @@
-# copyright 2003-2010 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
+# copyright 2003-2011 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
 # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
 #
 # This file is part of CubicWeb.
@@ -21,14 +21,15 @@
 __docformat__ = "restructuredtext en"
 _ = unicode
 
-from yams.buildobjs import (EntityType, RelationType, SubjectRelation,
+from yams.buildobjs import (EntityType, RelationType, RelationDefinition,
+                            SubjectRelation,
                             RichString, String, Int)
 from cubicweb.schema import RQLConstraint, RQLUniqueConstraint
-from cubicweb.schemas import (META_ETYPE_PERMS, META_RTYPE_PERMS,
-                              HOOKS_RTYPE_PERMS)
+from cubicweb.schemas import (PUB_SYSTEM_ENTITY_PERMS, PUB_SYSTEM_REL_PERMS,
+                              RO_REL_PERMS)
 
 class Workflow(EntityType):
-    __permissions__ = META_ETYPE_PERMS
+    __permissions__ = PUB_SYSTEM_ENTITY_PERMS
 
     name = String(required=True, indexed=True, internationalizable=True,
                   maxsize=256)
@@ -47,7 +48,7 @@
 
 class default_workflow(RelationType):
     """default workflow for an entity type"""
-    __permissions__ = META_RTYPE_PERMS
+    __permissions__ = PUB_SYSTEM_REL_PERMS
 
     subject = 'CWEType'
     object = 'Workflow'
@@ -60,7 +61,7 @@
     """used to associate simple states to an entity type and/or to define
     workflows
     """
-    __permissions__ = META_ETYPE_PERMS
+    __permissions__ = PUB_SYSTEM_ENTITY_PERMS
 
     name = String(required=True, indexed=True, internationalizable=True,
                   maxsize=256,
@@ -83,7 +84,7 @@
 
 class BaseTransition(EntityType):
     """abstract base class for transitions"""
-    __permissions__ = META_ETYPE_PERMS
+    __permissions__ = PUB_SYSTEM_ENTITY_PERMS
 
     name = String(required=True, indexed=True, internationalizable=True,
                   maxsize=256,
@@ -91,22 +92,34 @@
                                                    _('workflow already have a transition of that name'))])
     type = String(vocabulary=(_('normal'), _('auto')), default='normal')
     description = RichString(description=_('semantic description of this transition'))
-    condition = SubjectRelation('RQLExpression', cardinality='*?', composite='subject',
-                                description=_('a RQL expression which should return some results, '
-                                              'else the transition won\'t be available. '
-                                              'This query may use X and U variables '
-                                              'that will respectivly represents '
-                                              'the current entity and the current user'))
 
-    require_group = SubjectRelation('CWGroup', cardinality='**',
-                                    description=_('group in which a user should be to be '
-                                                  'allowed to pass this transition'))
     transition_of = SubjectRelation('Workflow', cardinality='1*', composite='object',
                                     description=_('workflow to which this transition belongs'),
                                     constraints=[RQLUniqueConstraint('S name N, Y transition_of O, Y name N', 'Y',
                                                                      _('workflow already have a transition of that name'))])
 
 
+class require_group(RelationDefinition):
+    """group in which a user should be to be allowed to pass this transition"""
+    __permissions__ = PUB_SYSTEM_REL_PERMS
+    subject = 'BaseTransition'
+    object = 'CWGroup'
+
+
+class condition(RelationDefinition):
+    """a RQL expression which should return some results, else the transition
+    won't be available.
+
+    This query may use X and U variables that will respectivly represents the
+    current entity and the current user.
+    """
+    __permissions__ = PUB_SYSTEM_REL_PERMS
+    subject = 'BaseTransition'
+    object = 'RQLExpression'
+    cardinality = '*?'
+    composite = 'subject'
+
+
 class Transition(BaseTransition):
     """use to define a transition from one or multiple states to a destination
     states in workflow's definitions. Transition without destination state will
@@ -177,11 +190,11 @@
     # get actor and date time using owned_by and creation_date
 
 class from_state(RelationType):
-    __permissions__ = HOOKS_RTYPE_PERMS.copy()
+    __permissions__ = RO_REL_PERMS.copy()
     inlined = True
 
 class to_state(RelationType):
-    __permissions__ = HOOKS_RTYPE_PERMS.copy()
+    __permissions__ = RO_REL_PERMS.copy()
     inlined = True
 
 class by_transition(RelationType):
@@ -196,60 +209,52 @@
 
 class workflow_of(RelationType):
     """link a workflow to one or more entity type"""
-    __permissions__ = META_RTYPE_PERMS
+    __permissions__ = PUB_SYSTEM_REL_PERMS
 
 class state_of(RelationType):
     """link a state to one or more workflow"""
-    __permissions__ = META_RTYPE_PERMS
+    __permissions__ = PUB_SYSTEM_REL_PERMS
     inlined = True
 
 class transition_of(RelationType):
     """link a transition to one or more workflow"""
-    __permissions__ = META_RTYPE_PERMS
+    __permissions__ = PUB_SYSTEM_REL_PERMS
     inlined = True
 
 class destination_state(RelationType):
     """destination state of a transition"""
-    __permissions__ = META_RTYPE_PERMS
+    __permissions__ = PUB_SYSTEM_REL_PERMS
     inlined = True
 
 class allowed_transition(RelationType):
     """allowed transitions from this state"""
-    __permissions__ = META_RTYPE_PERMS
+    __permissions__ = PUB_SYSTEM_REL_PERMS
 
 class initial_state(RelationType):
     """indicate which state should be used by default when an entity using
     states is created
     """
-    __permissions__ = META_RTYPE_PERMS
+    __permissions__ = PUB_SYSTEM_REL_PERMS
     inlined = True
 
 
 class subworkflow(RelationType):
-    __permissions__ = META_RTYPE_PERMS
+    __permissions__ = PUB_SYSTEM_REL_PERMS
     inlined = True
 
 class exit_point(RelationType):
-    __permissions__ = META_RTYPE_PERMS
+    __permissions__ = PUB_SYSTEM_REL_PERMS
 
 class subworkflow_state(RelationType):
-    __permissions__ = META_RTYPE_PERMS
+    __permissions__ = PUB_SYSTEM_REL_PERMS
     inlined = True
 
 
-class condition(RelationType):
-    __permissions__ = META_RTYPE_PERMS
-
-# already defined in base.py
-# class require_group(RelationType):
-#     __permissions__ = META_RTYPE_PERMS
-
-
 # "abstract" relations, set by WorkflowableEntityType ##########################
 
 class custom_workflow(RelationType):
     """allow to set a specific workflow for an entity"""
-    __permissions__ = META_RTYPE_PERMS
+    __permissions__ = PUB_SYSTEM_REL_PERMS
 
     cardinality = '?*'
     constraints = [RQLConstraint('S is ET, O workflow_of ET',
@@ -275,7 +280,7 @@
 
 class in_state(RelationType):
     """indicate the current state of an entity"""
-    __permissions__ = HOOKS_RTYPE_PERMS
+    __permissions__ = RO_REL_PERMS
 
     # not inlined intentionnaly since when using ldap sources, user'state
     # has to be stored outside the CWUser table
--- a/server/__init__.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/server/__init__.py	Fri Oct 14 09:21:45 2011 +0200
@@ -148,20 +148,21 @@
     repo = Repository(config, vreg=vreg)
     schema = repo.schema
     sourcescfg = config.sources()
-    _title = '-> creating tables '
-    print _title,
     source = sourcescfg['system']
     driver = source['db-driver']
     sqlcnx = repo.system_source.get_connection()
     sqlcursor = sqlcnx.cursor()
     execute = sqlcursor.execute
     if drop:
+        _title = '-> drop tables '
         dropsql = sqldropschema(schema, driver)
         try:
-            sqlexec(dropsql, execute)
+            sqlexec(dropsql, execute, pbtitle=_title)
         except Exception, ex:
             print '-> drop failed, skipped (%s).' % ex
             sqlcnx.rollback()
+    _title = '-> creating tables '
+    print _title,
     # schema entities and relations tables
     # can't skip entities table even if system source doesn't support them,
     # they are used sometimes by generated sql. Keeping them empty is much
--- a/server/checkintegrity.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/server/checkintegrity.py	Fri Oct 14 09:21:45 2011 +0200
@@ -36,9 +36,8 @@
 
 def notify_fixed(fix):
     if fix:
-        print >> sys.stderr, ' [FIXED]'
-    else:
-        print >> sys.stderr
+        sys.stderr.write(' [FIXED]')
+    sys.stderr.write('\n')
 
 def has_eid(session, sqlcursor, eid, eids):
     """return true if the eid is a valid eid"""
@@ -69,9 +68,9 @@
         eids[eid] = False
         return False
     elif len(result) > 1:
-        msg = '  More than one entity with eid %s exists in source !'
-        print >> sys.stderr, msg % eid
-        print >> sys.stderr, '  WARNING : Unable to fix this, do it yourself !'
+        msg = ('  More than one entity with eid %s exists in source !\n'
+               '  WARNING : Unable to fix this, do it yourself !\n')
+        sys.stderr.write(msg % eid)
     eids[eid] = True
     return True
 
@@ -169,8 +168,8 @@
     for row in cursor.fetchall():
         eid = row[0]
         if not has_eid(session, cursor, eid, eids):
-            msg = '  Entity with eid %s exists in the text index but in no source'
-            print >> sys.stderr, msg % eid,
+            msg = '  Entity with eid %s exists in the text index but in no source\n'
+            sys.stderr.write(msg % eid)
             if fix:
                 session.system_sql('DELETE FROM appears WHERE uid=%s;' % eid)
             notify_fixed(fix)
@@ -183,8 +182,8 @@
     for row in cursor.fetchall():
         eid = row[0]
         if not has_eid(session, cursor, eid, eids):
-            msg = '  Entity with eid %s exists in the system table but in no source'
-            print >> sys.stderr, msg % eid,
+            msg = '  Entity with eid %s exists in the system table but in no source\n'
+            sys.stderr.write(msg % eid)
             if fix:
                 session.system_sql('DELETE FROM entities WHERE eid=%s;' % eid)
             notify_fixed(fix)
@@ -213,7 +212,7 @@
             # no need to call has_eid
             if not eid in eids or not eids[eid]:
                 msg = '  Entity with eid %s exists in the %s table but not in the system table'
-                print >> sys.stderr, msg % (eid, eschema.type),
+                sys.stderr.write(msg % (eid, eschema.type))
                 if fix:
                     session.system_sql('DELETE FROM %s WHERE %s=%s;' % (table, column, eid))
                 notify_fixed(fix)
@@ -221,7 +220,7 @@
 
 def bad_related_msg(rtype, target, eid, fix):
     msg = '  A relation %s with %s eid %s exists but no such entity in sources'
-    print >> sys.stderr, msg % (rtype, target, eid),
+    sys.stderr.write(msg % (rtype, target, eid))
     notify_fixed(fix)
 
 
@@ -294,8 +293,8 @@
                 else:
                     rql = 'Any X WHERE NOT Y %s X, X is %s' % (rschema, etype)
                 for entity in session.execute(rql).entities():
-                    print >> sys.stderr, '%s #%s is missing mandatory %s relation %s' % (
-                        entity.__regid__, entity.eid, role, rschema),
+                    sys.stderr.write('%s #%s is missing mandatory %s relation %s' % (
+                            entity.__regid__, entity.eid, role, rschema))
                     if fix:
                         #if entity.cw_describe()['source']['uri'] == 'system': XXX
                         entity.cw_delete()
@@ -315,8 +314,8 @@
                 rql = 'Any X WHERE X %s NULL, X is %s, X cw_source S, S name "system"' % (
                     rschema, rdef.subject)
                 for entity in session.execute(rql).entities():
-                    print >> sys.stderr, '%s #%s is missing mandatory attribute %s' % (
-                        entity.__regid__, entity.eid, rschema),
+                    sys.stderr.write('%s #%s is missing mandatory attribute %s' % (
+                            entity.__regid__, entity.eid, rschema))
                     if fix:
                         entity.cw_delete()
                     notify_fixed(fix)
@@ -339,7 +338,7 @@
                                         % (eidcolumn, table, column))
             for eid, in cursor.fetchall():
                 msg = '  %s with eid %s has no %s'
-                print >> sys.stderr, msg % (etype, eid, rel),
+                sys.stderr.write(msg % (etype, eid, rel))
                 if fix:
                     session.system_sql("UPDATE %s SET %s=%%(v)s WHERE %s=%s ;"
                                        % (table, column, eidcolumn, eid),
--- a/server/migractions.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/server/migractions.py	Fri Oct 14 09:21:45 2011 +0200
@@ -117,7 +117,15 @@
             # which is called on regular start
             repo.hm.call_hooks('server_maintenance', repo=repo)
         if not schema and not getattr(config, 'quick_start', False):
-            schema = config.load_schema(expand_cubes=True)
+            insert_lperms = self.repo.get_versions()['cubicweb'] < (3, 14, 0) and 'localperms' in config.available_cubes()
+            if insert_lperms:
+                cubes = config._cubes
+                config._cubes += ('localperms',)
+            try:
+                schema = config.load_schema(expand_cubes=True)
+            finally:
+                if insert_lperms:
+                    config._cubes = cubes
         self.fs_schema = schema
         self._synchronized = set()
 
@@ -152,7 +160,7 @@
             return super(ServerMigrationHelper, self).cmd_process_script(
                   migrscript, funcname, *args, **kwargs)
         except ExecutionError, err:
-            print >> sys.stderr, "-> %s" % err
+            sys.stderr.write("-> %s\n" % err)
         except BaseException:
             self.rollback()
             raise
--- a/server/repository.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/server/repository.py	Fri Oct 14 09:21:45 2011 +0200
@@ -60,8 +60,7 @@
      security_enabled
 from cubicweb.server.ssplanner import EditedEntity
 
-NO_CACHE_RELATIONS = set( [('require_permission', 'object'),
-                           ('owned_by', 'object'),
+NO_CACHE_RELATIONS = set( [('owned_by', 'object'),
                            ('created_by', 'object'),
                            ('cw_source', 'object'),
                            ])
@@ -460,8 +459,9 @@
     def _build_user(self, session, eid):
         """return a CWUser entity for user with the given eid"""
         cls = self.vreg['etypes'].etype_class('CWUser')
-        rql = cls.fetch_rql(session.user, ['X eid %(x)s'])
-        rset = session.execute(rql, {'x': eid})
+        st = cls.fetch_rqlst(session.user, ordermethod=None)
+        st.add_eid_restriction(st.get_variable('X'), 'x', 'Substitute')
+        rset = session.execute(st.as_string(), {'x': eid})
         assert len(rset) == 1, rset
         cwuser = rset.get_entity(0, 0)
         # pylint: disable=W0104
@@ -1085,6 +1085,9 @@
             entity = source.before_entity_insertion(
                 session, extid, etype, eid, sourceparams)
             if source.should_call_hooks:
+                # get back a copy of operation for later restore if necessary,
+                # see below
+                pending_operations = session.pending_operations[:]
                 self.hm.call_hooks('before_add_entity', session, entity=entity)
             self.add_info(session, entity, source, extid, complete=complete)
             source.after_entity_insertion(session, extid, entity, sourceparams)
@@ -1096,6 +1099,16 @@
         except Exception:
             if commit or free_cnxset:
                 session.rollback(free_cnxset)
+            else:
+                # XXX do some cleanup manually so that the transaction has a
+                # chance to be commited, with simply this entity discarded
+                self._extid_cache.pop(cachekey, None)
+                self._type_source_cache.pop(eid, None)
+                if 'entity' in locals():
+                    hook.CleanupDeletedEidsCacheOp.get_instance(session).add_data(entity.eid)
+                    self.system_source.delete_info_multi(session, [entity], uri)
+                    if source.should_call_hooks:
+                        session._threaddata.pending_operations = pending_operations
             raise
 
     def add_info(self, session, entity, source, extid=None, complete=True):
--- a/server/serverconfig.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/server/serverconfig.py	Fri Oct 14 09:21:45 2011 +0200
@@ -302,9 +302,7 @@
                         if attr != 'adapter':
                             self.error('skip unknown option %s in sources file')
                 sconfig = _sconfig
-            print >> stream, '[%s]' % section
-            print >> stream, generate_source_config(sconfig)
-            print >> stream
+            stream.write('[%s]\n%s\n' % (section, generate_source_config(sconfig)))
         restrict_perms_to_user(sourcesfile)
 
     def pyro_enabled(self):
--- a/server/session.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/server/session.py	Fri Oct 14 09:21:45 2011 +0200
@@ -28,6 +28,7 @@
 from warnings import warn
 
 from logilab.common.deprecation import deprecated
+from logilab.common.textutils import unormalize
 from rql import CoercionError
 from rql.nodes import ETYPE_PYOBJ_MAP, etype_from_pyobj
 from yams import BASE_TYPES
@@ -232,7 +233,7 @@
 
     def __init__(self, user, repo, cnxprops=None, _id=None):
         super(Session, self).__init__(repo.vreg)
-        self.id = _id or make_uid(user.login.encode('UTF8'))
+        self.id = _id or make_uid(unormalize(user.login).encode('UTF8'))
         cnxprops = cnxprops or ConnectionProperties('inmemory')
         self.user = user
         self.repo = repo
@@ -1319,9 +1320,6 @@
     def owns(self, eid):
         return True
 
-    def has_permission(self, pname, contexteid=None):
-        return True
-
     def property_value(self, key):
         if key == 'ui.language':
             return 'en'
--- a/server/sources/datafeed.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/server/sources/datafeed.py	Fri Oct 14 09:21:45 2011 +0200
@@ -91,9 +91,11 @@
         source_entity.complete()
         self.parser_id = source_entity.parser
         self.latest_retrieval = source_entity.latest_retrieval
-        self.urls = [url.strip() for url in source_entity.url.splitlines()
-                     if url.strip()]
-
+        if source_entity.url:
+            self.urls = [url.strip() for url in source_entity.url.splitlines()
+                         if url.strip()]
+        else:
+            self.urls = []
     def update_config(self, source_entity, typedconfig):
         """update configuration from source entity. `typedconfig` is config
         properly typed with defaults set
@@ -295,7 +297,9 @@
                                          complete=False, commit=False,
                                          sourceparams=sourceparams)
         except ValidationError, ex:
-            self.source.error('error while creating %s: %s', etype, ex)
+            # XXX use critical so they are seen during tests. Should consider
+            # raise_on_error instead?
+            self.source.critical('error while creating %s: %s', etype, ex)
             return None
         if eid < 0:
             # entity has been moved away from its original source
--- a/server/sqlutils.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/server/sqlutils.py	Fri Oct 14 09:21:45 2011 +0200
@@ -129,7 +129,7 @@
         dbhelper = db.get_db_helper(driver)
         w(dbhelper.sql_drop_fti())
         w('')
-    w(dropschema2sql(schema, prefix=SQL_PREFIX,
+    w(dropschema2sql(dbhelper, schema, prefix=SQL_PREFIX,
                      skip_entities=skip_entities,
                      skip_relations=skip_relations))
     w('')
--- a/server/test/data/bootstrap_cubes	Fri Oct 14 09:04:39 2011 +0200
+++ b/server/test/data/bootstrap_cubes	Fri Oct 14 09:21:45 2011 +0200
@@ -1,1 +1,1 @@
-card,comment,folder,tag,basket,email,file
+card,comment,folder,tag,basket,email,file,localperms
--- a/server/test/unittest_checkintegrity.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/server/test/unittest_checkintegrity.py	Fri Oct 14 09:21:45 2011 +0200
@@ -46,9 +46,9 @@
     def test_reindex_all(self):
         self.execute('INSERT Personne X: X nom "toto", X prenom "tutu"')
         self.session.commit(False)
-        self.failUnless(self.execute('Any X WHERE X has_text "tutu"'))
+        self.assertTrue(self.execute('Any X WHERE X has_text "tutu"'))
         reindex_entities(self.repo.schema, self.session, withpb=False)
-        self.failUnless(self.execute('Any X WHERE X has_text "tutu"'))
+        self.assertTrue(self.execute('Any X WHERE X has_text "tutu"'))
 
     def test_reindex_etype(self):
         self.execute('INSERT Personne X: X nom "toto", X prenom "tutu"')
@@ -56,8 +56,8 @@
         self.session.commit(False)
         reindex_entities(self.repo.schema, self.session, withpb=False,
                          etypes=('Personne',))
-        self.failUnless(self.execute('Any X WHERE X has_text "tutu"'))
-        self.failUnless(self.execute('Any X WHERE X has_text "toto"'))
+        self.assertTrue(self.execute('Any X WHERE X has_text "tutu"'))
+        self.assertTrue(self.execute('Any X WHERE X has_text "toto"'))
 
 if __name__ == '__main__':
     unittest_main()
--- a/server/test/unittest_datafeed.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/server/test/unittest_datafeed.py	Fri Oct 14 09:21:45 2011 +0200
@@ -115,8 +115,8 @@
         req = self.request()
         req.execute('DELETE CWSource S WHERE S name "myrenamedfeed"')
         self.commit()
-        self.failIf(self.execute('Card X WHERE X title "cubicweb.org"'))
-        self.failIf(self.execute('Any X WHERE X has_text "cubicweb.org"'))
+        self.assertFalse(self.execute('Card X WHERE X title "cubicweb.org"'))
+        self.assertFalse(self.execute('Any X WHERE X has_text "cubicweb.org"'))
 
 if __name__ == '__main__':
     from logilab.common.testlib import unittest_main
--- a/server/test/unittest_ldapuser.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/server/test/unittest_ldapuser.py	Fri Oct 14 09:21:45 2011 +0200
@@ -262,7 +262,7 @@
     def test_multiple_entities_from_different_sources(self):
         req = self.request()
         self.create_user(req, 'cochon')
-        self.failUnless(self.sexecute('Any X,Y WHERE X login %(syt)s, Y login "cochon"', {'syt': SYT}))
+        self.assertTrue(self.sexecute('Any X,Y WHERE X login %(syt)s, Y login "cochon"', {'syt': SYT}))
 
     def test_exists1(self):
         self.session.set_cnxset()
@@ -288,9 +288,9 @@
         self.create_user(req, 'comme')
         self.create_user(req, 'cochon')
         self.sexecute('SET X copain Y WHERE X login "comme", Y login "cochon"')
-        self.failUnless(self.sexecute('Any X, Y WHERE X copain Y, X login "comme", Y login "cochon"'))
+        self.assertTrue(self.sexecute('Any X, Y WHERE X copain Y, X login "comme", Y login "cochon"'))
         self.sexecute('SET X copain Y WHERE X login %(syt)s, Y login "cochon"', {'syt': SYT})
-        self.failUnless(self.sexecute('Any X, Y WHERE X copain Y, X login %(syt)s, Y login "cochon"', {'syt': SYT}))
+        self.assertTrue(self.sexecute('Any X, Y WHERE X copain Y, X login %(syt)s, Y login "cochon"', {'syt': SYT}))
         rset = self.sexecute('Any GN,L WHERE X in_group G, X login L, G name GN, G name "managers" '
                              'OR EXISTS(X copain T, T login in ("comme", "cochon"))')
         self.assertEqual(sorted(rset.rows), [['managers', 'admin'], ['users', 'comme'], ['users', SYT]])
@@ -392,8 +392,8 @@
                                                   'type': 'CWUser',
                                                   'extid': None})
         self.assertEqual(e.cw_source[0].name, 'system')
-        self.failUnless(e.creation_date)
-        self.failUnless(e.modification_date)
+        self.assertTrue(e.creation_date)
+        self.assertTrue(e.modification_date)
         # XXX test some password has been set
         source.synchronize()
         rset = self.sexecute('CWUser X WHERE X login %(login)s', {'login': SYT})
--- a/server/test/unittest_migractions.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/server/test/unittest_migractions.py	Fri Oct 14 09:21:45 2011 +0200
@@ -74,13 +74,13 @@
         self.repo.vreg['etypes'].clear_caches()
 
     def test_add_attribute_int(self):
-        self.failIf('whatever' in self.schema)
+        self.assertFalse('whatever' in self.schema)
         self.request().create_entity('Note')
         self.commit()
         orderdict = dict(self.mh.rqlexec('Any RTN, O WHERE X name "Note", RDEF from_entity X, '
                                          'RDEF relation_type RT, RDEF ordernum O, RT name RTN'))
         self.mh.cmd_add_attribute('Note', 'whatever')
-        self.failUnless('whatever' in self.schema)
+        self.assertTrue('whatever' in self.schema)
         self.assertEqual(self.schema['whatever'].subjects(), ('Note',))
         self.assertEqual(self.schema['whatever'].objects(), ('Int',))
         self.assertEqual(self.schema['Note'].default('whatever'), 2)
@@ -108,12 +108,12 @@
         self.mh.rollback()
 
     def test_add_attribute_varchar(self):
-        self.failIf('whatever' in self.schema)
+        self.assertFalse('whatever' in self.schema)
         self.request().create_entity('Note')
         self.commit()
-        self.failIf('shortpara' in self.schema)
+        self.assertFalse('shortpara' in self.schema)
         self.mh.cmd_add_attribute('Note', 'shortpara')
-        self.failUnless('shortpara' in self.schema)
+        self.assertTrue('shortpara' in self.schema)
         self.assertEqual(self.schema['shortpara'].subjects(), ('Note', ))
         self.assertEqual(self.schema['shortpara'].objects(), ('String', ))
         # test created column is actually a varchar(64)
@@ -128,10 +128,10 @@
         self.mh.rollback()
 
     def test_add_datetime_with_default_value_attribute(self):
-        self.failIf('mydate' in self.schema)
-        self.failIf('shortpara' in self.schema)
+        self.assertFalse('mydate' in self.schema)
+        self.assertFalse('shortpara' in self.schema)
         self.mh.cmd_add_attribute('Note', 'mydate')
-        self.failUnless('mydate' in self.schema)
+        self.assertTrue('mydate' in self.schema)
         self.assertEqual(self.schema['mydate'].subjects(), ('Note', ))
         self.assertEqual(self.schema['mydate'].objects(), ('Date', ))
         testdate = date(2005, 12, 13)
@@ -167,17 +167,17 @@
         self.mh.rollback()
 
     def test_rename_attribute(self):
-        self.failIf('civility' in self.schema)
+        self.assertFalse('civility' in self.schema)
         eid1 = self.mh.rqlexec('INSERT Personne X: X nom "lui", X sexe "M"')[0][0]
         eid2 = self.mh.rqlexec('INSERT Personne X: X nom "l\'autre", X sexe NULL')[0][0]
         self.mh.cmd_rename_attribute('Personne', 'sexe', 'civility')
-        self.failIf('sexe' in self.schema)
-        self.failUnless('civility' in self.schema)
+        self.assertFalse('sexe' in self.schema)
+        self.assertTrue('civility' in self.schema)
         # test data has been backported
         c1 = self.mh.rqlexec('Any C WHERE X eid %s, X civility C' % eid1)[0][0]
-        self.failUnlessEqual(c1, 'M')
+        self.assertEqual(c1, 'M')
         c2 = self.mh.rqlexec('Any C WHERE X eid %s, X civility C' % eid2)[0][0]
-        self.failUnlessEqual(c2, None)
+        self.assertEqual(c2, None)
 
 
     def test_workflow_actions(self):
@@ -192,13 +192,13 @@
             self.assertEqual(s1, "foo")
 
     def test_add_entity_type(self):
-        self.failIf('Folder2' in self.schema)
-        self.failIf('filed_under2' in self.schema)
+        self.assertFalse('Folder2' in self.schema)
+        self.assertFalse('filed_under2' in self.schema)
         self.mh.cmd_add_entity_type('Folder2')
-        self.failUnless('Folder2' in self.schema)
-        self.failUnless(self.execute('CWEType X WHERE X name "Folder2"'))
-        self.failUnless('filed_under2' in self.schema)
-        self.failUnless(self.execute('CWRType X WHERE X name "filed_under2"'))
+        self.assertTrue('Folder2' in self.schema)
+        self.assertTrue(self.execute('CWEType X WHERE X name "Folder2"'))
+        self.assertTrue('filed_under2' in self.schema)
+        self.assertTrue(self.execute('CWRType X WHERE X name "filed_under2"'))
         self.schema.rebuild_infered_relations()
         self.assertEqual(sorted(str(rs) for rs in self.schema['Folder2'].subject_relations()),
                           ['created_by', 'creation_date', 'cw_source', 'cwuri',
@@ -214,7 +214,7 @@
         self.assertEqual(self.schema['filed_under2'].objects(), ('Folder2',))
         eschema = self.schema.eschema('Folder2')
         for cstr in eschema.rdef('name').constraints:
-            self.failUnless(hasattr(cstr, 'eid'))
+            self.assertTrue(hasattr(cstr, 'eid'))
 
     def test_add_drop_entity_type(self):
         self.mh.cmd_add_entity_type('Folder2')
@@ -227,23 +227,23 @@
         self.commit()
         eschema = self.schema.eschema('Folder2')
         self.mh.cmd_drop_entity_type('Folder2')
-        self.failIf('Folder2' in self.schema)
-        self.failIf(self.execute('CWEType X WHERE X name "Folder2"'))
+        self.assertFalse('Folder2' in self.schema)
+        self.assertFalse(self.execute('CWEType X WHERE X name "Folder2"'))
         # test automatic workflow deletion
-        self.failIf(self.execute('Workflow X WHERE NOT X workflow_of ET'))
-        self.failIf(self.execute('State X WHERE NOT X state_of WF'))
-        self.failIf(self.execute('Transition X WHERE NOT X transition_of WF'))
+        self.assertFalse(self.execute('Workflow X WHERE NOT X workflow_of ET'))
+        self.assertFalse(self.execute('State X WHERE NOT X state_of WF'))
+        self.assertFalse(self.execute('Transition X WHERE NOT X transition_of WF'))
 
     def test_add_drop_relation_type(self):
         self.mh.cmd_add_entity_type('Folder2', auto=False)
         self.mh.cmd_add_relation_type('filed_under2')
         self.schema.rebuild_infered_relations()
-        self.failUnless('filed_under2' in self.schema)
+        self.assertTrue('filed_under2' in self.schema)
         self.assertEqual(sorted(str(e) for e in self.schema['filed_under2'].subjects()),
                           sorted(str(e) for e in self.schema.entities() if not e.final))
         self.assertEqual(self.schema['filed_under2'].objects(), ('Folder2',))
         self.mh.cmd_drop_relation_type('filed_under2')
-        self.failIf('filed_under2' in self.schema)
+        self.assertFalse('filed_under2' in self.schema)
 
     def test_add_relation_definition_nortype(self):
         self.mh.cmd_add_relation_definition('Personne', 'concerne2', 'Affaire')
@@ -260,9 +260,9 @@
         self.mh.rqlexec('SET X concerne2 Y WHERE X is Personne, Y is Affaire')
         self.commit()
         self.mh.cmd_drop_relation_definition('Personne', 'concerne2', 'Affaire')
-        self.failUnless('concerne2' in self.schema)
+        self.assertTrue('concerne2' in self.schema)
         self.mh.cmd_drop_relation_definition('Personne', 'concerne2', 'Note')
-        self.failIf('concerne2' in self.schema)
+        self.assertFalse('concerne2' in self.schema)
 
     def test_drop_relation_definition_existant_rtype(self):
         self.assertEqual(sorted(str(e) for e in self.schema['concerne'].subjects()),
@@ -380,8 +380,8 @@
         self.assertEqual(eexpr.reverse_delete_permission, ())
         self.assertEqual(eexpr.reverse_update_permission, ())
         # no more rqlexpr to delete and add para attribute
-        self.failIf(self._rrqlexpr_rset('add', 'para'))
-        self.failIf(self._rrqlexpr_rset('delete', 'para'))
+        self.assertFalse(self._rrqlexpr_rset('add', 'para'))
+        self.assertFalse(self._rrqlexpr_rset('delete', 'para'))
         # new rql expr to add ecrit_par relation
         rexpr = self._rrqlexpr_entity('add', 'ecrit_par')
         self.assertEqual(rexpr.expression,
@@ -391,13 +391,13 @@
         self.assertEqual(rexpr.reverse_read_permission, ())
         self.assertEqual(rexpr.reverse_delete_permission, ())
         # no more rqlexpr to delete and add travaille relation
-        self.failIf(self._rrqlexpr_rset('add', 'travaille'))
-        self.failIf(self._rrqlexpr_rset('delete', 'travaille'))
+        self.assertFalse(self._rrqlexpr_rset('add', 'travaille'))
+        self.assertFalse(self._rrqlexpr_rset('delete', 'travaille'))
         # no more rqlexpr to delete and update Societe entity
-        self.failIf(self._erqlexpr_rset('update', 'Societe'))
-        self.failIf(self._erqlexpr_rset('delete', 'Societe'))
+        self.assertFalse(self._erqlexpr_rset('update', 'Societe'))
+        self.assertFalse(self._erqlexpr_rset('delete', 'Societe'))
         # no more rqlexpr to read Affaire entity
-        self.failIf(self._erqlexpr_rset('read', 'Affaire'))
+        self.assertFalse(self._erqlexpr_rset('read', 'Affaire'))
         # rqlexpr to update Affaire entity has been updated
         eexpr = self._erqlexpr_entity('update', 'Affaire')
         self.assertEqual(eexpr.expression, 'X concerne S, S owned_by U')
@@ -470,13 +470,13 @@
             try:
                 self.mh.cmd_remove_cube('email', removedeps=True)
                 # file was there because it's an email dependancy, should have been removed
-                self.failIf('email' in self.config.cubes())
-                self.failIf(self.config.cube_dir('email') in self.config.cubes_path())
-                self.failIf('file' in self.config.cubes())
-                self.failIf(self.config.cube_dir('file') in self.config.cubes_path())
+                self.assertFalse('email' in self.config.cubes())
+                self.assertFalse(self.config.cube_dir('email') in self.config.cubes_path())
+                self.assertFalse('file' in self.config.cubes())
+                self.assertFalse(self.config.cube_dir('file') in self.config.cubes_path())
                 for ertype in ('Email', 'EmailThread', 'EmailPart', 'File',
                                'sender', 'in_thread', 'reply_to', 'data_format'):
-                    self.failIf(ertype in schema, ertype)
+                    self.assertFalse(ertype in schema, ertype)
                 self.assertEqual(sorted(schema['see_also'].rdefs.keys()),
                                   sorted([('Folder', 'Folder'),
                                           ('Bookmark', 'Bookmark'),
@@ -493,13 +493,13 @@
                 raise
         finally:
             self.mh.cmd_add_cube('email')
-            self.failUnless('email' in self.config.cubes())
-            self.failUnless(self.config.cube_dir('email') in self.config.cubes_path())
-            self.failUnless('file' in self.config.cubes())
-            self.failUnless(self.config.cube_dir('file') in self.config.cubes_path())
+            self.assertTrue('email' in self.config.cubes())
+            self.assertTrue(self.config.cube_dir('email') in self.config.cubes_path())
+            self.assertTrue('file' in self.config.cubes())
+            self.assertTrue(self.config.cube_dir('file') in self.config.cubes_path())
             for ertype in ('Email', 'EmailThread', 'EmailPart', 'File',
                            'sender', 'in_thread', 'reply_to', 'data_format'):
-                self.failUnless(ertype in schema, ertype)
+                self.assertTrue(ertype in schema, ertype)
             self.assertEqual(sorted(schema['see_also'].rdefs.keys()),
                               sorted([('EmailThread', 'EmailThread'), ('Folder', 'Folder'),
                                       ('Bookmark', 'Bookmark'),
@@ -530,18 +530,18 @@
             try:
                 self.mh.cmd_remove_cube('email')
                 cubes.remove('email')
-                self.failIf('email' in self.config.cubes())
-                self.failUnless('file' in self.config.cubes())
+                self.assertFalse('email' in self.config.cubes())
+                self.assertTrue('file' in self.config.cubes())
                 for ertype in ('Email', 'EmailThread', 'EmailPart',
                                'sender', 'in_thread', 'reply_to'):
-                    self.failIf(ertype in schema, ertype)
+                    self.assertFalse(ertype in schema, ertype)
             except :
                 import traceback
                 traceback.print_exc()
                 raise
         finally:
             self.mh.cmd_add_cube('email')
-            self.failUnless('email' in self.config.cubes())
+            self.assertTrue('email' in self.config.cubes())
             # trick: overwrite self.maxeid to avoid deletion of just reintroduced
             #        types (and their associated tables!)
             self.maxeid = self.execute('Any MAX(X)')[0][0]
@@ -570,13 +570,13 @@
         text = self.execute('INSERT Text X: X para "hip", X summary "hop", X newattr "momo"').get_entity(0, 0)
         note = self.execute('INSERT Note X: X para "hip", X shortpara "hop", X newattr "momo", X unique_id "x"').get_entity(0, 0)
         aff = self.execute('INSERT Affaire X').get_entity(0, 0)
-        self.failUnless(self.execute('SET X newnotinlined Y WHERE X eid %(x)s, Y eid %(y)s',
+        self.assertTrue(self.execute('SET X newnotinlined Y WHERE X eid %(x)s, Y eid %(y)s',
                                      {'x': text.eid, 'y': aff.eid}))
-        self.failUnless(self.execute('SET X newnotinlined Y WHERE X eid %(x)s, Y eid %(y)s',
+        self.assertTrue(self.execute('SET X newnotinlined Y WHERE X eid %(x)s, Y eid %(y)s',
                                      {'x': note.eid, 'y': aff.eid}))
-        self.failUnless(self.execute('SET X newinlined Y WHERE X eid %(x)s, Y eid %(y)s',
+        self.assertTrue(self.execute('SET X newinlined Y WHERE X eid %(x)s, Y eid %(y)s',
                                      {'x': text.eid, 'y': aff.eid}))
-        self.failUnless(self.execute('SET X newinlined Y WHERE X eid %(x)s, Y eid %(y)s',
+        self.assertTrue(self.execute('SET X newinlined Y WHERE X eid %(x)s, Y eid %(y)s',
                                      {'x': note.eid, 'y': aff.eid}))
         # XXX remove specializes by ourselves, else tearDown fails when removing
         # Para because of Note inheritance. This could be fixed by putting the
@@ -601,11 +601,11 @@
     def test_add_symmetric_relation_type(self):
         same_as_sql = self.mh.sqlexec("SELECT sql FROM sqlite_master WHERE type='table' "
                                       "and name='same_as_relation'")
-        self.failIf(same_as_sql)
+        self.assertFalse(same_as_sql)
         self.mh.cmd_add_relation_type('same_as')
         same_as_sql = self.mh.sqlexec("SELECT sql FROM sqlite_master WHERE type='table' "
                                       "and name='same_as_relation'")
-        self.failUnless(same_as_sql)
+        self.assertTrue(same_as_sql)
 
 if __name__ == '__main__':
     unittest_main()
--- a/server/test/unittest_multisources.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/server/test/unittest_multisources.py	Fri Oct 14 09:21:45 2011 +0200
@@ -180,10 +180,10 @@
 
     def test_has_text(self):
         self.repo.sources_by_uri['extern'].synchronize(MTIME) # in case fti_update has been run before
-        self.failUnless(self.sexecute('Any X WHERE X has_text "affref"'))
-        self.failUnless(self.sexecute('Affaire X WHERE X has_text "affref"'))
-        self.failUnless(self.sexecute('Any X ORDERBY FTIRANK(X) WHERE X has_text "affref"'))
-        self.failUnless(self.sexecute('Affaire X ORDERBY FTIRANK(X) WHERE X has_text "affref"'))
+        self.assertTrue(self.sexecute('Any X WHERE X has_text "affref"'))
+        self.assertTrue(self.sexecute('Affaire X WHERE X has_text "affref"'))
+        self.assertTrue(self.sexecute('Any X ORDERBY FTIRANK(X) WHERE X has_text "affref"'))
+        self.assertTrue(self.sexecute('Affaire X ORDERBY FTIRANK(X) WHERE X has_text "affref"'))
 
     def test_anon_has_text(self):
         self.repo.sources_by_uri['extern'].synchronize(MTIME) # in case fti_update has been run before
@@ -210,13 +210,13 @@
         try:
             # force sync
             self.repo.sources_by_uri['extern'].synchronize(MTIME)
-            self.failUnless(self.sexecute('Any X WHERE X has_text "blah"'))
-            self.failUnless(self.sexecute('Any X WHERE X has_text "affreux"'))
+            self.assertTrue(self.sexecute('Any X WHERE X has_text "blah"'))
+            self.assertTrue(self.sexecute('Any X WHERE X has_text "affreux"'))
             cu.execute('DELETE Affaire X WHERE X eid %(x)s', {'x': aff2})
             self.cnx2.commit()
             self.repo.sources_by_uri['extern'].synchronize(MTIME)
             rset = self.sexecute('Any X WHERE X has_text "affreux"')
-            self.failIf(rset)
+            self.assertFalse(rset)
         finally:
             # restore state
             cu.execute('SET X ref "AFFREF" WHERE X eid %(x)s', {'x': self.aff1})
@@ -389,7 +389,7 @@
         req.execute('DELETE CWSource S WHERE S name "extern"')
         self.commit()
         cu = self.session.system_sql("SELECT * FROM entities WHERE source='extern'")
-        self.failIf(cu.fetchall())
+        self.assertFalse(cu.fetchall())
 
 if __name__ == '__main__':
     from logilab.common.testlib import unittest_main
--- a/server/test/unittest_querier.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/server/test/unittest_querier.py	Fri Oct 14 09:21:45 2011 +0200
@@ -250,7 +250,7 @@
 
     def test_unknown_eid(self):
         # should return an empty result set
-        self.failIf(self.execute('Any X WHERE X eid 99999999'))
+        self.assertFalse(self.execute('Any X WHERE X eid 99999999'))
 
     def test_typed_eid(self):
         # should return an empty result set
@@ -418,8 +418,8 @@
         self.execute("SET X tags Y WHERE X eid %(t)s, Y eid %(g)s",
                      {'g': geid, 't': teid})
         rset = self.execute("Any GN,TN ORDERBY GN WHERE T? tags G, T name TN, G name GN")
-        self.failUnless(['users', 'tag'] in rset.rows)
-        self.failUnless(['activated', None] in rset.rows)
+        self.assertTrue(['users', 'tag'] in rset.rows)
+        self.assertTrue(['activated', None] in rset.rows)
         rset = self.execute("Any GN,TN ORDERBY GN WHERE T tags G?, T name TN, G name GN")
         self.assertEqual(rset.rows, [[None, 'tagbis'], ['users', 'tag']])
 
@@ -494,26 +494,26 @@
 
     def test_select_custom_aggregat_concat_string(self):
         rset = self.execute('Any GROUP_CONCAT(N) WHERE X is CWGroup, X name N')
-        self.failUnless(rset)
-        self.failUnlessEqual(sorted(rset[0][0].split(', ')), ['guests', 'managers',
+        self.assertTrue(rset)
+        self.assertEqual(sorted(rset[0][0].split(', ')), ['guests', 'managers',
                                                              'owners', 'users'])
 
     def test_select_custom_regproc_limit_size(self):
         rset = self.execute('Any TEXT_LIMIT_SIZE(N, 3) WHERE X is CWGroup, X name N, X name "managers"')
-        self.failUnless(rset)
-        self.failUnlessEqual(rset[0][0], 'man...')
+        self.assertTrue(rset)
+        self.assertEqual(rset[0][0], 'man...')
         self.execute("INSERT Basket X: X name 'bidule', X description '<b>hop hop</b>', X description_format 'text/html'")
         rset = self.execute('Any LIMIT_SIZE(D, DF, 3) WHERE X is Basket, X description D, X description_format DF')
-        self.failUnless(rset)
-        self.failUnlessEqual(rset[0][0], 'hop...')
+        self.assertTrue(rset)
+        self.assertEqual(rset[0][0], 'hop...')
 
     def test_select_regproc_orderby(self):
         rset = self.execute('DISTINCT Any X,N ORDERBY GROUP_SORT_VALUE(N) WHERE X is CWGroup, X name N, X name "managers"')
-        self.failUnlessEqual(len(rset), 1)
-        self.failUnlessEqual(rset[0][1], 'managers')
+        self.assertEqual(len(rset), 1)
+        self.assertEqual(rset[0][1], 'managers')
         rset = self.execute('Any X,N ORDERBY GROUP_SORT_VALUE(N) WHERE X is CWGroup, X name N, NOT U in_group X, U login "admin"')
-        self.failUnlessEqual(len(rset), 3)
-        self.failUnlessEqual(rset[0][1], 'owners')
+        self.assertEqual(len(rset), 3)
+        self.assertEqual(rset[0][1], 'owners')
 
     def test_select_aggregat_sort(self):
         rset = self.execute('Any G, COUNT(U) GROUPBY G ORDERBY 2 WHERE U in_group G')
@@ -619,7 +619,7 @@
         self.assertEqual(len(rset.rows), 2, rset.rows)
         biduleeids = [r[0] for r in rset.rows]
         rset = self.execute(u'Any N where NOT N has_text "bidüle"')
-        self.failIf([r[0] for r in rset.rows if r[0] in biduleeids])
+        self.assertFalse([r[0] for r in rset.rows if r[0] in biduleeids])
         # duh?
         rset = self.execute('Any X WHERE X has_text %(text)s', {'text': u'ça'})
 
@@ -757,7 +757,7 @@
 
     def test_select_explicit_eid(self):
         rset = self.execute('Any X,E WHERE X owned_by U, X eid E, U eid %(u)s', {'u': self.session.user.eid})
-        self.failUnless(rset)
+        self.assertTrue(rset)
         self.assertEqual(rset.description[0][1], 'Int')
 
 #     def test_select_rewritten_optional(self):
@@ -774,7 +774,7 @@
         rset = self.execute('Tag X WHERE X creation_date TODAY')
         self.assertEqual(len(rset.rows), 2)
         rset = self.execute('Any MAX(D) WHERE X is Tag, X creation_date D')
-        self.failUnless(isinstance(rset[0][0], datetime), (rset[0][0], type(rset[0][0])))
+        self.assertTrue(isinstance(rset[0][0], datetime), (rset[0][0], type(rset[0][0])))
 
     def test_today(self):
         self.execute("INSERT Tag X: X name 'bidule', X creation_date TODAY")
@@ -891,11 +891,11 @@
 
     def test_select_date_mathexp(self):
         rset = self.execute('Any X, TODAY - CD WHERE X is CWUser, X creation_date CD')
-        self.failUnless(rset)
-        self.failUnlessEqual(rset.description[0][1], 'Interval')
+        self.assertTrue(rset)
+        self.assertEqual(rset.description[0][1], 'Interval')
         eid, = self.execute("INSERT Personne X: X nom 'bidule'")[0]
         rset = self.execute('Any X, NOW - CD WHERE X is Personne, X creation_date CD')
-        self.failUnlessEqual(rset.description[0][1], 'Interval')
+        self.assertEqual(rset.description[0][1], 'Interval')
 
     def test_select_subquery_aggregat_1(self):
         # percent users by groups
@@ -1173,7 +1173,7 @@
         rset = self.execute('Any X, Y WHERE X travaille Y')
         self.assertEqual(len(rset.rows), 1)
         # test add of an existant relation but with NOT X rel Y protection
-        self.failIf(self.execute("SET X travaille Y WHERE X eid %(x)s, Y eid %(y)s,"
+        self.assertFalse(self.execute("SET X travaille Y WHERE X eid %(x)s, Y eid %(y)s,"
                                  "NOT X travaille Y",
                                  {'x': str(eid1), 'y': str(eid2)}))
 
@@ -1198,9 +1198,9 @@
         peid2 = self.execute("INSERT Personne Y: Y nom 'tutu'")[0][0]
         self.execute('SET P1 owned_by U, P2 owned_by U '
                      'WHERE P1 eid %s, P2 eid %s, U eid %s' % (peid1, peid2, ueid))
-        self.failUnless(self.execute('Any X WHERE X eid %s, X owned_by U, U eid %s'
+        self.assertTrue(self.execute('Any X WHERE X eid %s, X owned_by U, U eid %s'
                                        % (peid1, ueid)))
-        self.failUnless(self.execute('Any X WHERE X eid %s, X owned_by U, U eid %s'
+        self.assertTrue(self.execute('Any X WHERE X eid %s, X owned_by U, U eid %s'
                                        % (peid2, ueid)))
 
     def test_update_math_expr(self):
--- a/server/test/unittest_repository.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/server/test/unittest_repository.py	Fri Oct 14 09:21:45 2011 +0200
@@ -98,13 +98,13 @@
                                            ('nom', 'prenom', 'inline2'))
 
     def test_all_entities_have_owner(self):
-        self.failIf(self.execute('Any X WHERE NOT X owned_by U'))
+        self.assertFalse(self.execute('Any X WHERE NOT X owned_by U'))
 
     def test_all_entities_have_is(self):
-        self.failIf(self.execute('Any X WHERE NOT X is ET'))
+        self.assertFalse(self.execute('Any X WHERE NOT X is ET'))
 
     def test_all_entities_have_cw_source(self):
-        self.failIf(self.execute('Any X WHERE NOT X cw_source S'))
+        self.assertFalse(self.execute('Any X WHERE NOT X cw_source S'))
 
     def test_connect(self):
         cnxid = self.repo.connect(self.admlogin, password=self.admpassword)
@@ -147,7 +147,7 @@
                           'INSERT CWUser X: X login %(login)s, X upassword %(passwd)s',
                           {'login': u"tutetute", 'passwd': 'tutetute'})
         self.assertRaises(ValidationError, self.repo.commit, cnxid)
-        self.failIf(self.repo.execute(cnxid, 'CWUser X WHERE X login "tutetute"'))
+        self.assertFalse(self.repo.execute(cnxid, 'CWUser X WHERE X login "tutetute"'))
         self.repo.close(cnxid)
 
     def test_rollback_on_execute_validation_error(self):
@@ -160,12 +160,12 @@
         with self.temporary_appobjects(ValidationErrorAfterHook):
             self.assertRaises(ValidationError,
                               self.execute, 'SET X name "toto" WHERE X is CWGroup, X name "guests"')
-            self.failUnless(self.execute('Any X WHERE X is CWGroup, X name "toto"'))
+            self.assertTrue(self.execute('Any X WHERE X is CWGroup, X name "toto"'))
             with self.assertRaises(QueryError) as cm:
                 self.commit()
             self.assertEqual(str(cm.exception), 'transaction must be rollbacked')
             self.rollback()
-            self.failIf(self.execute('Any X WHERE X is CWGroup, X name "toto"'))
+            self.assertFalse(self.execute('Any X WHERE X is CWGroup, X name "toto"'))
 
     def test_rollback_on_execute_unauthorized(self):
         class UnauthorizedAfterHook(Hook):
@@ -177,12 +177,12 @@
         with self.temporary_appobjects(UnauthorizedAfterHook):
             self.assertRaises(Unauthorized,
                               self.execute, 'SET X name "toto" WHERE X is CWGroup, X name "guests"')
-            self.failUnless(self.execute('Any X WHERE X is CWGroup, X name "toto"'))
+            self.assertTrue(self.execute('Any X WHERE X is CWGroup, X name "toto"'))
             with self.assertRaises(QueryError) as cm:
                 self.commit()
             self.assertEqual(str(cm.exception), 'transaction must be rollbacked')
             self.rollback()
-            self.failIf(self.execute('Any X WHERE X is CWGroup, X name "toto"'))
+            self.assertFalse(self.execute('Any X WHERE X is CWGroup, X name "toto"'))
 
 
     def test_close(self):
@@ -364,13 +364,13 @@
             cnx.load_appobjects(subpath=('entities',))
             # check we can get the schema
             schema = cnx.get_schema()
-            self.failUnless(cnx.vreg)
-            self.failUnless('etypes'in cnx.vreg)
+            self.assertTrue(cnx.vreg)
+            self.assertTrue('etypes'in cnx.vreg)
             cu = cnx.cursor()
             rset = cu.execute('Any U,G WHERE U in_group G')
             user = iter(rset.entities()).next()
-            self.failUnless(user._cw)
-            self.failUnless(user._cw.vreg)
+            self.assertTrue(user._cw)
+            self.assertTrue(user._cw.vreg)
             from cubicweb.entities import authobjs
             self.assertIsInstance(user._cw.user, authobjs.CWUser)
             cnx.close()
@@ -425,7 +425,7 @@
 
     def test_schema_is_relation(self):
         no_is_rset = self.execute('Any X WHERE NOT X is ET')
-        self.failIf(no_is_rset, no_is_rset.description)
+        self.assertFalse(no_is_rset, no_is_rset.description)
 
 #     def test_perfo(self):
 #         self.set_debug(True)
@@ -509,7 +509,7 @@
             events = ('before_update_entity',)
             def __call__(self):
                 # invoiced attribute shouldn't be considered "edited" before the hook
-                self._test.failIf('invoiced' in self.entity.cw_edited,
+                self._test.assertFalse('invoiced' in self.entity.cw_edited,
                                   'cw_edited cluttered by previous update')
                 self.entity.cw_edited['invoiced'] = 10
         with self.temporary_appobjects(DummyBeforeHook):
@@ -582,7 +582,7 @@
         self.session.set_cnxset()
         cu = self.session.system_sql('SELECT mtime FROM entities WHERE eid = %s' % eidp)
         mtime = cu.fetchone()[0]
-        self.failUnless(omtime < mtime)
+        self.assertTrue(omtime < mtime)
         self.commit()
         date, modified, deleted = self.repo.entities_modified_since(('Personne',), omtime)
         self.assertEqual(modified, [('Personne', eidp)])
@@ -627,7 +627,7 @@
     def test_no_uncessary_ftiindex_op(self):
         req = self.request()
         req.create_entity('Workflow', name=u'dummy workflow', description=u'huuuuu')
-        self.failIf(any(x for x in self.session.pending_operations
+        self.assertFalse(any(x for x in self.session.pending_operations
                         if isinstance(x, native.FTIndexEntityOp)))
 
 
@@ -639,7 +639,7 @@
                           [u'system.version.basket', u'system.version.card', u'system.version.comment',
                            u'system.version.cubicweb', u'system.version.email',
                            u'system.version.file', u'system.version.folder',
-                           u'system.version.tag'])
+                           u'system.version.localperms', u'system.version.tag'])
 
 CALLED = []
 
--- a/server/test/unittest_rql2sql.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/server/test/unittest_rql2sql.py	Fri Oct 14 09:21:45 2011 +0200
@@ -46,12 +46,12 @@
     for modname in drivers[driver]:
         try:
             if not quiet:
-                print >> sys.stderr, 'Trying %s' % modname
+                sys.stderr.write('Trying %s\n' % modname)
             module = db.load_module_from_name(modname, use_sys=False)
             break
         except ImportError:
             if not quiet:
-                print >> sys.stderr, '%s is not available' % modname
+                sys.stderr.write('%s is not available\n' % modname)
             continue
     else:
         return mock_object(STRING=1, BOOLEAN=2, BINARY=3, DATETIME=4, NUMBER=5), drivers[driver][0]
--- a/server/test/unittest_rqlannotation.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/server/test/unittest_rqlannotation.py	Fri Oct 14 09:21:45 2011 +0200
@@ -342,7 +342,7 @@
 
     def test_remove_from_deleted_source_1(self):
         rqlst = self._prepare('Note X WHERE X eid 999998, NOT X cw_source Y')
-        self.failIf('X' in rqlst.defined_vars) # simplified
+        self.assertFalse('X' in rqlst.defined_vars) # simplified
         self.assertEqual(rqlst.defined_vars['Y']._q_invariant, True)
 
     def test_remove_from_deleted_source_2(self):
--- a/server/test/unittest_security.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/server/test/unittest_security.py	Fri Oct 14 09:21:45 2011 +0200
@@ -327,7 +327,7 @@
             cu = cnx.cursor()
             aff2 = cu.execute("INSERT Affaire X: X sujet 'cool'")[0][0]
             # entity created in transaction are readable *by eid*
-            self.failUnless(cu.execute('Any X WHERE X eid %(x)s', {'x':aff2}))
+            self.assertTrue(cu.execute('Any X WHERE X eid %(x)s', {'x':aff2}))
             # XXX would be nice if it worked
             rset = cu.execute("Affaire X WHERE X sujet 'cool'")
             self.assertEqual(len(rset), 0)
@@ -347,8 +347,8 @@
         cu.execute("SET A concerne S WHERE A eid %(a)s, S eid %(s)s", {'a': aff2, 's': soc1})
         cnx.commit()
         self.assertRaises(Unauthorized, cu.execute, 'Any X WHERE X eid %(x)s', {'x':aff1})
-        self.failUnless(cu.execute('Any X WHERE X eid %(x)s', {'x':aff2}))
-        self.failUnless(cu.execute('Any X WHERE X eid %(x)s', {'x':card1}))
+        self.assertTrue(cu.execute('Any X WHERE X eid %(x)s', {'x':aff2}))
+        self.assertTrue(cu.execute('Any X WHERE X eid %(x)s', {'x':card1}))
         rset = cu.execute("Any X WHERE X has_text 'cool'")
         self.assertEqual(sorted(eid for eid, in rset.rows),
                           [card1, aff2])
@@ -457,14 +457,14 @@
         cnx = self.login('anon')
         cu = cnx.cursor()
         rset = cu.execute('CWUser X')
-        self.failUnless(rset)
+        self.assertTrue(rset)
         x = rset.get_entity(0, 0)
         self.assertEqual(x.login, None)
-        self.failUnless(x.creation_date)
+        self.assertTrue(x.creation_date)
         x = rset.get_entity(1, 0)
         x.complete()
         self.assertEqual(x.login, None)
-        self.failUnless(x.creation_date)
+        self.assertTrue(x.creation_date)
         cnx.rollback()
         cnx.close()
 
@@ -492,7 +492,7 @@
         cu = cnx.cursor()
         cu.execute('DELETE Affaire X WHERE X ref "ARCT01"')
         cnx.commit()
-        self.failIf(cu.execute('Affaire X'))
+        self.assertFalse(cu.execute('Affaire X'))
         cnx.close()
 
     def test_users_and_groups_non_readable_by_guests(self):
--- a/server/test/unittest_session.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/server/test/unittest_session.py	Fri Oct 14 09:21:45 2011 +0200
@@ -95,7 +95,7 @@
         description = self.session.build_description(rset.syntax_tree(), None, rset.rows)
         self.assertEqual(len(description), orig_length - 1)
         self.assertEqual(len(rset.rows), orig_length - 1)
-        self.failIf(rset.rows[0][0] == 9999999)
+        self.assertFalse(rset.rows[0][0] == 9999999)
 
 
 if __name__ == '__main__':
--- a/server/test/unittest_storage.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/server/test/unittest_storage.py	Fri Oct 14 09:21:45 2011 +0200
@@ -89,10 +89,10 @@
         f1 = self.create_file()
         expected_filepath = osp.join(self.tempdir, '%s_data_%s' %
                                      (f1.eid, f1.data_name))
-        self.failUnless(osp.isfile(expected_filepath))
+        self.assertTrue(osp.isfile(expected_filepath))
         self.assertEqual(file(expected_filepath).read(), 'the-data')
         self.rollback()
-        self.failIf(osp.isfile(expected_filepath))
+        self.assertFalse(osp.isfile(expected_filepath))
         f1 = self.create_file()
         self.commit()
         self.assertEqual(file(expected_filepath).read(), 'the-data')
@@ -100,12 +100,12 @@
         self.rollback()
         self.assertEqual(file(expected_filepath).read(), 'the-data')
         f1.cw_delete()
-        self.failUnless(osp.isfile(expected_filepath))
+        self.assertTrue(osp.isfile(expected_filepath))
         self.rollback()
-        self.failUnless(osp.isfile(expected_filepath))
+        self.assertTrue(osp.isfile(expected_filepath))
         f1.cw_delete()
         self.commit()
-        self.failIf(osp.isfile(expected_filepath))
+        self.assertFalse(osp.isfile(expected_filepath))
 
     def test_bfss_sqlite_fspath(self):
         f1 = self.create_file()
@@ -219,7 +219,7 @@
         #       update f1's local dict. We want the pure rql version to work
         self.commit()
         old_path = self.fspath(f1)
-        self.failUnless(osp.isfile(old_path))
+        self.assertTrue(osp.isfile(old_path))
         self.assertEqual(osp.splitext(old_path)[1], '.txt')
         self.execute('SET F data %(d)s, F data_name %(dn)s, F data_format %(df)s WHERE F eid %(f)s',
                      {'d': Binary('some other data'), 'f': f1.eid, 'dn': u'bar.jpg', 'df': u'image/jpeg'})
@@ -228,8 +228,8 @@
         # the old file is dead
         f2 = self.execute('Any F WHERE F eid %(f)s, F is File', {'f': f1.eid}).get_entity(0, 0)
         new_path = self.fspath(f2)
-        self.failIf(osp.isfile(old_path))
-        self.failUnless(osp.isfile(new_path))
+        self.assertFalse(osp.isfile(old_path))
+        self.assertTrue(osp.isfile(new_path))
         self.assertEqual(osp.splitext(new_path)[1], '.jpg')
 
     @tag('update', 'extension', 'rollback')
@@ -242,7 +242,7 @@
         self.commit()
         old_path = self.fspath(f1)
         old_data = f1.data.getvalue()
-        self.failUnless(osp.isfile(old_path))
+        self.assertTrue(osp.isfile(old_path))
         self.assertEqual(osp.splitext(old_path)[1], '.txt')
         self.execute('SET F data %(d)s, F data_name %(dn)s, F data_format %(df)s WHERE F eid %(f)s',
                      {'d': Binary('some other data'), 'f': f1.eid, 'dn': u'bar.jpg', 'df': u'image/jpeg'})
@@ -252,7 +252,7 @@
         f2 = self.execute('Any F WHERE F eid %(f)s, F is File', {'f': f1.eid}).get_entity(0, 0)
         new_path = self.fspath(f2)
         new_data = f2.data.getvalue()
-        self.failUnless(osp.isfile(new_path))
+        self.assertTrue(osp.isfile(new_path))
         self.assertEqual(osp.splitext(new_path)[1], '.txt')
         self.assertEqual(old_path, new_path)
         self.assertEqual(old_data, new_data)
@@ -279,7 +279,7 @@
         self.commit()
         self.assertEqual(f1.data.getvalue(), 'the new data')
         self.assertEqual(self.fspath(f1), new_fspath)
-        self.failIf(osp.isfile(old_fspath))
+        self.assertFalse(osp.isfile(old_fspath))
 
     @tag('fsimport')
     def test_clean(self):
--- a/server/test/unittest_undo.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/server/test/unittest_undo.py	Fri Oct 14 09:21:45 2011 +0200
@@ -43,13 +43,13 @@
         # also check transaction actions have been properly deleted
         cu = self.session.system_sql(
             "SELECT * from tx_entity_actions WHERE tx_uuid='%s'" % txuuid)
-        self.failIf(cu.fetchall())
+        self.assertFalse(cu.fetchall())
         cu = self.session.system_sql(
             "SELECT * from tx_relation_actions WHERE tx_uuid='%s'" % txuuid)
-        self.failIf(cu.fetchall())
+        self.assertFalse(cu.fetchall())
 
     def test_undo_api(self):
-        self.failUnless(self.txuuid)
+        self.assertTrue(self.txuuid)
         # test transaction api
         self.assertRaises(NoSuchTransaction,
                           self.cnx.transaction_info, 'hop')
@@ -58,7 +58,7 @@
         self.assertRaises(NoSuchTransaction,
                           self.cnx.undo_transaction, 'hop')
         txinfo = self.cnx.transaction_info(self.txuuid)
-        self.failUnless(txinfo.datetime)
+        self.assertTrue(txinfo.datetime)
         self.assertEqual(txinfo.user_eid, self.session.user.eid)
         self.assertEqual(txinfo.user().login, 'admin')
         actions = txinfo.actions_list()
@@ -159,9 +159,9 @@
         undotxuuid = self.commit()
         self.assertEqual(undotxuuid, None) # undo not undoable
         self.assertEqual(errors, [])
-        self.failUnless(self.execute('Any X WHERE X eid %(x)s', {'x': toto.eid}))
-        self.failUnless(self.execute('Any X WHERE X eid %(x)s', {'x': e.eid}))
-        self.failUnless(self.execute('Any X WHERE X has_text "toto@logilab"'))
+        self.assertTrue(self.execute('Any X WHERE X eid %(x)s', {'x': toto.eid}))
+        self.assertTrue(self.execute('Any X WHERE X eid %(x)s', {'x': e.eid}))
+        self.assertTrue(self.execute('Any X WHERE X has_text "toto@logilab"'))
         self.assertEqual(toto.cw_adapt_to('IWorkflowable').state, 'activated')
         self.assertEqual(toto.cw_adapt_to('IEmailable').get_email(), 'toto@logilab.org')
         self.assertEqual([(p.pkey, p.value) for p in toto.reverse_for_user],
@@ -231,20 +231,20 @@
         txuuid = self.commit()
         errors = self.cnx.undo_transaction(txuuid)
         self.commit()
-        self.failIf(errors)
-        self.failIf(self.execute('Any X WHERE X eid %(x)s', {'x': c.eid}))
-        self.failIf(self.execute('Any X WHERE X eid %(x)s', {'x': p.eid}))
-        self.failIf(self.execute('Any X,Y WHERE X fiche Y'))
+        self.assertFalse(errors)
+        self.assertFalse(self.execute('Any X WHERE X eid %(x)s', {'x': c.eid}))
+        self.assertFalse(self.execute('Any X WHERE X eid %(x)s', {'x': p.eid}))
+        self.assertFalse(self.execute('Any X,Y WHERE X fiche Y'))
         self.session.set_cnxset()
         for eid in (p.eid, c.eid):
-            self.failIf(session.system_sql(
+            self.assertFalse(session.system_sql(
                 'SELECT * FROM entities WHERE eid=%s' % eid).fetchall())
-            self.failIf(session.system_sql(
+            self.assertFalse(session.system_sql(
                 'SELECT 1 FROM owned_by_relation WHERE eid_from=%s' % eid).fetchall())
             # added by sql in hooks (except when using dataimport)
-            self.failIf(session.system_sql(
+            self.assertFalse(session.system_sql(
                 'SELECT 1 FROM is_relation WHERE eid_from=%s' % eid).fetchall())
-            self.failIf(session.system_sql(
+            self.assertFalse(session.system_sql(
                 'SELECT 1 FROM is_instance_of_relation WHERE eid_from=%s' % eid).fetchall())
         self.check_transaction_deleted(txuuid)
 
--- a/setup.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/setup.py	Fri Oct 14 09:21:45 2011 +0200
@@ -119,7 +119,7 @@
             src = '%s/%s' % (directory, filename)
             dest = to_dir + src[len(from_dir):]
             if verbose:
-               print >> sys.stderr, src, '->', dest
+               sys.stderr.write('%s -> %s\n' % (src, dest))
             if os.path.isdir(src):
                 if not exists(dest):
                     os.mkdir(dest)
--- a/skeleton/setup.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/skeleton/setup.py	Fri Oct 14 09:21:45 2011 +0200
@@ -105,7 +105,7 @@
             src = join(directory, filename)
             dest = to_dir + src[len(from_dir):]
             if verbose:
-                print >> sys.stderr, src, '->', dest
+                sys.stderr.write('%s -> %s\n' % (src, dest))
             if os.path.isdir(src):
                 if not exists(dest):
                     os.mkdir(dest)
--- a/sobjects/test/unittest_email.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/sobjects/test/unittest_email.py	Fri Oct 14 09:21:45 2011 +0200
@@ -51,7 +51,7 @@
         self.execute('SET U primary_email E WHERE U login "anon", E address "client@client.com"')
         self.commit()
         rset = self.execute('Any X WHERE X use_email E, E eid %(e)s', {'e': email1})
-        self.failIf(rset.rowcount != 1, rset)
+        self.assertFalse(rset.rowcount != 1, rset)
 
     def test_security_check(self):
         req = self.request()
--- a/sobjects/test/unittest_notification.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/sobjects/test/unittest_notification.py	Fri Oct 14 09:21:45 2011 +0200
@@ -30,29 +30,29 @@
     def test_base(self):
         msgid1 = construct_message_id('testapp', 21)
         msgid2 = construct_message_id('testapp', 21)
-        self.failIfEqual(msgid1, msgid2)
-        self.failIf('&' in msgid1)
-        self.failIf('=' in msgid1)
-        self.failIf('/' in msgid1)
-        self.failIf('+' in msgid1)
+        self.assertNotEqual(msgid1, msgid2)
+        self.assertFalse('&' in msgid1)
+        self.assertFalse('=' in msgid1)
+        self.assertFalse('/' in msgid1)
+        self.assertFalse('+' in msgid1)
         values = parse_message_id(msgid1, 'testapp')
-        self.failUnless(values)
+        self.assertTrue(values)
         # parse_message_id should work with or without surrounding <>
-        self.failUnlessEqual(values, parse_message_id(msgid1[1:-1], 'testapp'))
-        self.failUnlessEqual(values['eid'], '21')
-        self.failUnless('timestamp' in values)
-        self.failUnlessEqual(parse_message_id(msgid1[1:-1], 'anotherapp'), None)
+        self.assertEqual(values, parse_message_id(msgid1[1:-1], 'testapp'))
+        self.assertEqual(values['eid'], '21')
+        self.assertTrue('timestamp' in values)
+        self.assertEqual(parse_message_id(msgid1[1:-1], 'anotherapp'), None)
 
     def test_notimestamp(self):
         msgid1 = construct_message_id('testapp', 21, False)
         msgid2 = construct_message_id('testapp', 21, False)
         values = parse_message_id(msgid1, 'testapp')
-        self.failUnlessEqual(values, {'eid': '21'})
+        self.assertEqual(values, {'eid': '21'})
 
     def test_parse_message_doesnt_raise(self):
-        self.failUnlessEqual(parse_message_id('oijioj@bla.bla', 'tesapp'), None)
-        self.failUnlessEqual(parse_message_id('oijioj@bla', 'tesapp'), None)
-        self.failUnlessEqual(parse_message_id('oijioj', 'tesapp'), None)
+        self.assertEqual(parse_message_id('oijioj@bla.bla', 'tesapp'), None)
+        self.assertEqual(parse_message_id('oijioj@bla', 'tesapp'), None)
+        self.assertEqual(parse_message_id('oijioj', 'tesapp'), None)
 
 
     def test_nonregr_empty_message_id(self):
@@ -86,7 +86,7 @@
         req = self.request()
         u = self.create_user(req, 'toto')
         u.cw_adapt_to('IWorkflowable').fire_transition('deactivate', comment=u'yeah')
-        self.failIf(MAILBOX)
+        self.assertFalse(MAILBOX)
         self.commit()
         self.assertEqual(len(MAILBOX), 1)
         email = MAILBOX[0]
--- a/test/data/bootstrap_cubes	Fri Oct 14 09:04:39 2011 +0200
+++ b/test/data/bootstrap_cubes	Fri Oct 14 09:21:45 2011 +0200
@@ -1,1 +1,1 @@
-card, file, tag
+card, file, tag, localperms
--- a/test/data/entities.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/test/data/entities.py	Fri Oct 14 09:21:45 2011 +0200
@@ -1,4 +1,4 @@
-# copyright 2003-2010 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
+# copyright 2003-2011 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
 # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
 #
 # This file is part of CubicWeb.
@@ -15,9 +15,7 @@
 #
 # You should have received a copy of the GNU Lesser General Public License along
 # with CubicWeb.  If not, see <http://www.gnu.org/licenses/>.
-"""
 
-"""
 from cubicweb.entities import AnyEntity, fetch_config
 
 class Societe(AnyEntity):
@@ -27,7 +25,7 @@
 class Personne(Societe):
     """customized class forne Person entities"""
     __regid__ = 'Personne'
-    fetch_attrs, fetch_order = fetch_config(['nom', 'prenom'])
+    fetch_attrs, cw_fetch_order = fetch_config(['nom', 'prenom'])
     rest_attr = 'nom'
 
 
--- a/test/data/rewrite/bootstrap_cubes	Fri Oct 14 09:04:39 2011 +0200
+++ b/test/data/rewrite/bootstrap_cubes	Fri Oct 14 09:21:45 2011 +0200
@@ -1,1 +1,1 @@
-card
+card,localperms
--- a/test/unittest_cwconfig.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/test/unittest_cwconfig.py	Fri Oct 14 09:21:45 2011 +0200
@@ -123,7 +123,7 @@
         self.assertEqual(self.config.cubes_search_path(),
                           [CUSTOM_CUBES_DIR,
                            self.config.CUBES_DIR])
-        self.failUnless('mycube' in self.config.available_cubes())
+        self.assertTrue('mycube' in self.config.available_cubes())
         # test cubes python path
         self.config.adjust_sys_path()
         import cubes
--- a/test/unittest_entity.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/test/unittest_entity.py	Fri Oct 14 09:21:45 2011 +0200
@@ -33,16 +33,16 @@
         super(EntityTC, self).setUp()
         self.backup_dict = {}
         for cls in self.vreg['etypes'].iter_classes():
-            self.backup_dict[cls] = (cls.fetch_attrs, cls.fetch_order)
+            self.backup_dict[cls] = (cls.fetch_attrs, cls.cw_fetch_order)
 
     def tearDown(self):
         super(EntityTC, self).tearDown()
         for cls in self.vreg['etypes'].iter_classes():
-            cls.fetch_attrs, cls.fetch_order = self.backup_dict[cls]
+            cls.fetch_attrs, cls.cw_fetch_order = self.backup_dict[cls]
 
     def test_boolean_value(self):
         e = self.vreg['etypes'].etype_class('CWUser')(self.request())
-        self.failUnless(e)
+        self.assertTrue(e)
 
     def test_yams_inheritance(self):
         from entities import Note
@@ -87,8 +87,8 @@
                      {'t': oe.eid, 'u': p.eid})
         e = req.create_entity('Note', type=u'z')
         e.copy_relations(oe.eid)
-        self.failIf(e.ecrit_par)
-        self.failUnless(oe.ecrit_par)
+        self.assertFalse(e.ecrit_par)
+        self.assertTrue(oe.ecrit_par)
 
     def test_copy_with_composite(self):
         user = self.user()
@@ -100,8 +100,8 @@
                                'WHERE G name "users"')[0][0]
         e = self.execute('Any X WHERE X eid %(x)s', {'x': usereid}).get_entity(0, 0)
         e.copy_relations(user.eid)
-        self.failIf(e.use_email)
-        self.failIf(e.primary_email)
+        self.assertFalse(e.use_email)
+        self.assertFalse(e.primary_email)
 
     def test_copy_with_non_initial_state(self):
         user = self.user()
@@ -128,7 +128,7 @@
         groups = user.in_group
         self.assertEqual(sorted(user._cw_related_cache), ['in_group_subject', 'primary_email_subject'])
         for group in groups:
-            self.failIf('in_group_subject' in group._cw_related_cache, group._cw_related_cache.keys())
+            self.assertFalse('in_group_subject' in group._cw_related_cache, group._cw_related_cache.keys())
 
     def test_related_limit(self):
         req = self.request()
@@ -179,7 +179,7 @@
         try:
             # testing basic fetch_attrs attribute
             self.assertEqual(Personne.fetch_rql(user),
-                              'Any X,AA,AB,AC ORDERBY AA ASC '
+                              'Any X,AA,AB,AC ORDERBY AA '
                               'WHERE X is Personne, X nom AA, X prenom AB, X modification_date AC')
             # testing unknown attributes
             Personne.fetch_attrs = ('bloug', 'beep')
@@ -187,36 +187,36 @@
             # testing one non final relation
             Personne.fetch_attrs = ('nom', 'prenom', 'travaille')
             self.assertEqual(Personne.fetch_rql(user),
-                              'Any X,AA,AB,AC,AD ORDERBY AA ASC '
+                              'Any X,AA,AB,AC,AD ORDERBY AA '
                               'WHERE X is Personne, X nom AA, X prenom AB, X travaille AC?, AC nom AD')
             # testing two non final relations
             Personne.fetch_attrs = ('nom', 'prenom', 'travaille', 'evaluee')
             self.assertEqual(Personne.fetch_rql(user),
-                             'Any X,AA,AB,AC,AD,AE ORDERBY AA ASC '
+                             'Any X,AA,AB,AC,AD,AE ORDERBY AA '
                              'WHERE X is Personne, X nom AA, X prenom AB, X travaille AC?, AC nom AD, '
                              'X evaluee AE?')
             # testing one non final relation with recursion
             Personne.fetch_attrs = ('nom', 'prenom', 'travaille')
             Societe.fetch_attrs = ('nom', 'evaluee')
             self.assertEqual(Personne.fetch_rql(user),
-                              'Any X,AA,AB,AC,AD,AE,AF ORDERBY AA ASC,AF DESC '
+                              'Any X,AA,AB,AC,AD,AE,AF ORDERBY AA,AF DESC '
                               'WHERE X is Personne, X nom AA, X prenom AB, X travaille AC?, AC nom AD, '
                               'AC evaluee AE?, AE modification_date AF'
                               )
             # testing symmetric relation
             Personne.fetch_attrs = ('nom', 'connait')
-            self.assertEqual(Personne.fetch_rql(user), 'Any X,AA,AB ORDERBY AA ASC '
+            self.assertEqual(Personne.fetch_rql(user), 'Any X,AA,AB ORDERBY AA '
                               'WHERE X is Personne, X nom AA, X connait AB?')
             # testing optional relation
             peschema.subjrels['travaille'].rdef(peschema, seschema).cardinality = '?*'
             Personne.fetch_attrs = ('nom', 'prenom', 'travaille')
             Societe.fetch_attrs = ('nom',)
             self.assertEqual(Personne.fetch_rql(user),
-                              'Any X,AA,AB,AC,AD ORDERBY AA ASC WHERE X is Personne, X nom AA, X prenom AB, X travaille AC?, AC nom AD')
+                              'Any X,AA,AB,AC,AD ORDERBY AA WHERE X is Personne, X nom AA, X prenom AB, X travaille AC?, AC nom AD')
             # testing relation with cardinality > 1
             peschema.subjrels['travaille'].rdef(peschema, seschema).cardinality = '**'
             self.assertEqual(Personne.fetch_rql(user),
-                              'Any X,AA,AB ORDERBY AA ASC WHERE X is Personne, X nom AA, X prenom AB')
+                              'Any X,AA,AB ORDERBY AA WHERE X is Personne, X nom AA, X prenom AB')
             # XXX test unauthorized attribute
         finally:
             # fetch_attrs restored by generic tearDown
@@ -227,15 +227,21 @@
         Personne = self.vreg['etypes'].etype_class('Personne')
         Note = self.vreg['etypes'].etype_class('Note')
         SubNote = self.vreg['etypes'].etype_class('SubNote')
-        self.failUnless(issubclass(self.vreg['etypes'].etype_class('SubNote'), Note))
-        Personne.fetch_attrs, Personne.fetch_order = fetch_config(('nom', 'type'))
-        Note.fetch_attrs, Note.fetch_order = fetch_config(('type',))
-        SubNote.fetch_attrs, SubNote.fetch_order = fetch_config(('type',))
+        self.assertTrue(issubclass(self.vreg['etypes'].etype_class('SubNote'), Note))
+        Personne.fetch_attrs, Personne.cw_fetch_order = fetch_config(('nom', 'type'))
+        Note.fetch_attrs, Note.cw_fetch_order = fetch_config(('type',))
+        SubNote.fetch_attrs, SubNote.cw_fetch_order = fetch_config(('type',))
         p = self.request().create_entity('Personne', nom=u'pouet')
         self.assertEqual(p.cw_related_rql('evaluee'),
-                          'Any X,AA,AB ORDERBY AA ASC WHERE E eid %(x)s, E evaluee X, '
-                          'X type AA, X modification_date AB')
-        Personne.fetch_attrs, Personne.fetch_order = fetch_config(('nom', ))
+                         'Any X,AA,AB ORDERBY AA WHERE E eid %(x)s, E evaluee X, '
+                         'X type AA, X modification_date AB')
+        n = self.request().create_entity('Note')
+        self.assertEqual(n.cw_related_rql('evaluee', role='object',
+                                          targettypes=('Societe', 'Personne')),
+                         "Any X,AA ORDERBY AB DESC WHERE E eid %(x)s, X evaluee E, "
+                         "X is IN('Personne', 'Societe'), X nom AA, "
+                         "X modification_date AB")
+        Personne.fetch_attrs, Personne.cw_fetch_order = fetch_config(('nom', ))
         # XXX
         self.assertEqual(p.cw_related_rql('evaluee'),
                           'Any X,AA ORDERBY AA DESC '
@@ -246,8 +252,8 @@
                           'Any X,AA ORDERBY AA DESC '
                           'WHERE E eid %(x)s, E tags X, X modification_date AA')
         self.assertEqual(tag.cw_related_rql('tags', 'subject', ('Personne',)),
-                          'Any X,AA,AB ORDERBY AA ASC '
-                          'WHERE E eid %(x)s, E tags X, X is IN (Personne), X nom AA, '
+                          'Any X,AA,AB ORDERBY AA '
+                          'WHERE E eid %(x)s, E tags X, X is Personne, X nom AA, '
                           'X modification_date AB')
 
     def test_related_rql_ambiguous_cant_use_fetch_order(self):
@@ -258,7 +264,7 @@
                           'Any X,AA ORDERBY AA DESC '
                           'WHERE E eid %(x)s, E tags X, X modification_date AA')
 
-    def test_related_rql_cant_fetch_ambiguous_rtype(self):
+    def test_related_rql_fetch_ambiguous_rtype(self):
         soc_etype = self.vreg['etypes'].etype_class('Societe')
         soc = soc_etype(self.request())
         soc_etype.fetch_attrs = ('fournit',)
@@ -266,15 +272,14 @@
         self.vreg['etypes'].etype_class('Produit').fetch_attrs = ('fabrique_par',)
         self.vreg['etypes'].etype_class('Usine').fetch_attrs = ('lieu',)
         self.vreg['etypes'].etype_class('Personne').fetch_attrs = ('nom',)
-        # XXX should be improved: we could fetch fabrique_par object too
         self.assertEqual(soc.cw_related_rql('fournit', 'subject'),
-                         'Any X WHERE E eid %(x)s, E fournit X')
+                         'Any X,A WHERE E eid %(x)s, E fournit X, X fabrique_par A')
 
     def test_unrelated_rql_security_1_manager(self):
         user = self.request().user
         rql = user.cw_unrelated_rql('use_email', 'EmailAddress', 'subject')[0]
         self.assertEqual(rql, 'Any O,AA,AB,AC ORDERBY AC DESC '
-                         'WHERE NOT EXISTS(ZZ use_email O), S eid %(x)s, '
+                         'WHERE NOT ZZ use_email O, S eid %(x)s, '
                          'O is EmailAddress, O address AA, O alias AB, O modification_date AC')
 
     def test_unrelated_rql_security_1_user(self):
@@ -284,37 +289,37 @@
         user = req.user
         rql = user.cw_unrelated_rql('use_email', 'EmailAddress', 'subject')[0]
         self.assertEqual(rql, 'Any O,AA,AB,AC ORDERBY AC DESC '
-                         'WHERE NOT EXISTS(ZZ use_email O), S eid %(x)s, '
+                         'WHERE NOT ZZ use_email O, S eid %(x)s, '
                          'O is EmailAddress, O address AA, O alias AB, O modification_date AC')
         user = self.execute('Any X WHERE X login "admin"').get_entity(0, 0)
         rql = user.cw_unrelated_rql('use_email', 'EmailAddress', 'subject')[0]
         self.assertEqual(rql, 'Any O,AA,AB,AC ORDERBY AC DESC '
-                         'WHERE NOT EXISTS(ZZ use_email O, ZZ is CWUser), S eid %(x)s, '
-                         'O is EmailAddress, O address AA, O alias AB, O modification_date AC, A eid %(B)s, '
-                         'EXISTS(S identity A, NOT A in_group C, C name "guests", C is CWGroup)')
+                         'WHERE NOT ZZ use_email O, S eid %(x)s, '
+                         'O is EmailAddress, O address AA, O alias AB, O modification_date AC, AD eid %(AE)s, '
+                         'EXISTS(S identity AD, NOT AD in_group AF, AF name "guests", AF is CWGroup), ZZ is CWUser')
 
     def test_unrelated_rql_security_1_anon(self):
         self.login('anon')
         user = self.request().user
         rql = user.cw_unrelated_rql('use_email', 'EmailAddress', 'subject')[0]
         self.assertEqual(rql, 'Any O,AA,AB,AC ORDERBY AC DESC '
-                         'WHERE NOT EXISTS(ZZ use_email O, ZZ is CWUser), S eid %(x)s, '
-                         'O is EmailAddress, O address AA, O alias AB, O modification_date AC, A eid %(B)s, '
-                         'EXISTS(S identity A, NOT A in_group C, C name "guests", C is CWGroup)')
+                         'WHERE NOT ZZ use_email O, S eid %(x)s, '
+                         'O is EmailAddress, O address AA, O alias AB, O modification_date AC, AD eid %(AE)s, '
+                         'EXISTS(S identity AD, NOT AD in_group AF, AF name "guests", AF is CWGroup), ZZ is CWUser')
 
     def test_unrelated_rql_security_2(self):
         email = self.execute('INSERT EmailAddress X: X address "hop"').get_entity(0, 0)
         rql = email.cw_unrelated_rql('use_email', 'CWUser', 'object')[0]
         self.assertEqual(rql, 'Any S,AA,AB,AC,AD ORDERBY AA '
-                         'WHERE NOT EXISTS(S use_email O), O eid %(x)s, S is CWUser, '
+                         'WHERE NOT S use_email O, O eid %(x)s, S is CWUser, '
                          'S login AA, S firstname AB, S surname AC, S modification_date AD')
         self.login('anon')
         email = self.execute('Any X WHERE X eid %(x)s', {'x': email.eid}).get_entity(0, 0)
         rql = email.cw_unrelated_rql('use_email', 'CWUser', 'object')[0]
         self.assertEqual(rql, 'Any S,AA,AB,AC,AD ORDERBY AA '
-                         'WHERE NOT EXISTS(S use_email O), O eid %(x)s, S is CWUser, '
+                         'WHERE NOT S use_email O, O eid %(x)s, S is CWUser, '
                          'S login AA, S firstname AB, S surname AC, S modification_date AD, '
-                         'A eid %(B)s, EXISTS(S identity A, NOT A in_group C, C name "guests", C is CWGroup)')
+                         'AE eid %(AF)s, EXISTS(S identity AE, NOT AE in_group AG, AG name "guests", AG is CWGroup)')
 
     def test_unrelated_rql_security_nonexistant(self):
         self.login('anon')
@@ -323,7 +328,7 @@
         self.assertEqual(rql, 'Any S,AA,AB,AC,AD ORDERBY AA '
                          'WHERE S is CWUser, '
                          'S login AA, S firstname AB, S surname AC, S modification_date AD, '
-                         'A eid %(B)s, EXISTS(S identity A, NOT A in_group C, C name "guests", C is CWGroup)')
+                         'AE eid %(AF)s, EXISTS(S identity AE, NOT AE in_group AG, AG name "guests", AG is CWGroup)')
 
     def test_unrelated_rql_constraints_creation_subject(self):
         person = self.vreg['etypes'].etype_class('Personne')(self.request())
@@ -338,14 +343,15 @@
         self.assertEqual(
             rql, 'Any S,AA,AB,AC ORDERBY AC DESC WHERE '
             'S is Personne, S nom AA, S prenom AB, S modification_date AC, '
-            'NOT (S connait A, A nom "toto"), A is Personne, EXISTS(S travaille B, B nom "tutu")')
+            'NOT (S connait AD, AD nom "toto"), AD is Personne, '
+            'EXISTS(S travaille AE, AE nom "tutu")')
 
     def test_unrelated_rql_constraints_edition_subject(self):
         person = self.request().create_entity('Personne', nom=u'sylvain')
         rql = person.cw_unrelated_rql('connait', 'Personne', 'subject')[0]
         self.assertEqual(
             rql, 'Any O,AA,AB,AC ORDERBY AC DESC WHERE '
-            'NOT EXISTS(S connait O), S eid %(x)s, O is Personne, '
+            'NOT S connait O, S eid %(x)s, O is Personne, '
             'O nom AA, O prenom AB, O modification_date AC, '
             'NOT S identity O')
 
@@ -354,23 +360,23 @@
         rql = person.cw_unrelated_rql('connait', 'Personne', 'object')[0]
         self.assertEqual(
             rql, 'Any S,AA,AB,AC ORDERBY AC DESC WHERE '
-            'NOT EXISTS(S connait O), O eid %(x)s, S is Personne, '
+            'NOT S connait O, O eid %(x)s, S is Personne, '
             'S nom AA, S prenom AB, S modification_date AC, '
-            'NOT S identity O, NOT (S connait A, A nom "toto"), '
-            'EXISTS(S travaille B, B nom "tutu")')
+            'NOT S identity O, NOT (S connait AD, AD nom "toto"), '
+            'EXISTS(S travaille AE, AE nom "tutu")')
 
     def test_unrelated_base(self):
         req = self.request()
         p = req.create_entity('Personne', nom=u'di mascio', prenom=u'adrien')
         e = req.create_entity('Tag', name=u'x')
         related = [r.eid for r in e.tags]
-        self.failUnlessEqual(related, [])
+        self.assertEqual(related, [])
         unrelated = [r[0] for r in e.unrelated('tags', 'Personne', 'subject')]
-        self.failUnless(p.eid in unrelated)
+        self.assertTrue(p.eid in unrelated)
         self.execute('SET X tags Y WHERE X is Tag, Y is Personne')
         e = self.execute('Any X WHERE X is Tag').get_entity(0, 0)
         unrelated = [r[0] for r in e.unrelated('tags', 'Personne', 'subject')]
-        self.failIf(p.eid in unrelated)
+        self.assertFalse(p.eid in unrelated)
 
     def test_unrelated_limit(self):
         req = self.request()
@@ -538,7 +544,7 @@
         p2 = req.create_entity('Personne', nom=u'toto')
         self.execute('SET X evaluee Y WHERE X nom "di mascio", Y nom "toto"')
         self.assertEqual(p1.evaluee[0].nom, "toto")
-        self.failUnless(not p1.reverse_evaluee)
+        self.assertTrue(not p1.reverse_evaluee)
 
     def test_complete_relation(self):
         session = self.session
@@ -547,10 +553,10 @@
             'WHERE U login "admin", S1 name "activated", S2 name "deactivated"')[0][0]
         trinfo = self.execute('Any X WHERE X eid %(x)s', {'x': eid}).get_entity(0, 0)
         trinfo.complete()
-        self.failUnless(isinstance(trinfo.cw_attr_cache['creation_date'], datetime))
-        self.failUnless(trinfo.cw_relation_cached('from_state', 'subject'))
-        self.failUnless(trinfo.cw_relation_cached('to_state', 'subject'))
-        self.failUnless(trinfo.cw_relation_cached('wf_info_for', 'subject'))
+        self.assertTrue(isinstance(trinfo.cw_attr_cache['creation_date'], datetime))
+        self.assertTrue(trinfo.cw_relation_cached('from_state', 'subject'))
+        self.assertTrue(trinfo.cw_relation_cached('to_state', 'subject'))
+        self.assertTrue(trinfo.cw_relation_cached('wf_info_for', 'subject'))
         self.assertEqual(trinfo.by_transition, ())
 
     def test_request_cache(self):
@@ -558,7 +564,7 @@
         user = self.execute('CWUser X WHERE X login "admin"', req=req).get_entity(0, 0)
         state = user.in_state[0]
         samestate = self.execute('State X WHERE X name "activated"', req=req).get_entity(0, 0)
-        self.failUnless(state is samestate)
+        self.assertTrue(state is samestate)
 
     def test_rest_path(self):
         req = self.request()
--- a/test/unittest_rqlrewrite.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/test/unittest_rqlrewrite.py	Fri Oct 14 09:21:45 2011 +0200
@@ -110,7 +110,7 @@
                            'P name "read", P require_group G')
         rqlst = parse('Card C')
         rewrite(rqlst, {('C', 'X'): (constraint,)}, {})
-        self.failUnlessEqual(rqlst.as_string(),
+        self.assertEqual(rqlst.as_string(),
                              u"Any C WHERE C is Card, B eid %(D)s, "
                              "EXISTS(C in_state A, B in_group E, F require_state A, "
                              "F name 'read', F require_group E, A is State, E is CWGroup, F is CWPermission)")
@@ -129,13 +129,13 @@
                              "F name 'read', F require_group E, A is State, E is CWGroup, F is CWPermission), "
                              "(EXISTS(S ref LIKE 'PUBLIC%')) OR (EXISTS(B in_group G, G name 'public', G is CWGroup)), "
                              "S is Affaire")
-        self.failUnless('D' in kwargs)
+        self.assertTrue('D' in kwargs)
 
     def test_or(self):
         constraint = '(X identity U) OR (X in_state ST, CL identity U, CL in_state ST, ST name "subscribed")'
         rqlst = parse('Any S WHERE S owned_by C, C eid %(u)s, S is in (CWUser, CWGroup)')
         rewrite(rqlst, {('C', 'X'): (constraint,)}, {'u':1})
-        self.failUnlessEqual(rqlst.as_string(),
+        self.assertEqual(rqlst.as_string(),
                              "Any S WHERE S owned_by C, C eid %(u)s, S is IN(CWUser, CWGroup), A eid %(B)s, "
                              "EXISTS((C identity A) OR (C in_state D, E identity A, "
                              "E in_state D, D name 'subscribed'), D is State, E is CWUser)")
@@ -145,7 +145,7 @@
                            'P name "read", P require_group G')
         rqlst = parse('Any 2') # this is the simplified rql st for Any X WHERE X eid 12
         rewrite(rqlst, {('2', 'X'): (constraint,)}, {})
-        self.failUnlessEqual(rqlst.as_string(),
+        self.assertEqual(rqlst.as_string(),
                              u"Any 2 WHERE B eid %(C)s, "
                              "EXISTS(2 in_state A, B in_group D, E require_state A, "
                              "E name 'read', E require_group D, A is State, D is CWGroup, E is CWPermission)")
@@ -155,7 +155,7 @@
                            'P name "read", P require_group G')
         rqlst = parse('Any A,C WHERE A documented_by C?')
         rewrite(rqlst, {('C', 'X'): (constraint,)}, {})
-        self.failUnlessEqual(rqlst.as_string(),
+        self.assertEqual(rqlst.as_string(),
                              "Any A,C WHERE A documented_by C?, A is Affaire "
                              "WITH C BEING "
                              "(Any C WHERE EXISTS(C in_state B, D in_group F, G require_state B, G name 'read', "
@@ -166,7 +166,7 @@
                            'P name "read", P require_group G')
         rqlst = parse('Any A,C,T WHERE A documented_by C?, C title T')
         rewrite(rqlst, {('C', 'X'): (constraint,)}, {})
-        self.failUnlessEqual(rqlst.as_string(),
+        self.assertEqual(rqlst.as_string(),
                              "Any A,C,T WHERE A documented_by C?, A is Affaire "
                              "WITH C,T BEING "
                              "(Any C,T WHERE C title T, EXISTS(C in_state B, D in_group F, "
@@ -179,7 +179,7 @@
         constraint2 = 'X in_state S, S name "public"'
         rqlst = parse('Any A,C,T WHERE A documented_by C?, C title T')
         rewrite(rqlst, {('C', 'X'): (constraint1, constraint2)}, {})
-        self.failUnlessEqual(rqlst.as_string(),
+        self.assertEqual(rqlst.as_string(),
                              "Any A,C,T WHERE A documented_by C?, A is Affaire "
                              "WITH C,T BEING (Any C,T WHERE C title T, "
                              "EXISTS(C in_state B, D in_group F, G require_state B, G name 'read', G require_group F), "
@@ -194,7 +194,7 @@
         rewrite(rqlst, {('LA', 'X'): (constraint1, constraint2),
                         ('X', 'X'): (constraint3,),
                         ('Y', 'X'): (constraint3,)}, {})
-        self.failUnlessEqual(rqlst.as_string(),
+        self.assertEqual(rqlst.as_string(),
                              u'Any X,LA,Y WHERE LA? documented_by X, LA concerne Y, B eid %(C)s, '
                              'EXISTS(X created_by B), EXISTS(Y created_by B), '
                              'X is Card, Y is IN(Division, Note, Societe) '
@@ -209,12 +209,12 @@
                         ('A', 'X'): (c2,),
                         }, {})
         # XXX suboptimal
-        self.failUnlessEqual(rqlst.as_string(),
-                             "Any C,A,R WITH A,C,R BEING "
-                             "(Any A,C,R WHERE A? inlined_card C, A ref R, "
-                             "(A is NULL) OR (EXISTS(A inlined_card B, B require_permission D, "
-                             "B is Card, D is CWPermission)), "
-                             "A is Affaire, C is Card, EXISTS(C require_permission E, E is CWPermission))")
+        self.assertEqual(rqlst.as_string(),
+                         "Any C,A,R WITH A,C,R BEING "
+                         "(Any A,C,R WHERE A? inlined_card C, A ref R, "
+                         "(A is NULL) OR (EXISTS(A inlined_card B, B require_permission D, "
+                         "B is Card, D is CWPermission)), "
+                         "A is Affaire, C is Card, EXISTS(C require_permission E, E is CWPermission))")
 
     # def test_optional_var_inlined_has_perm(self):
     #     c1 = ('X require_permission P')
@@ -223,7 +223,7 @@
     #     rewrite(rqlst, {('C', 'X'): (c1,),
     #                     ('A', 'X'): (c2,),
     #                     }, {})
-    #     self.failUnlessEqual(rqlst.as_string(),
+    #     self.assertEqual(rqlst.as_string(),
     #                          "")
 
     def test_optional_var_inlined_imbricated_error(self):
@@ -255,7 +255,7 @@
         snippet = ('X in_state S, S name "hop"')
         rqlst = parse('Card C WHERE C in_state STATE')
         rewrite(rqlst, {('C', 'X'): (snippet,)}, {})
-        self.failUnlessEqual(rqlst.as_string(),
+        self.assertEqual(rqlst.as_string(),
                              "Any C WHERE C in_state STATE, C is Card, "
                              "EXISTS(STATE name 'hop'), STATE is State")
 
@@ -263,7 +263,7 @@
         snippet = ('TW subworkflow_exit X, TW name "hop"')
         rqlst = parse('WorkflowTransition C WHERE C subworkflow_exit EXIT')
         rewrite(rqlst, {('EXIT', 'X'): (snippet,)}, {})
-        self.failUnlessEqual(rqlst.as_string(),
+        self.assertEqual(rqlst.as_string(),
                              "Any C WHERE C subworkflow_exit EXIT, C is WorkflowTransition, "
                              "EXISTS(C name 'hop'), EXIT is SubWorkflowExitPoint")
 
@@ -272,14 +272,14 @@
         snippet = ('X in_state S?, S name "hop"')
         rqlst = parse('Card C WHERE C in_state STATE?')
         rewrite(rqlst, {('C', 'X'): (snippet,)}, {})
-        self.failUnlessEqual(rqlst.as_string(),
+        self.assertEqual(rqlst.as_string(),
                              "Any C WHERE C in_state STATE?, C is Card, "
                              "EXISTS(STATE name 'hop'), STATE is State")
     def test_relation_optimization_2_rhs(self):
         snippet = ('TW? subworkflow_exit X, TW name "hop"')
         rqlst = parse('SubWorkflowExitPoint EXIT WHERE C? subworkflow_exit EXIT')
         rewrite(rqlst, {('EXIT', 'X'): (snippet,)}, {})
-        self.failUnlessEqual(rqlst.as_string(),
+        self.assertEqual(rqlst.as_string(),
                              "Any EXIT WHERE C? subworkflow_exit EXIT, EXIT is SubWorkflowExitPoint, "
                              "EXISTS(C name 'hop'), C is WorkflowTransition")
 
@@ -288,14 +288,14 @@
         snippet = ('X in_state S?, S name "hop"')
         rqlst = parse('Card C WHERE C in_state STATE')
         rewrite(rqlst, {('C', 'X'): (snippet,)}, {})
-        self.failUnlessEqual(rqlst.as_string(),
+        self.assertEqual(rqlst.as_string(),
                              "Any C WHERE C in_state STATE, C is Card, "
                              "EXISTS(STATE name 'hop'), STATE is State")
     def test_relation_optimization_3_rhs(self):
         snippet = ('TW? subworkflow_exit X, TW name "hop"')
         rqlst = parse('WorkflowTransition C WHERE C subworkflow_exit EXIT')
         rewrite(rqlst, {('EXIT', 'X'): (snippet,)}, {})
-        self.failUnlessEqual(rqlst.as_string(),
+        self.assertEqual(rqlst.as_string(),
                              "Any C WHERE C subworkflow_exit EXIT, C is WorkflowTransition, "
                              "EXISTS(C name 'hop'), EXIT is SubWorkflowExitPoint")
 
@@ -304,14 +304,14 @@
         snippet = ('X in_state S, S name "hop"')
         rqlst = parse('Card C WHERE C in_state STATE?')
         rewrite(rqlst, {('C', 'X'): (snippet,)}, {})
-        self.failUnlessEqual(rqlst.as_string(),
+        self.assertEqual(rqlst.as_string(),
                              "Any C WHERE C in_state STATE?, C is Card, "
                              "EXISTS(C in_state A, A name 'hop', A is State), STATE is State")
     def test_relation_non_optimization_1_rhs(self):
         snippet = ('TW subworkflow_exit X, TW name "hop"')
         rqlst = parse('SubWorkflowExitPoint EXIT WHERE C? subworkflow_exit EXIT')
         rewrite(rqlst, {('EXIT', 'X'): (snippet,)}, {})
-        self.failUnlessEqual(rqlst.as_string(),
+        self.assertEqual(rqlst.as_string(),
                              "Any EXIT WHERE C? subworkflow_exit EXIT, EXIT is SubWorkflowExitPoint, "
                              "EXISTS(A subworkflow_exit EXIT, A name 'hop', A is WorkflowTransition), "
                              "C is WorkflowTransition")
@@ -326,7 +326,7 @@
         trinfo_constraint = ('X wf_info_for Y, Y require_permission P, P name "read"')
         rqlst = parse('Any U,T WHERE U is CWUser, T wf_info_for U')
         rewrite(rqlst, {('T', 'X'): (trinfo_constraint, 'X wf_info_for Y, Y in_group G, G name "managers"')}, {})
-        self.failUnlessEqual(rqlst.as_string(),
+        self.assertEqual(rqlst.as_string(),
                              u"Any U,T WHERE U is CWUser, T wf_info_for U, "
                              "EXISTS(U in_group B, B name 'managers', B is CWGroup), T is TrInfo")
 
@@ -335,14 +335,14 @@
         trinfo_constraint = ('X wf_info_for Y, Y require_permission P, P name "read"')
         rqlst = parse('Any T WHERE T wf_info_for X')
         rewrite(rqlst, {('T', 'X'): (trinfo_constraint, 'X in_group G, G name "managers"')}, {})
-        self.failUnlessEqual(rqlst.as_string(),
+        self.assertEqual(rqlst.as_string(),
                              u'XXX dunno what should be generated')
 
     def test_add_ambiguity_exists(self):
         constraint = ('X concerne Y')
         rqlst = parse('Affaire X')
         rewrite(rqlst, {('X', 'X'): (constraint,)}, {})
-        self.failUnlessEqual(rqlst.as_string(),
+        self.assertEqual(rqlst.as_string(),
                              u"Any X WHERE X is Affaire, ((EXISTS(X concerne A, A is Division)) OR (EXISTS(X concerne C, C is Societe))) OR (EXISTS(X concerne B, B is Note))")
 
     def test_add_ambiguity_outerjoin(self):
@@ -350,7 +350,7 @@
         rqlst = parse('Any X,C WHERE X? documented_by C')
         rewrite(rqlst, {('X', 'X'): (constraint,)}, {})
         # ambiguity are kept in the sub-query, no need to be resolved using OR
-        self.failUnlessEqual(rqlst.as_string(),
+        self.assertEqual(rqlst.as_string(),
                              u"Any X,C WHERE X? documented_by C, C is Card WITH X BEING (Any X WHERE EXISTS(X concerne A), X is Affaire)")
 
 
@@ -358,76 +358,76 @@
         constraint = RRQLExpression('S owned_by U')
         rqlst = parse('Card C')
         rewrite(rqlst, {('C', 'S'): (constraint,)}, {}, 'SU')
-        self.failUnlessEqual(rqlst.as_string(),
+        self.assertEqual(rqlst.as_string(),
                              u"Any C WHERE C is Card, A eid %(B)s, EXISTS(C owned_by A)")
         rqlst = parse('Card C')
         rewrite(rqlst, {('C', 'S'): (constraint,)}, {}, 'OU')
-        self.failUnlessEqual(rqlst.as_string(),
+        self.assertEqual(rqlst.as_string(),
                              u"Any C WHERE C is Card")
         rqlst = parse('Card C')
         rewrite(rqlst, {('C', 'S'): (constraint,)}, {}, 'SOU')
-        self.failUnlessEqual(rqlst.as_string(),
+        self.assertEqual(rqlst.as_string(),
                              u"Any C WHERE C is Card, A eid %(B)s, EXISTS(C owned_by A)")
 
     def test_rrqlexpr_nonexistant_subject_2(self):
         constraint = RRQLExpression('S owned_by U, O owned_by U, O is Card')
         rqlst = parse('Card C')
         rewrite(rqlst, {('C', 'S'): (constraint,)}, {}, 'SU')
-        self.failUnlessEqual(rqlst.as_string(),
+        self.assertEqual(rqlst.as_string(),
                              'Any C WHERE C is Card, A eid %(B)s, EXISTS(C owned_by A)')
         rqlst = parse('Card C')
         rewrite(rqlst, {('C', 'S'): (constraint,)}, {}, 'OU')
-        self.failUnlessEqual(rqlst.as_string(),
+        self.assertEqual(rqlst.as_string(),
                              'Any C WHERE C is Card, B eid %(D)s, EXISTS(A owned_by B, A is Card)')
         rqlst = parse('Card C')
         rewrite(rqlst, {('C', 'S'): (constraint,)}, {}, 'SOU')
-        self.failUnlessEqual(rqlst.as_string(),
+        self.assertEqual(rqlst.as_string(),
                              'Any C WHERE C is Card, A eid %(B)s, EXISTS(C owned_by A, D owned_by A, D is Card)')
 
     def test_rrqlexpr_nonexistant_subject_3(self):
         constraint = RRQLExpression('U in_group G, G name "users"')
         rqlst = parse('Card C')
         rewrite(rqlst, {('C', 'S'): (constraint,)}, {}, 'SU')
-        self.failUnlessEqual(rqlst.as_string(),
+        self.assertEqual(rqlst.as_string(),
                              u'Any C WHERE C is Card, A eid %(B)s, EXISTS(A in_group D, D name "users", D is CWGroup)')
 
     def test_rrqlexpr_nonexistant_subject_4(self):
         constraint = RRQLExpression('U in_group G, G name "users", S owned_by U')
         rqlst = parse('Card C')
         rewrite(rqlst, {('C', 'S'): (constraint,)}, {}, 'SU')
-        self.failUnlessEqual(rqlst.as_string(),
+        self.assertEqual(rqlst.as_string(),
                              u'Any C WHERE C is Card, A eid %(B)s, EXISTS(A in_group D, D name "users", C owned_by A, D is CWGroup)')
         rqlst = parse('Card C')
         rewrite(rqlst, {('C', 'S'): (constraint,)}, {}, 'OU')
-        self.failUnlessEqual(rqlst.as_string(),
+        self.assertEqual(rqlst.as_string(),
                              u'Any C WHERE C is Card, A eid %(B)s, EXISTS(A in_group D, D name "users", D is CWGroup)')
 
     def test_rrqlexpr_nonexistant_subject_5(self):
         constraint = RRQLExpression('S owned_by Z, O owned_by Z, O is Card')
         rqlst = parse('Card C')
         rewrite(rqlst, {('C', 'S'): (constraint,)}, {}, 'S')
-        self.failUnlessEqual(rqlst.as_string(),
+        self.assertEqual(rqlst.as_string(),
                              u"Any C WHERE C is Card, EXISTS(C owned_by A, A is CWUser)")
 
     def test_rqlexpr_not_relation_1_1(self):
         constraint = RRQLExpression('X owned_by Z, Z login "hop"', 'X')
         rqlst = parse('Affaire A WHERE NOT EXISTS(A documented_by C)')
         rewrite(rqlst, {('C', 'X'): (constraint,)}, {}, 'X')
-        self.failUnlessEqual(rqlst.as_string(),
+        self.assertEqual(rqlst.as_string(),
                              u'Any A WHERE NOT EXISTS(A documented_by C, EXISTS(C owned_by B, B login "hop", B is CWUser), C is Card), A is Affaire')
 
     def test_rqlexpr_not_relation_1_2(self):
         constraint = RRQLExpression('X owned_by Z, Z login "hop"', 'X')
         rqlst = parse('Affaire A WHERE NOT EXISTS(A documented_by C)')
         rewrite(rqlst, {('A', 'X'): (constraint,)}, {}, 'X')
-        self.failUnlessEqual(rqlst.as_string(),
+        self.assertEqual(rqlst.as_string(),
                              u'Any A WHERE NOT EXISTS(A documented_by C, C is Card), A is Affaire, EXISTS(A owned_by B, B login "hop", B is CWUser)')
 
     def test_rqlexpr_not_relation_2(self):
         constraint = RRQLExpression('X owned_by Z, Z login "hop"', 'X')
         rqlst = rqlhelper.parse('Affaire A WHERE NOT A documented_by C', annotate=False)
         rewrite(rqlst, {('C', 'X'): (constraint,)}, {}, 'X')
-        self.failUnlessEqual(rqlst.as_string(),
+        self.assertEqual(rqlst.as_string(),
                              u'Any A WHERE NOT EXISTS(A documented_by C, EXISTS(C owned_by B, B login "hop", B is CWUser), C is Card), A is Affaire')
 
 
--- a/test/unittest_rset.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/test/unittest_rset.py	Fri Oct 14 09:21:45 2011 +0200
@@ -401,7 +401,7 @@
     def test_entities(self):
         rset = self.execute('Any U,G WHERE U in_group G')
         # make sure we have at least one element
-        self.failUnless(rset)
+        self.assertTrue(rset)
         self.assertEqual(set(e.e_schema.type for e in rset.entities(0)),
                           set(['CWUser',]))
         self.assertEqual(set(e.e_schema.type for e in rset.entities(1)),
@@ -410,7 +410,7 @@
     def test_iter_rows_with_entities(self):
         rset = self.execute('Any U,UN,G,GN WHERE U in_group G, U login UN, G name GN')
         # make sure we have at least one element
-        self.failUnless(rset)
+        self.assertTrue(rset)
         out = list(rset.iter_rows_with_entities())[0]
         self.assertEqual( out[0].login, out[1] )
         self.assertEqual( out[2].name, out[3] )
--- a/test/unittest_schema.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/test/unittest_schema.py	Fri Oct 14 09:21:45 2011 +0200
@@ -106,9 +106,9 @@
         # isinstance(cstr, RQLConstraint)
         # -> expected to return RQLConstraint instances but not
         #    RRQLVocabularyConstraint and QLUniqueConstraint
-        self.failIf(issubclass(RQLUniqueConstraint, RQLVocabularyConstraint))
-        self.failIf(issubclass(RQLUniqueConstraint, RQLConstraint))
-        self.failUnless(issubclass(RQLConstraint, RQLVocabularyConstraint))
+        self.assertFalse(issubclass(RQLUniqueConstraint, RQLVocabularyConstraint))
+        self.assertFalse(issubclass(RQLUniqueConstraint, RQLConstraint))
+        self.assertTrue(issubclass(RQLConstraint, RQLVocabularyConstraint))
 
     def test_entity_perms(self):
         self.assertEqual(eperson.get_groups('read'), set(('managers', 'users', 'guests')))
@@ -193,7 +193,7 @@
                               'fabrique_par', 'final', 'firstname', 'for_user', 'fournit',
                               'from_entity', 'from_state', 'fulltext_container', 'fulltextindexed',
 
-                              'has_text',
+                              'has_group_permission', 'has_text',
                               'identity', 'in_group', 'in_state', 'indexed',
                               'initial_state', 'inlined', 'internationalizable', 'is', 'is_instance_of',
 
@@ -225,12 +225,13 @@
         rels = sorted(str(r) for r in eschema.subject_relations())
         self.assertListEqual(rels, ['created_by', 'creation_date', 'custom_workflow',
                                     'cw_source', 'cwuri', 'eid',
-                                     'evaluee', 'firstname', 'has_text', 'identity',
-                                     'in_group', 'in_state', 'is',
-                                     'is_instance_of', 'last_login_time',
-                                     'login', 'modification_date', 'owned_by',
-                                     'primary_email', 'surname', 'upassword',
-                                     'use_email'])
+                                    'evaluee', 'firstname', 'has_group_permission',
+                                    'has_text', 'identity',
+                                    'in_group', 'in_state', 'is',
+                                    'is_instance_of', 'last_login_time',
+                                    'login', 'modification_date', 'owned_by',
+                                    'primary_email', 'surname', 'upassword',
+                                    'use_email'])
         rels = sorted(r.type for r in eschema.object_relations())
         self.assertListEqual(rels, ['bookmarked_by', 'created_by', 'for_user',
                                      'identity', 'owned_by', 'wf_info_for'])
@@ -238,15 +239,15 @@
         properties = rschema.rdef('CWAttribute', 'CWRType')
         self.assertEqual(properties.cardinality, '1*')
         constraints = properties.constraints
-        self.failUnlessEqual(len(constraints), 1, constraints)
+        self.assertEqual(len(constraints), 1, constraints)
         constraint = constraints[0]
-        self.failUnless(isinstance(constraint, RQLConstraint))
-        self.failUnlessEqual(constraint.expression, 'O final TRUE')
+        self.assertTrue(isinstance(constraint, RQLConstraint))
+        self.assertEqual(constraint.expression, 'O final TRUE')
 
     def test_fulltext_container(self):
         schema = loader.load(config)
-        self.failUnless('has_text' in schema['CWUser'].subject_relations())
-        self.failIf('has_text' in schema['EmailAddress'].subject_relations())
+        self.assertTrue('has_text' in schema['CWUser'].subject_relations())
+        self.assertFalse('has_text' in schema['EmailAddress'].subject_relations())
 
     def test_permission_settings(self):
         schema = loader.load(config)
--- a/test/unittest_selectors.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/test/unittest_selectors.py	Fri Oct 14 09:21:45 2011 +0200
@@ -87,11 +87,11 @@
 
     def test_composition(self):
         selector = (_1_() & _1_()) & (_1_() & _1_())
-        self.failUnless(isinstance(selector, AndSelector))
+        self.assertTrue(isinstance(selector, AndSelector))
         self.assertEqual(len(selector.selectors), 4)
         self.assertEqual(selector(None), 4)
         selector = (_1_() & _0_()) | (_1_() & _1_())
-        self.failUnless(isinstance(selector, OrSelector))
+        self.assertTrue(isinstance(selector, OrSelector))
         self.assertEqual(len(selector.selectors), 2)
         self.assertEqual(selector(None), 2)
 
@@ -151,13 +151,13 @@
         rset = f.as_rset()
         anyscore = is_instance('Any')(f.__class__, req, rset=rset)
         idownscore = adaptable('IDownloadable')(f.__class__, req, rset=rset)
-        self.failUnless(idownscore > anyscore, (idownscore, anyscore))
+        self.assertTrue(idownscore > anyscore, (idownscore, anyscore))
         filescore = is_instance('File')(f.__class__, req, rset=rset)
-        self.failUnless(filescore > idownscore, (filescore, idownscore))
+        self.assertTrue(filescore > idownscore, (filescore, idownscore))
 
     def test_etype_inheritance_no_yams_inheritance(self):
         cls = self.vreg['etypes'].etype_class('Personne')
-        self.failIf(is_instance('Societe').score_class(cls, self.request()))
+        self.assertFalse(is_instance('Societe').score_class(cls, self.request()))
 
     def test_yams_inheritance(self):
         cls = self.vreg['etypes'].etype_class('Transition')
@@ -321,7 +321,7 @@
         self.vreg._loadedmods[__name__] = {}
         self.vreg.register(SomeAction)
         SomeAction.__registered__(self.vreg['actions'])
-        self.failUnless(SomeAction in self.vreg['actions']['yo'], self.vreg['actions'])
+        self.assertTrue(SomeAction in self.vreg['actions']['yo'], self.vreg['actions'])
         try:
             # login as a simple user
             req = self.request()
@@ -330,18 +330,18 @@
             # it should not be possible to use SomeAction not owned objects
             req = self.request()
             rset = req.execute('Any G WHERE G is CWGroup, G name "managers"')
-            self.failIf('yo' in dict(self.pactions(req, rset)))
+            self.assertFalse('yo' in dict(self.pactions(req, rset)))
             # insert a new card, and check that we can use SomeAction on our object
             self.execute('INSERT Card C: C title "zoubidou"')
             self.commit()
             req = self.request()
             rset = req.execute('Card C WHERE C title "zoubidou"')
-            self.failUnless('yo' in dict(self.pactions(req, rset)), self.pactions(req, rset))
+            self.assertTrue('yo' in dict(self.pactions(req, rset)), self.pactions(req, rset))
             # make sure even managers can't use the action
             self.restore_connection()
             req = self.request()
             rset = req.execute('Card C WHERE C title "zoubidou"')
-            self.failIf('yo' in dict(self.pactions(req, rset)))
+            self.assertFalse('yo' in dict(self.pactions(req, rset)))
         finally:
             del self.vreg[SomeAction.__registry__][SomeAction.__regid__]
 
--- a/test/unittest_utils.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/test/unittest_utils.py	Fri Oct 14 09:21:45 2011 +0200
@@ -67,7 +67,7 @@
         # XXX
         self.assertEqual(l[4], (1, 3))
 
-        self.failIf(RepeatList(0, None))
+        self.assertFalse(RepeatList(0, None))
 
     def test_slice(self):
         l = RepeatList(3, (1, 3))
@@ -159,9 +159,17 @@
         self.assertEqual(self.encode(TestCase), 'null')
 
 class HTMLHeadTC(CubicWebTC):
+
+    def htmlhead(self, datadir_url):
+        req = self.request()
+        base_url = u'http://test.fr/data/'
+        req.datadir_url = base_url
+        head = HTMLHead(req)
+        return head
+
     def test_concat_urls(self):
         base_url = u'http://test.fr/data/'
-        head = HTMLHead(base_url)
+        head = self.htmlhead(base_url)
         urls = [base_url + u'bob1.js',
                 base_url + u'bob2.js',
                 base_url + u'bob3.js']
@@ -171,7 +179,7 @@
 
     def test_group_urls(self):
         base_url = u'http://test.fr/data/'
-        head = HTMLHead(base_url)
+        head = self.htmlhead(base_url)
         urls_spec = [(base_url + u'bob0.js', None),
                      (base_url + u'bob1.js', None),
                      (u'http://ext.com/bob2.js', None),
@@ -196,7 +204,7 @@
 
     def test_getvalue_with_concat(self):
         base_url = u'http://test.fr/data/'
-        head = HTMLHead(base_url)
+        head = self.htmlhead(base_url)
         head.add_js(base_url + u'bob0.js')
         head.add_js(base_url + u'bob1.js')
         head.add_js(u'http://ext.com/bob2.js')
@@ -224,20 +232,22 @@
         self.assertEqual(result, expected)
 
     def test_getvalue_without_concat(self):
-        base_url = u'http://test.fr/data/'
-        head = HTMLHead()
-        head.add_js(base_url + u'bob0.js')
-        head.add_js(base_url + u'bob1.js')
-        head.add_js(u'http://ext.com/bob2.js')
-        head.add_js(u'http://ext.com/bob3.js')
-        head.add_css(base_url + u'bob4.css')
-        head.add_css(base_url + u'bob5.css')
-        head.add_css(base_url + u'bob6.css', 'print')
-        head.add_css(base_url + u'bob7.css', 'print')
-        head.add_ie_css(base_url + u'bob8.css')
-        head.add_ie_css(base_url + u'bob9.css', 'print', u'[if lt IE 7]')
-        result = head.getvalue()
-        expected = u"""<head>
+        self.config.global_set_option('concat-resources', False)
+        try:
+            base_url = u'http://test.fr/data/'
+            head = self.htmlhead(base_url)
+            head.add_js(base_url + u'bob0.js')
+            head.add_js(base_url + u'bob1.js')
+            head.add_js(u'http://ext.com/bob2.js')
+            head.add_js(u'http://ext.com/bob3.js')
+            head.add_css(base_url + u'bob4.css')
+            head.add_css(base_url + u'bob5.css')
+            head.add_css(base_url + u'bob6.css', 'print')
+            head.add_css(base_url + u'bob7.css', 'print')
+            head.add_ie_css(base_url + u'bob8.css')
+            head.add_ie_css(base_url + u'bob9.css', 'print', u'[if lt IE 7]')
+            result = head.getvalue()
+            expected = u"""<head>
 <link rel="stylesheet" type="text/css" media="all" href="http://test.fr/data/bob4.css"/>
 <link rel="stylesheet" type="text/css" media="all" href="http://test.fr/data/bob5.css"/>
 <link rel="stylesheet" type="text/css" media="print" href="http://test.fr/data/bob6.css"/>
@@ -253,7 +263,9 @@
 <script type="text/javascript" src="http://ext.com/bob3.js"></script>
 </head>
 """
-        self.assertEqual(result, expected)
+            self.assertEqual(result, expected)
+        finally:
+            self.config.global_set_option('concat-resources', True)
 
 class DocTest(DocTest):
     from cubicweb import utils as module
--- a/test/unittest_vregistry.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/test/unittest_vregistry.py	Fri Oct 14 09:21:45 2011 +0200
@@ -56,7 +56,7 @@
     def test_load_subinterface_based_appobjects(self):
         self.vreg.register_objects([join(BASE, 'web', 'views', 'iprogress.py')])
         # check progressbar was kicked
-        self.failIf(self.vreg['views'].get('progressbar'))
+        self.assertFalse(self.vreg['views'].get('progressbar'))
         # we've to emulate register_objects to add custom MyCard objects
         path = [join(BASE, 'entities', '__init__.py'),
                 join(BASE, 'entities', 'adapters.py'),
@@ -74,8 +74,8 @@
 
     def test_properties(self):
         self.vreg.reset()
-        self.failIf('system.version.cubicweb' in self.vreg['propertydefs'])
-        self.failUnless(self.vreg.property_info('system.version.cubicweb'))
+        self.assertFalse('system.version.cubicweb' in self.vreg['propertydefs'])
+        self.assertTrue(self.vreg.property_info('system.version.cubicweb'))
         self.assertRaises(UnknownProperty, self.vreg.property_info, 'a.non.existent.key')
 
 
--- a/toolsutils.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/toolsutils.py	Fri Oct 14 09:21:45 2011 +0200
@@ -180,7 +180,7 @@
                            'Section %s is defined more than once' % section
                     config[section] = current = {}
                     continue
-                print >> sys.stderr, 'ignoring malformed line\n%r' % line
+                sys.stderr.write('ignoring malformed line\n%r\n' % line)
                 continue
             option = option.strip().replace(' ', '_')
             value = value.strip()
--- a/uilib.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/uilib.py	Fri Oct 14 09:21:45 2011 +0200
@@ -30,6 +30,7 @@
 
 from logilab.mtconverter import xml_escape, html_unescape
 from logilab.common.date import ustrftime
+from logilab.common.deprecation import deprecated
 
 from cubicweb.utils import JSString, json_dumps
 
@@ -79,6 +80,39 @@
         return ustrftime(value, req.property_value('ui.datetime-format')) + u' UTC'
     return ustrftime(value, req.property_value('ui.date-format'))
 
+_('%d years')
+_('%d months')
+_('%d weeks')
+_('%d days')
+_('%d hours')
+_('%d minutes')
+_('%d seconds')
+
+def print_timedelta(value, req, props, displaytime=True):
+    if isinstance(value, (int, long)):
+        # `date - date`, unlike `datetime - datetime` gives an int
+        # (number of days), not a timedelta
+        # XXX should rql be fixed to return Int instead of Interval in
+        #     that case? that would be probably the proper fix but we
+        #     loose information on the way...
+        value = timedelta(days=value)
+    if value.days > 730 or value.days < -730: # 2 years
+        return req._('%d years') % (value.days // 365)
+    elif value.days > 60 or value.days < -60: # 2 months
+        return req._('%d months') % (value.days // 30)
+    elif value.days > 14 or value.days < -14: # 2 weeks
+        return req._('%d weeks') % (value.days // 7)
+    elif value.days > 2 or value.days < -2:
+        return req._('%d days') % int(value.days)
+    else:
+        minus = 1 if value.days > 0 else -1
+        if value.seconds > 3600:
+            return req._('%d hours') % (int(value.seconds // 3600) * minus)
+        elif value.seconds >= 120:
+            return req._('%d minutes') % (int(value.seconds // 60) * minus)
+        else:
+            return req._('%d seconds') % (int(value.seconds) * minus)
+
 def print_boolean(value, req, props, displaytime=True):
     if value:
         return req._('yes')
@@ -98,18 +132,12 @@
     'Boolean': print_boolean,
     'Float': print_float,
     'Decimal': print_float,
-    # XXX Interval
+    'Interval': print_timedelta,
     }
 
+@deprecated('[3.14] use req.printable_value(attrtype, value, ...)')
 def printable_value(req, attrtype, value, props=None, displaytime=True):
-    """return a displayable value (i.e. unicode string)"""
-    if value is None:
-        return u''
-    try:
-        printer = PRINTERS[attrtype]
-    except KeyError:
-        return unicode(value)
-    return printer(value, req, props, displaytime)
+    return req.printable_value(attrtype, value, props, displaytime)
 
 
 # text publishing #############################################################
--- a/utils.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/utils.py	Fri Oct 14 09:21:45 2011 +0200
@@ -227,7 +227,7 @@
     xhtml_safe_script_opening = u'<script type="text/javascript"><!--//--><![CDATA[//><!--\n'
     xhtml_safe_script_closing = u'\n//--><!]]></script>'
 
-    def __init__(self, datadir_url=None):
+    def __init__(self, req):
         super(HTMLHead, self).__init__()
         self.jsvars = []
         self.jsfiles = []
@@ -235,8 +235,8 @@
         self.ie_cssfiles = []
         self.post_inlined_scripts = []
         self.pagedata_unload = False
-        self.datadir_url = datadir_url
-
+        self._cw = req
+        self.datadir_url = req.datadir_url
 
     def add_raw(self, rawheader):
         self.write(rawheader)
@@ -348,20 +348,26 @@
                 w(vardecl + u'\n')
             w(self.xhtml_safe_script_closing)
         # 2/ css files
-        for cssfile, media in (self.group_urls(self.cssfiles) if self.datadir_url else self.cssfiles):
+        ie_cssfiles = ((x, (y, z)) for x, y, z in self.ie_cssfiles)
+        if self.datadir_url and self._cw.vreg.config['concat-resources']:
+            cssfiles = self.group_urls(self.cssfiles)
+            ie_cssfiles = self.group_urls(ie_cssfiles)
+            jsfiles = (x for x, _ in self.group_urls((x, None) for x in self.jsfiles))
+        else:
+            cssfiles = self.cssfiles
+            jsfiles = self.jsfiles
+        for cssfile, media in cssfiles:
             w(u'<link rel="stylesheet" type="text/css" media="%s" href="%s"/>\n' %
               (media, xml_escape(cssfile)))
         # 3/ ie css if necessary
-        if self.ie_cssfiles:
-            ie_cssfiles = ((x, (y, z)) for x, y, z in self.ie_cssfiles)
-            for cssfile, (media, iespec) in (self.group_urls(ie_cssfiles) if self.datadir_url else ie_cssfiles):
+        if self.ie_cssfiles: # use self.ie_cssfiles because `ie_cssfiles` is a genexp
+            for cssfile, (media, iespec) in ie_cssfiles:
                 w(u'<!--%s>\n' % iespec)
                 w(u'<link rel="stylesheet" type="text/css" media="%s" href="%s"/>\n' %
                   (media, xml_escape(cssfile)))
             w(u'<![endif]--> \n')
         # 4/ js files
-        jsfiles = ((x, None) for x in self.jsfiles)
-        for jsfile, media in self.group_urls(jsfiles) if self.datadir_url else jsfiles:
+        for jsfile in jsfiles:
             if skiphead:
                 # Don't insert <script> tags directly as they would be
                 # interpreted directly by some browsers (e.g. IE).
@@ -473,10 +479,8 @@
         """define a json encoder to be able to encode yams std types"""
 
         def default(self, obj):
-            if hasattr(obj, 'eid'):
-                d = obj.cw_attr_cache.copy()
-                d['eid'] = obj.eid
-                return d
+            if hasattr(obj, '__json_encode__'):
+                return obj.__json_encode__()
             if isinstance(obj, datetime.datetime):
                 return ustrftime(obj, '%Y/%m/%d %H:%M:%S')
             elif isinstance(obj, datetime.date):
@@ -494,8 +498,8 @@
                 # just return None in those cases.
                 return None
 
-    def json_dumps(value):
-        return json.dumps(value, cls=CubicWebJsonEncoder)
+    def json_dumps(value, **kwargs):
+        return json.dumps(value, cls=CubicWebJsonEncoder, **kwargs)
 
 
     class JSString(str):
--- a/web/application.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/application.py	Fri Oct 14 09:21:45 2011 +0200
@@ -23,6 +23,7 @@
 
 import sys
 from time import clock, time
+from contextlib import contextmanager
 
 from logilab.common.deprecation import deprecated
 
@@ -32,7 +33,7 @@
 from cubicweb import (
     ValidationError, Unauthorized, AuthenticationError, NoSelectableObject,
     BadConnectionId, CW_EVENT_MANAGER)
-from cubicweb.dbapi import DBAPISession
+from cubicweb.dbapi import DBAPISession, anonymous_session
 from cubicweb.web import LOGGER, component
 from cubicweb.web import (
     StatusResponse, DirectResponse, Redirect, NotFound, LogOut,
@@ -42,6 +43,16 @@
 # print information about web session
 SESSION_MANAGER = None
 
+
+@contextmanager
+def anonymized_request(req):
+    orig_session = req.session
+    req.set_session(anonymous_session(req.vreg))
+    try:
+        yield req
+    finally:
+        req.set_session(orig_session)
+
 class AbstractSessionManager(component.Component):
     """manage session data associated to a session identifier"""
     __regid__ = 'sessionmanager'
--- a/web/data/cubicweb.facets.css	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/data/cubicweb.facets.css	Fri Oct 14 09:21:45 2011 +0200
@@ -4,17 +4,16 @@
 }
 
 div.facet {
- margin-bottom: 8px;
  background: #fff;
  padding: 5px;
- min-width: 10em;
+ margin: .3em!important;
 }
 
 div.facetTitle, div.bkSearch  {
- font-size: 80%;
  color: #000;
  margin-bottom: 2px;
  cursor: pointer;
+ font-weight: bold;
  font: %(facet_titleFont)s;
 }
 
@@ -23,45 +22,41 @@
  background: transparent url("puce.png") 0% 50% no-repeat;
  }
 
-div.facetBody {
-}
-
-.opened{
+.opened {
  color: #000 !important;
 }
 
-div.overflowed {
+div.vocabularyFacetBody {
   height: %(facet_overflowedHeight)s;
+}
+
+div.vocabularyFacetBodyWithLogicalSelector {
+  height: %(facet_overflowedHeightWithLogicalSelector)s;
+}
+
+div.vocabularyFacet {
   overflow-y: auto;
+  overflow-x: hidden;
 }
 
 div.facetCheckBox {
   clear: both;
   cursor: pointer;
-}
-
-div.facetCheckBox a {
- text-decoration: none;
- font-size: 85%;
+  text-decoration: none;
 }
 
 div.facetValue{
-clear: both
-}
-
-div.facetValue img{
- float: left;
- background: #fff;
+  padding-left: 2px;
+  clear: both
 }
 
-div.facetValue a {
- margin-left: 20px;
- display: block;
- margin-top: -6px; /* FIXME why do we need this ? */
+div.facetValue img {
+  float: left;
+  background: #fff;
 }
 
-div.facetValueSelected a {
-  font-weight: bold;
+div.facetValueSelected {
+  background: #EBE8D9;
 }
 
 #leftcol label {
@@ -77,35 +72,26 @@
   border: none;
 }
 
-
-div.facetCheckBox{
- line-height:0.8em;
- }
-
 .facet input{
  margin-top:3px;
  border:1px solid #ccc;
  font-size:11px;
- }
+}
 
-
-.facetValueDisabled {
+.facetValueDisabled span {
   font-style: italic;
   text-decoration: line-through;
 }
 
-
 div#filterboxTitle {
   margin-top: 50px;
   margin-bottom: 1em;
   color: #1190A1;
   font-size: 75%;
-  font-weight: bold;
   padding: 0.15em;
   text-transform: uppercase;
 }
 
-
 div#facetLoading {
   display: none;
   position: fixed;
@@ -126,8 +112,3 @@
   background-color: #EBE8D9;
   border: dotted grey 1px;
 }
-
-div.facet {
- padding: none;
- margin: .3em!important;
-}
--- a/web/data/cubicweb.facets.js	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/data/cubicweb.facets.js	Fri Oct 14 09:21:45 2011 +0200
@@ -49,6 +49,7 @@
 }
 
 
+// XXX deprecate vidargs once TableView is gone
 function buildRQL(divid, vid, paginate, vidargs) {
     jQuery(CubicWeb).trigger('facets-content-loading', [divid, vid, paginate, vidargs]);
     var $form = $('#' + divid + 'Form');
@@ -77,7 +78,7 @@
         copyParam(zipped, extraparams, 'vid');
         extraparams['divid'] = divid;
         copyParam(zipped, extraparams, 'divid');
-        copyParam(zipped, extraparams, 'subvid');
+        copyParam(zipped, extraparams, 'subvid'); // XXX deprecate once TableView is gone
         copyParam(zipped, extraparams, 'fromformfilter');
         // paginate used to know if the filter box is acting, in which case we
         // want to reload action box to match current selection (we don't want
--- a/web/data/cubicweb.js	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/data/cubicweb.js	Fri Oct 14 09:21:45 2011 +0200
@@ -82,6 +82,15 @@
         }
         return src;
     }
+
+
+    sortValueExtraction: function (node) {
+	var sortvalue = jQuery(node).attr('cubicweb:sortvalue');
+	if (sortvalue === undefined) {
+	    return '';
+	}
+	return sortvalue;
+}
 });
 
 
--- a/web/data/cubicweb.widgets.js	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/data/cubicweb.widgets.js	Fri Oct 14 09:21:45 2011 +0200
@@ -40,10 +40,6 @@
     });
 }
 
-// we need to differenciate cases where initFacetBoxEvents is called
-// with one argument or without any argument. If we use `initFacetBoxEvents`
-// as the direct callback on the jQuery.ready event, jQuery will pass some argument
-// of his, so we use this small anonymous function instead.
 jQuery(document).ready(function() {
     buildWidgets();
 });
--- a/web/data/jquery.js	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/data/jquery.js	Fri Oct 14 09:21:45 2011 +0200
@@ -1,154 +1,9046 @@
 /*!
- * jQuery JavaScript Library v1.4.2
+ * jQuery JavaScript Library v1.6.4
  * http://jquery.com/
  *
- * Copyright 2010, John Resig
+ * Copyright 2011, John Resig
  * Dual licensed under the MIT or GPL Version 2 licenses.
  * http://jquery.org/license
  *
  * Includes Sizzle.js
  * http://sizzlejs.com/
- * Copyright 2010, The Dojo Foundation
+ * Copyright 2011, The Dojo Foundation
  * Released under the MIT, BSD, and GPL Licenses.
  *
- * Date: Sat Feb 13 22:33:48 2010 -0500
+ * Date: Mon Sep 12 18:54:48 2011 -0400
+ */
+(function( window, undefined ) {
+
+// Use the correct document accordingly with window argument (sandbox)
+var document = window.document,
+	navigator = window.navigator,
+	location = window.location;
+var jQuery = (function() {
+
+// Define a local copy of jQuery
+var jQuery = function( selector, context ) {
+		// The jQuery object is actually just the init constructor 'enhanced'
+		return new jQuery.fn.init( selector, context, rootjQuery );
+	},
+
+	// Map over jQuery in case of overwrite
+	_jQuery = window.jQuery,
+
+	// Map over the $ in case of overwrite
+	_$ = window.$,
+
+	// A central reference to the root jQuery(document)
+	rootjQuery,
+
+	// A simple way to check for HTML strings or ID strings
+	// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
+	quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
+
+	// Check if a string has a non-whitespace character in it
+	rnotwhite = /\S/,
+
+	// Used for trimming whitespace
+	trimLeft = /^\s+/,
+	trimRight = /\s+$/,
+
+	// Check for digits
+	rdigit = /\d/,
+
+	// Match a standalone tag
+	rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,
+
+	// JSON RegExp
+	rvalidchars = /^[\],:{}\s]*$/,
+	rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
+	rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
+	rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
+
+	// Useragent RegExp
+	rwebkit = /(webkit)[ \/]([\w.]+)/,
+	ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
+	rmsie = /(msie) ([\w.]+)/,
+	rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,
+
+	// Matches dashed string for camelizing
+	rdashAlpha = /-([a-z]|[0-9])/ig,
+	rmsPrefix = /^-ms-/,
+
+	// Used by jQuery.camelCase as callback to replace()
+	fcamelCase = function( all, letter ) {
+		return ( letter + "" ).toUpperCase();
+	},
+
+	// Keep a UserAgent string for use with jQuery.browser
+	userAgent = navigator.userAgent,
+
+	// For matching the engine and version of the browser
+	browserMatch,
+
+	// The deferred used on DOM ready
+	readyList,
+
+	// The ready event handler
+	DOMContentLoaded,
+
+	// Save a reference to some core methods
+	toString = Object.prototype.toString,
+	hasOwn = Object.prototype.hasOwnProperty,
+	push = Array.prototype.push,
+	slice = Array.prototype.slice,
+	trim = String.prototype.trim,
+	indexOf = Array.prototype.indexOf,
+
+	// [[Class]] -> type pairs
+	class2type = {};
+
+jQuery.fn = jQuery.prototype = {
+	constructor: jQuery,
+	init: function( selector, context, rootjQuery ) {
+		var match, elem, ret, doc;
+
+		// Handle $(""), $(null), or $(undefined)
+		if ( !selector ) {
+			return this;
+		}
+
+		// Handle $(DOMElement)
+		if ( selector.nodeType ) {
+			this.context = this[0] = selector;
+			this.length = 1;
+			return this;
+		}
+
+		// The body element only exists once, optimize finding it
+		if ( selector === "body" && !context && document.body ) {
+			this.context = document;
+			this[0] = document.body;
+			this.selector = selector;
+			this.length = 1;
+			return this;
+		}
+
+		// Handle HTML strings
+		if ( typeof selector === "string" ) {
+			// Are we dealing with HTML string or an ID?
+			if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
+				// Assume that strings that start and end with <> are HTML and skip the regex check
+				match = [ null, selector, null ];
+
+			} else {
+				match = quickExpr.exec( selector );
+			}
+
+			// Verify a match, and that no context was specified for #id
+			if ( match && (match[1] || !context) ) {
+
+				// HANDLE: $(html) -> $(array)
+				if ( match[1] ) {
+					context = context instanceof jQuery ? context[0] : context;
+					doc = (context ? context.ownerDocument || context : document);
+
+					// If a single string is passed in and it's a single tag
+					// just do a createElement and skip the rest
+					ret = rsingleTag.exec( selector );
+
+					if ( ret ) {
+						if ( jQuery.isPlainObject( context ) ) {
+							selector = [ document.createElement( ret[1] ) ];
+							jQuery.fn.attr.call( selector, context, true );
+
+						} else {
+							selector = [ doc.createElement( ret[1] ) ];
+						}
+
+					} else {
+						ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
+						selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes;
+					}
+
+					return jQuery.merge( this, selector );
+
+				// HANDLE: $("#id")
+				} else {
+					elem = document.getElementById( match[2] );
+
+					// Check parentNode to catch when Blackberry 4.6 returns
+					// nodes that are no longer in the document #6963
+					if ( elem && elem.parentNode ) {
+						// Handle the case where IE and Opera return items
+						// by name instead of ID
+						if ( elem.id !== match[2] ) {
+							return rootjQuery.find( selector );
+						}
+
+						// Otherwise, we inject the element directly into the jQuery object
+						this.length = 1;
+						this[0] = elem;
+					}
+
+					this.context = document;
+					this.selector = selector;
+					return this;
+				}
+
+			// HANDLE: $(expr, $(...))
+			} else if ( !context || context.jquery ) {
+				return (context || rootjQuery).find( selector );
+
+			// HANDLE: $(expr, context)
+			// (which is just equivalent to: $(context).find(expr)
+			} else {
+				return this.constructor( context ).find( selector );
+			}
+
+		// HANDLE: $(function)
+		// Shortcut for document ready
+		} else if ( jQuery.isFunction( selector ) ) {
+			return rootjQuery.ready( selector );
+		}
+
+		if (selector.selector !== undefined) {
+			this.selector = selector.selector;
+			this.context = selector.context;
+		}
+
+		return jQuery.makeArray( selector, this );
+	},
+
+	// Start with an empty selector
+	selector: "",
+
+	// The current version of jQuery being used
+	jquery: "1.6.4",
+
+	// The default length of a jQuery object is 0
+	length: 0,
+
+	// The number of elements contained in the matched element set
+	size: function() {
+		return this.length;
+	},
+
+	toArray: function() {
+		return slice.call( this, 0 );
+	},
+
+	// Get the Nth element in the matched element set OR
+	// Get the whole matched element set as a clean array
+	get: function( num ) {
+		return num == null ?
+
+			// Return a 'clean' array
+			this.toArray() :
+
+			// Return just the object
+			( num < 0 ? this[ this.length + num ] : this[ num ] );
+	},
+
+	// Take an array of elements and push it onto the stack
+	// (returning the new matched element set)
+	pushStack: function( elems, name, selector ) {
+		// Build a new jQuery matched element set
+		var ret = this.constructor();
+
+		if ( jQuery.isArray( elems ) ) {
+			push.apply( ret, elems );
+
+		} else {
+			jQuery.merge( ret, elems );
+		}
+
+		// Add the old object onto the stack (as a reference)
+		ret.prevObject = this;
+
+		ret.context = this.context;
+
+		if ( name === "find" ) {
+			ret.selector = this.selector + (this.selector ? " " : "") + selector;
+		} else if ( name ) {
+			ret.selector = this.selector + "." + name + "(" + selector + ")";
+		}
+
+		// Return the newly-formed element set
+		return ret;
+	},
+
+	// Execute a callback for every element in the matched set.
+	// (You can seed the arguments with an array of args, but this is
+	// only used internally.)
+	each: function( callback, args ) {
+		return jQuery.each( this, callback, args );
+	},
+
+	ready: function( fn ) {
+		// Attach the listeners
+		jQuery.bindReady();
+
+		// Add the callback
+		readyList.done( fn );
+
+		return this;
+	},
+
+	eq: function( i ) {
+		return i === -1 ?
+			this.slice( i ) :
+			this.slice( i, +i + 1 );
+	},
+
+	first: function() {
+		return this.eq( 0 );
+	},
+
+	last: function() {
+		return this.eq( -1 );
+	},
+
+	slice: function() {
+		return this.pushStack( slice.apply( this, arguments ),
+			"slice", slice.call(arguments).join(",") );
+	},
+
+	map: function( callback ) {
+		return this.pushStack( jQuery.map(this, function( elem, i ) {
+			return callback.call( elem, i, elem );
+		}));
+	},
+
+	end: function() {
+		return this.prevObject || this.constructor(null);
+	},
+
+	// For internal use only.
+	// Behaves like an Array's method, not like a jQuery method.
+	push: push,
+	sort: [].sort,
+	splice: [].splice
+};
+
+// Give the init function the jQuery prototype for later instantiation
+jQuery.fn.init.prototype = jQuery.fn;
+
+jQuery.extend = jQuery.fn.extend = function() {
+	var options, name, src, copy, copyIsArray, clone,
+		target = arguments[0] || {},
+		i = 1,
+		length = arguments.length,
+		deep = false;
+
+	// Handle a deep copy situation
+	if ( typeof target === "boolean" ) {
+		deep = target;
+		target = arguments[1] || {};
+		// skip the boolean and the target
+		i = 2;
+	}
+
+	// Handle case when target is a string or something (possible in deep copy)
+	if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
+		target = {};
+	}
+
+	// extend jQuery itself if only one argument is passed
+	if ( length === i ) {
+		target = this;
+		--i;
+	}
+
+	for ( ; i < length; i++ ) {
+		// Only deal with non-null/undefined values
+		if ( (options = arguments[ i ]) != null ) {
+			// Extend the base object
+			for ( name in options ) {
+				src = target[ name ];
+				copy = options[ name ];
+
+				// Prevent never-ending loop
+				if ( target === copy ) {
+					continue;
+				}
+
+				// Recurse if we're merging plain objects or arrays
+				if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
+					if ( copyIsArray ) {
+						copyIsArray = false;
+						clone = src && jQuery.isArray(src) ? src : [];
+
+					} else {
+						clone = src && jQuery.isPlainObject(src) ? src : {};
+					}
+
+					// Never move original objects, clone them
+					target[ name ] = jQuery.extend( deep, clone, copy );
+
+				// Don't bring in undefined values
+				} else if ( copy !== undefined ) {
+					target[ name ] = copy;
+				}
+			}
+		}
+	}
+
+	// Return the modified object
+	return target;
+};
+
+jQuery.extend({
+	noConflict: function( deep ) {
+		if ( window.$ === jQuery ) {
+			window.$ = _$;
+		}
+
+		if ( deep && window.jQuery === jQuery ) {
+			window.jQuery = _jQuery;
+		}
+
+		return jQuery;
+	},
+
+	// Is the DOM ready to be used? Set to true once it occurs.
+	isReady: false,
+
+	// A counter to track how many items to wait for before
+	// the ready event fires. See #6781
+	readyWait: 1,
+
+	// Hold (or release) the ready event
+	holdReady: function( hold ) {
+		if ( hold ) {
+			jQuery.readyWait++;
+		} else {
+			jQuery.ready( true );
+		}
+	},
+
+	// Handle when the DOM is ready
+	ready: function( wait ) {
+		// Either a released hold or an DOMready/load event and not yet ready
+		if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) {
+			// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
+			if ( !document.body ) {
+				return setTimeout( jQuery.ready, 1 );
+			}
+
+			// Remember that the DOM is ready
+			jQuery.isReady = true;
+
+			// If a normal DOM Ready event fired, decrement, and wait if need be
+			if ( wait !== true && --jQuery.readyWait > 0 ) {
+				return;
+			}
+
+			// If there are functions bound, to execute
+			readyList.resolveWith( document, [ jQuery ] );
+
+			// Trigger any bound ready events
+			if ( jQuery.fn.trigger ) {
+				jQuery( document ).trigger( "ready" ).unbind( "ready" );
+			}
+		}
+	},
+
+	bindReady: function() {
+		if ( readyList ) {
+			return;
+		}
+
+		readyList = jQuery._Deferred();
+
+		// Catch cases where $(document).ready() is called after the
+		// browser event has already occurred.
+		if ( document.readyState === "complete" ) {
+			// Handle it asynchronously to allow scripts the opportunity to delay ready
+			return setTimeout( jQuery.ready, 1 );
+		}
+
+		// Mozilla, Opera and webkit nightlies currently support this event
+		if ( document.addEventListener ) {
+			// Use the handy event callback
+			document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
+
+			// A fallback to window.onload, that will always work
+			window.addEventListener( "load", jQuery.ready, false );
+
+		// If IE event model is used
+		} else if ( document.attachEvent ) {
+			// ensure firing before onload,
+			// maybe late but safe also for iframes
+			document.attachEvent( "onreadystatechange", DOMContentLoaded );
+
+			// A fallback to window.onload, that will always work
+			window.attachEvent( "onload", jQuery.ready );
+
+			// If IE and not a frame
+			// continually check to see if the document is ready
+			var toplevel = false;
+
+			try {
+				toplevel = window.frameElement == null;
+			} catch(e) {}
+
+			if ( document.documentElement.doScroll && toplevel ) {
+				doScrollCheck();
+			}
+		}
+	},
+
+	// See test/unit/core.js for details concerning isFunction.
+	// Since version 1.3, DOM methods and functions like alert
+	// aren't supported. They return false on IE (#2968).
+	isFunction: function( obj ) {
+		return jQuery.type(obj) === "function";
+	},
+
+	isArray: Array.isArray || function( obj ) {
+		return jQuery.type(obj) === "array";
+	},
+
+	// A crude way of determining if an object is a window
+	isWindow: function( obj ) {
+		return obj && typeof obj === "object" && "setInterval" in obj;
+	},
+
+	isNaN: function( obj ) {
+		return obj == null || !rdigit.test( obj ) || isNaN( obj );
+	},
+
+	type: function( obj ) {
+		return obj == null ?
+			String( obj ) :
+			class2type[ toString.call(obj) ] || "object";
+	},
+
+	isPlainObject: function( obj ) {
+		// Must be an Object.
+		// Because of IE, we also have to check the presence of the constructor property.
+		// Make sure that DOM nodes and window objects don't pass through, as well
+		if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
+			return false;
+		}
+
+		try {
+			// Not own constructor property must be Object
+			if ( obj.constructor &&
+				!hasOwn.call(obj, "constructor") &&
+				!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
+				return false;
+			}
+		} catch ( e ) {
+			// IE8,9 Will throw exceptions on certain host objects #9897
+			return false;
+		}
+
+		// Own properties are enumerated firstly, so to speed up,
+		// if last one is own, then all properties are own.
+
+		var key;
+		for ( key in obj ) {}
+
+		return key === undefined || hasOwn.call( obj, key );
+	},
+
+	isEmptyObject: function( obj ) {
+		for ( var name in obj ) {
+			return false;
+		}
+		return true;
+	},
+
+	error: function( msg ) {
+		throw msg;
+	},
+
+	parseJSON: function( data ) {
+		if ( typeof data !== "string" || !data ) {
+			return null;
+		}
+
+		// Make sure leading/trailing whitespace is removed (IE can't handle it)
+		data = jQuery.trim( data );
+
+		// Attempt to parse using the native JSON parser first
+		if ( window.JSON && window.JSON.parse ) {
+			return window.JSON.parse( data );
+		}
+
+		// Make sure the incoming data is actual JSON
+		// Logic borrowed from http://json.org/json2.js
+		if ( rvalidchars.test( data.replace( rvalidescape, "@" )
+			.replace( rvalidtokens, "]" )
+			.replace( rvalidbraces, "")) ) {
+
+			return (new Function( "return " + data ))();
+
+		}
+		jQuery.error( "Invalid JSON: " + data );
+	},
+
+	// Cross-browser xml parsing
+	parseXML: function( data ) {
+		var xml, tmp;
+		try {
+			if ( window.DOMParser ) { // Standard
+				tmp = new DOMParser();
+				xml = tmp.parseFromString( data , "text/xml" );
+			} else { // IE
+				xml = new ActiveXObject( "Microsoft.XMLDOM" );
+				xml.async = "false";
+				xml.loadXML( data );
+			}
+		} catch( e ) {
+			xml = undefined;
+		}
+		if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
+			jQuery.error( "Invalid XML: " + data );
+		}
+		return xml;
+	},
+
+	noop: function() {},
+
+	// Evaluates a script in a global context
+	// Workarounds based on findings by Jim Driscoll
+	// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
+	globalEval: function( data ) {
+		if ( data && rnotwhite.test( data ) ) {
+			// We use execScript on Internet Explorer
+			// We use an anonymous function so that context is window
+			// rather than jQuery in Firefox
+			( window.execScript || function( data ) {
+				window[ "eval" ].call( window, data );
+			} )( data );
+		}
+	},
+
+	// Convert dashed to camelCase; used by the css and data modules
+	// Microsoft forgot to hump their vendor prefix (#9572)
+	camelCase: function( string ) {
+		return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
+	},
+
+	nodeName: function( elem, name ) {
+		return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
+	},
+
+	// args is for internal usage only
+	each: function( object, callback, args ) {
+		var name, i = 0,
+			length = object.length,
+			isObj = length === undefined || jQuery.isFunction( object );
+
+		if ( args ) {
+			if ( isObj ) {
+				for ( name in object ) {
+					if ( callback.apply( object[ name ], args ) === false ) {
+						break;
+					}
+				}
+			} else {
+				for ( ; i < length; ) {
+					if ( callback.apply( object[ i++ ], args ) === false ) {
+						break;
+					}
+				}
+			}
+
+		// A special, fast, case for the most common use of each
+		} else {
+			if ( isObj ) {
+				for ( name in object ) {
+					if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
+						break;
+					}
+				}
+			} else {
+				for ( ; i < length; ) {
+					if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) {
+						break;
+					}
+				}
+			}
+		}
+
+		return object;
+	},
+
+	// Use native String.trim function wherever possible
+	trim: trim ?
+		function( text ) {
+			return text == null ?
+				"" :
+				trim.call( text );
+		} :
+
+		// Otherwise use our own trimming functionality
+		function( text ) {
+			return text == null ?
+				"" :
+				text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
+		},
+
+	// results is for internal usage only
+	makeArray: function( array, results ) {
+		var ret = results || [];
+
+		if ( array != null ) {
+			// The window, strings (and functions) also have 'length'
+			// The extra typeof function check is to prevent crashes
+			// in Safari 2 (See: #3039)
+			// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
+			var type = jQuery.type( array );
+
+			if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) {
+				push.call( ret, array );
+			} else {
+				jQuery.merge( ret, array );
+			}
+		}
+
+		return ret;
+	},
+
+	inArray: function( elem, array ) {
+		if ( !array ) {
+			return -1;
+		}
+
+		if ( indexOf ) {
+			return indexOf.call( array, elem );
+		}
+
+		for ( var i = 0, length = array.length; i < length; i++ ) {
+			if ( array[ i ] === elem ) {
+				return i;
+			}
+		}
+
+		return -1;
+	},
+
+	merge: function( first, second ) {
+		var i = first.length,
+			j = 0;
+
+		if ( typeof second.length === "number" ) {
+			for ( var l = second.length; j < l; j++ ) {
+				first[ i++ ] = second[ j ];
+			}
+
+		} else {
+			while ( second[j] !== undefined ) {
+				first[ i++ ] = second[ j++ ];
+			}
+		}
+
+		first.length = i;
+
+		return first;
+	},
+
+	grep: function( elems, callback, inv ) {
+		var ret = [], retVal;
+		inv = !!inv;
+
+		// Go through the array, only saving the items
+		// that pass the validator function
+		for ( var i = 0, length = elems.length; i < length; i++ ) {
+			retVal = !!callback( elems[ i ], i );
+			if ( inv !== retVal ) {
+				ret.push( elems[ i ] );
+			}
+		}
+
+		return ret;
+	},
+
+	// arg is for internal usage only
+	map: function( elems, callback, arg ) {
+		var value, key, ret = [],
+			i = 0,
+			length = elems.length,
+			// jquery objects are treated as arrays
+			isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
+
+		// Go through the array, translating each of the items to their
+		if ( isArray ) {
+			for ( ; i < length; i++ ) {
+				value = callback( elems[ i ], i, arg );
+
+				if ( value != null ) {
+					ret[ ret.length ] = value;
+				}
+			}
+
+		// Go through every key on the object,
+		} else {
+			for ( key in elems ) {
+				value = callback( elems[ key ], key, arg );
+
+				if ( value != null ) {
+					ret[ ret.length ] = value;
+				}
+			}
+		}
+
+		// Flatten any nested arrays
+		return ret.concat.apply( [], ret );
+	},
+
+	// A global GUID counter for objects
+	guid: 1,
+
+	// Bind a function to a context, optionally partially applying any
+	// arguments.
+	proxy: function( fn, context ) {
+		if ( typeof context === "string" ) {
+			var tmp = fn[ context ];
+			context = fn;
+			fn = tmp;
+		}
+
+		// Quick check to determine if target is callable, in the spec
+		// this throws a TypeError, but we will just return undefined.
+		if ( !jQuery.isFunction( fn ) ) {
+			return undefined;
+		}
+
+		// Simulated bind
+		var args = slice.call( arguments, 2 ),
+			proxy = function() {
+				return fn.apply( context, args.concat( slice.call( arguments ) ) );
+			};
+
+		// Set the guid of unique handler to the same of original handler, so it can be removed
+		proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
+
+		return proxy;
+	},
+
+	// Mutifunctional method to get and set values to a collection
+	// The value/s can optionally be executed if it's a function
+	access: function( elems, key, value, exec, fn, pass ) {
+		var length = elems.length;
+
+		// Setting many attributes
+		if ( typeof key === "object" ) {
+			for ( var k in key ) {
+				jQuery.access( elems, k, key[k], exec, fn, value );
+			}
+			return elems;
+		}
+
+		// Setting one attribute
+		if ( value !== undefined ) {
+			// Optionally, function values get executed if exec is true
+			exec = !pass && exec && jQuery.isFunction(value);
+
+			for ( var i = 0; i < length; i++ ) {
+				fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
+			}
+
+			return elems;
+		}
+
+		// Getting an attribute
+		return length ? fn( elems[0], key ) : undefined;
+	},
+
+	now: function() {
+		return (new Date()).getTime();
+	},
+
+	// Use of jQuery.browser is frowned upon.
+	// More details: http://docs.jquery.com/Utilities/jQuery.browser
+	uaMatch: function( ua ) {
+		ua = ua.toLowerCase();
+
+		var match = rwebkit.exec( ua ) ||
+			ropera.exec( ua ) ||
+			rmsie.exec( ua ) ||
+			ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
+			[];
+
+		return { browser: match[1] || "", version: match[2] || "0" };
+	},
+
+	sub: function() {
+		function jQuerySub( selector, context ) {
+			return new jQuerySub.fn.init( selector, context );
+		}
+		jQuery.extend( true, jQuerySub, this );
+		jQuerySub.superclass = this;
+		jQuerySub.fn = jQuerySub.prototype = this();
+		jQuerySub.fn.constructor = jQuerySub;
+		jQuerySub.sub = this.sub;
+		jQuerySub.fn.init = function init( selector, context ) {
+			if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
+				context = jQuerySub( context );
+			}
+
+			return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
+		};
+		jQuerySub.fn.init.prototype = jQuerySub.fn;
+		var rootjQuerySub = jQuerySub(document);
+		return jQuerySub;
+	},
+
+	browser: {}
+});
+
+// Populate the class2type map
+jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
+	class2type[ "[object " + name + "]" ] = name.toLowerCase();
+});
+
+browserMatch = jQuery.uaMatch( userAgent );
+if ( browserMatch.browser ) {
+	jQuery.browser[ browserMatch.browser ] = true;
+	jQuery.browser.version = browserMatch.version;
+}
+
+// Deprecated, use jQuery.browser.webkit instead
+if ( jQuery.browser.webkit ) {
+	jQuery.browser.safari = true;
+}
+
+// IE doesn't match non-breaking spaces with \s
+if ( rnotwhite.test( "\xA0" ) ) {
+	trimLeft = /^[\s\xA0]+/;
+	trimRight = /[\s\xA0]+$/;
+}
+
+// All jQuery objects should point back to these
+rootjQuery = jQuery(document);
+
+// Cleanup functions for the document ready method
+if ( document.addEventListener ) {
+	DOMContentLoaded = function() {
+		document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
+		jQuery.ready();
+	};
+
+} else if ( document.attachEvent ) {
+	DOMContentLoaded = function() {
+		// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
+		if ( document.readyState === "complete" ) {
+			document.detachEvent( "onreadystatechange", DOMContentLoaded );
+			jQuery.ready();
+		}
+	};
+}
+
+// The DOM ready check for Internet Explorer
+function doScrollCheck() {
+	if ( jQuery.isReady ) {
+		return;
+	}
+
+	try {
+		// If IE is used, use the trick by Diego Perini
+		// http://javascript.nwbox.com/IEContentLoaded/
+		document.documentElement.doScroll("left");
+	} catch(e) {
+		setTimeout( doScrollCheck, 1 );
+		return;
+	}
+
+	// and execute any waiting functions
+	jQuery.ready();
+}
+
+return jQuery;
+
+})();
+
+
+var // Promise methods
+	promiseMethods = "done fail isResolved isRejected promise then always pipe".split( " " ),
+	// Static reference to slice
+	sliceDeferred = [].slice;
+
+jQuery.extend({
+	// Create a simple deferred (one callbacks list)
+	_Deferred: function() {
+		var // callbacks list
+			callbacks = [],
+			// stored [ context , args ]
+			fired,
+			// to avoid firing when already doing so
+			firing,
+			// flag to know if the deferred has been cancelled
+			cancelled,
+			// the deferred itself
+			deferred  = {
+
+				// done( f1, f2, ...)
+				done: function() {
+					if ( !cancelled ) {
+						var args = arguments,
+							i,
+							length,
+							elem,
+							type,
+							_fired;
+						if ( fired ) {
+							_fired = fired;
+							fired = 0;
+						}
+						for ( i = 0, length = args.length; i < length; i++ ) {
+							elem = args[ i ];
+							type = jQuery.type( elem );
+							if ( type === "array" ) {
+								deferred.done.apply( deferred, elem );
+							} else if ( type === "function" ) {
+								callbacks.push( elem );
+							}
+						}
+						if ( _fired ) {
+							deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] );
+						}
+					}
+					return this;
+				},
+
+				// resolve with given context and args
+				resolveWith: function( context, args ) {
+					if ( !cancelled && !fired && !firing ) {
+						// make sure args are available (#8421)
+						args = args || [];
+						firing = 1;
+						try {
+							while( callbacks[ 0 ] ) {
+								callbacks.shift().apply( context, args );
+							}
+						}
+						finally {
+							fired = [ context, args ];
+							firing = 0;
+						}
+					}
+					return this;
+				},
+
+				// resolve with this as context and given arguments
+				resolve: function() {
+					deferred.resolveWith( this, arguments );
+					return this;
+				},
+
+				// Has this deferred been resolved?
+				isResolved: function() {
+					return !!( firing || fired );
+				},
+
+				// Cancel
+				cancel: function() {
+					cancelled = 1;
+					callbacks = [];
+					return this;
+				}
+			};
+
+		return deferred;
+	},
+
+	// Full fledged deferred (two callbacks list)
+	Deferred: function( func ) {
+		var deferred = jQuery._Deferred(),
+			failDeferred = jQuery._Deferred(),
+			promise;
+		// Add errorDeferred methods, then and promise
+		jQuery.extend( deferred, {
+			then: function( doneCallbacks, failCallbacks ) {
+				deferred.done( doneCallbacks ).fail( failCallbacks );
+				return this;
+			},
+			always: function() {
+				return deferred.done.apply( deferred, arguments ).fail.apply( this, arguments );
+			},
+			fail: failDeferred.done,
+			rejectWith: failDeferred.resolveWith,
+			reject: failDeferred.resolve,
+			isRejected: failDeferred.isResolved,
+			pipe: function( fnDone, fnFail ) {
+				return jQuery.Deferred(function( newDefer ) {
+					jQuery.each( {
+						done: [ fnDone, "resolve" ],
+						fail: [ fnFail, "reject" ]
+					}, function( handler, data ) {
+						var fn = data[ 0 ],
+							action = data[ 1 ],
+							returned;
+						if ( jQuery.isFunction( fn ) ) {
+							deferred[ handler ](function() {
+								returned = fn.apply( this, arguments );
+								if ( returned && jQuery.isFunction( returned.promise ) ) {
+									returned.promise().then( newDefer.resolve, newDefer.reject );
+								} else {
+									newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );
+								}
+							});
+						} else {
+							deferred[ handler ]( newDefer[ action ] );
+						}
+					});
+				}).promise();
+			},
+			// Get a promise for this deferred
+			// If obj is provided, the promise aspect is added to the object
+			promise: function( obj ) {
+				if ( obj == null ) {
+					if ( promise ) {
+						return promise;
+					}
+					promise = obj = {};
+				}
+				var i = promiseMethods.length;
+				while( i-- ) {
+					obj[ promiseMethods[i] ] = deferred[ promiseMethods[i] ];
+				}
+				return obj;
+			}
+		});
+		// Make sure only one callback list will be used
+		deferred.done( failDeferred.cancel ).fail( deferred.cancel );
+		// Unexpose cancel
+		delete deferred.cancel;
+		// Call given func if any
+		if ( func ) {
+			func.call( deferred, deferred );
+		}
+		return deferred;
+	},
+
+	// Deferred helper
+	when: function( firstParam ) {
+		var args = arguments,
+			i = 0,
+			length = args.length,
+			count = length,
+			deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ?
+				firstParam :
+				jQuery.Deferred();
+		function resolveFunc( i ) {
+			return function( value ) {
+				args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
+				if ( !( --count ) ) {
+					// Strange bug in FF4:
+					// Values changed onto the arguments object sometimes end up as undefined values
+					// outside the $.when method. Cloning the object into a fresh array solves the issue
+					deferred.resolveWith( deferred, sliceDeferred.call( args, 0 ) );
+				}
+			};
+		}
+		if ( length > 1 ) {
+			for( ; i < length; i++ ) {
+				if ( args[ i ] && jQuery.isFunction( args[ i ].promise ) ) {
+					args[ i ].promise().then( resolveFunc(i), deferred.reject );
+				} else {
+					--count;
+				}
+			}
+			if ( !count ) {
+				deferred.resolveWith( deferred, args );
+			}
+		} else if ( deferred !== firstParam ) {
+			deferred.resolveWith( deferred, length ? [ firstParam ] : [] );
+		}
+		return deferred.promise();
+	}
+});
+
+
+
+jQuery.support = (function() {
+
+	var div = document.createElement( "div" ),
+		documentElement = document.documentElement,
+		all,
+		a,
+		select,
+		opt,
+		input,
+		marginDiv,
+		support,
+		fragment,
+		body,
+		testElementParent,
+		testElement,
+		testElementStyle,
+		tds,
+		events,
+		eventName,
+		i,
+		isSupported;
+
+	// Preliminary tests
+	div.setAttribute("className", "t");
+	div.innerHTML = "   <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
+
+
+	all = div.getElementsByTagName( "*" );
+	a = div.getElementsByTagName( "a" )[ 0 ];
+
+	// Can't get basic test support
+	if ( !all || !all.length || !a ) {
+		return {};
+	}
+
+	// First batch of supports tests
+	select = document.createElement( "select" );
+	opt = select.appendChild( document.createElement("option") );
+	input = div.getElementsByTagName( "input" )[ 0 ];
+
+	support = {
+		// IE strips leading whitespace when .innerHTML is used
+		leadingWhitespace: ( div.firstChild.nodeType === 3 ),
+
+		// Make sure that tbody elements aren't automatically inserted
+		// IE will insert them into empty tables
+		tbody: !div.getElementsByTagName( "tbody" ).length,
+
+		// Make sure that link elements get serialized correctly by innerHTML
+		// This requires a wrapper element in IE
+		htmlSerialize: !!div.getElementsByTagName( "link" ).length,
+
+		// Get the style information from getAttribute
+		// (IE uses .cssText instead)
+		style: /top/.test( a.getAttribute("style") ),
+
+		// Make sure that URLs aren't manipulated
+		// (IE normalizes it by default)
+		hrefNormalized: ( a.getAttribute( "href" ) === "/a" ),
+
+		// Make sure that element opacity exists
+		// (IE uses filter instead)
+		// Use a regex to work around a WebKit issue. See #5145
+		opacity: /^0.55$/.test( a.style.opacity ),
+
+		// Verify style float existence
+		// (IE uses styleFloat instead of cssFloat)
+		cssFloat: !!a.style.cssFloat,
+
+		// Make sure that if no value is specified for a checkbox
+		// that it defaults to "on".
+		// (WebKit defaults to "" instead)
+		checkOn: ( input.value === "on" ),
+
+		// Make sure that a selected-by-default option has a working selected property.
+		// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
+		optSelected: opt.selected,
+
+		// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
+		getSetAttribute: div.className !== "t",
+
+		// Will be defined later
+		submitBubbles: true,
+		changeBubbles: true,
+		focusinBubbles: false,
+		deleteExpando: true,
+		noCloneEvent: true,
+		inlineBlockNeedsLayout: false,
+		shrinkWrapBlocks: false,
+		reliableMarginRight: true
+	};
+
+	// Make sure checked status is properly cloned
+	input.checked = true;
+	support.noCloneChecked = input.cloneNode( true ).checked;
+
+	// Make sure that the options inside disabled selects aren't marked as disabled
+	// (WebKit marks them as disabled)
+	select.disabled = true;
+	support.optDisabled = !opt.disabled;
+
+	// Test to see if it's possible to delete an expando from an element
+	// Fails in Internet Explorer
+	try {
+		delete div.test;
+	} catch( e ) {
+		support.deleteExpando = false;
+	}
+
+	if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
+		div.attachEvent( "onclick", function() {
+			// Cloning a node shouldn't copy over any
+			// bound event handlers (IE does this)
+			support.noCloneEvent = false;
+		});
+		div.cloneNode( true ).fireEvent( "onclick" );
+	}
+
+	// Check if a radio maintains it's value
+	// after being appended to the DOM
+	input = document.createElement("input");
+	input.value = "t";
+	input.setAttribute("type", "radio");
+	support.radioValue = input.value === "t";
+
+	input.setAttribute("checked", "checked");
+	div.appendChild( input );
+	fragment = document.createDocumentFragment();
+	fragment.appendChild( div.firstChild );
+
+	// WebKit doesn't clone checked state correctly in fragments
+	support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
+
+	div.innerHTML = "";
+
+	// Figure out if the W3C box model works as expected
+	div.style.width = div.style.paddingLeft = "1px";
+
+	body = document.getElementsByTagName( "body" )[ 0 ];
+	// We use our own, invisible, body unless the body is already present
+	// in which case we use a div (#9239)
+	testElement = document.createElement( body ? "div" : "body" );
+	testElementStyle = {
+		visibility: "hidden",
+		width: 0,
+		height: 0,
+		border: 0,
+		margin: 0,
+		background: "none"
+	};
+	if ( body ) {
+		jQuery.extend( testElementStyle, {
+			position: "absolute",
+			left: "-1000px",
+			top: "-1000px"
+		});
+	}
+	for ( i in testElementStyle ) {
+		testElement.style[ i ] = testElementStyle[ i ];
+	}
+	testElement.appendChild( div );
+	testElementParent = body || documentElement;
+	testElementParent.insertBefore( testElement, testElementParent.firstChild );
+
+	// Check if a disconnected checkbox will retain its checked
+	// value of true after appended to the DOM (IE6/7)
+	support.appendChecked = input.checked;
+
+	support.boxModel = div.offsetWidth === 2;
+
+	if ( "zoom" in div.style ) {
+		// Check if natively block-level elements act like inline-block
+		// elements when setting their display to 'inline' and giving
+		// them layout
+		// (IE < 8 does this)
+		div.style.display = "inline";
+		div.style.zoom = 1;
+		support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 );
+
+		// Check if elements with layout shrink-wrap their children
+		// (IE 6 does this)
+		div.style.display = "";
+		div.innerHTML = "<div style='width:4px;'></div>";
+		support.shrinkWrapBlocks = ( div.offsetWidth !== 2 );
+	}
+
+	div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>";
+	tds = div.getElementsByTagName( "td" );
+
+	// Check if table cells still have offsetWidth/Height when they are set
+	// to display:none and there are still other visible table cells in a
+	// table row; if so, offsetWidth/Height are not reliable for use when
+	// determining if an element has been hidden directly using
+	// display:none (it is still safe to use offsets if a parent element is
+	// hidden; don safety goggles and see bug #4512 for more information).
+	// (only IE 8 fails this test)
+	isSupported = ( tds[ 0 ].offsetHeight === 0 );
+
+	tds[ 0 ].style.display = "";
+	tds[ 1 ].style.display = "none";
+
+	// Check if empty table cells still have offsetWidth/Height
+	// (IE < 8 fail this test)
+	support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
+	div.innerHTML = "";
+
+	// Check if div with explicit width and no margin-right incorrectly
+	// gets computed margin-right based on width of container. For more
+	// info see bug #3333
+	// Fails in WebKit before Feb 2011 nightlies
+	// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
+	if ( document.defaultView && document.defaultView.getComputedStyle ) {
+		marginDiv = document.createElement( "div" );
+		marginDiv.style.width = "0";
+		marginDiv.style.marginRight = "0";
+		div.appendChild( marginDiv );
+		support.reliableMarginRight =
+			( parseInt( ( document.defaultView.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0;
+	}
+
+	// Remove the body element we added
+	testElement.innerHTML = "";
+	testElementParent.removeChild( testElement );
+
+	// Technique from Juriy Zaytsev
+	// http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/
+	// We only care about the case where non-standard event systems
+	// are used, namely in IE. Short-circuiting here helps us to
+	// avoid an eval call (in setAttribute) which can cause CSP
+	// to go haywire. See: https://developer.mozilla.org/en/Security/CSP
+	if ( div.attachEvent ) {
+		for( i in {
+			submit: 1,
+			change: 1,
+			focusin: 1
+		} ) {
+			eventName = "on" + i;
+			isSupported = ( eventName in div );
+			if ( !isSupported ) {
+				div.setAttribute( eventName, "return;" );
+				isSupported = ( typeof div[ eventName ] === "function" );
+			}
+			support[ i + "Bubbles" ] = isSupported;
+		}
+	}
+
+	// Null connected elements to avoid leaks in IE
+	testElement = fragment = select = opt = body = marginDiv = div = input = null;
+
+	return support;
+})();
+
+// Keep track of boxModel
+jQuery.boxModel = jQuery.support.boxModel;
+
+
+
+
+var rbrace = /^(?:\{.*\}|\[.*\])$/,
+	rmultiDash = /([A-Z])/g;
+
+jQuery.extend({
+	cache: {},
+
+	// Please use with caution
+	uuid: 0,
+
+	// Unique for each copy of jQuery on the page
+	// Non-digits removed to match rinlinejQuery
+	expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
+
+	// The following elements throw uncatchable exceptions if you
+	// attempt to add expando properties to them.
+	noData: {
+		"embed": true,
+		// Ban all objects except for Flash (which handle expandos)
+		"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
+		"applet": true
+	},
+
+	hasData: function( elem ) {
+		elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
+
+		return !!elem && !isEmptyDataObject( elem );
+	},
+
+	data: function( elem, name, data, pvt /* Internal Use Only */ ) {
+		if ( !jQuery.acceptData( elem ) ) {
+			return;
+		}
+
+		var thisCache, ret,
+			internalKey = jQuery.expando,
+			getByName = typeof name === "string",
+
+			// We have to handle DOM nodes and JS objects differently because IE6-7
+			// can't GC object references properly across the DOM-JS boundary
+			isNode = elem.nodeType,
+
+			// Only DOM nodes need the global jQuery cache; JS object data is
+			// attached directly to the object so GC can occur automatically
+			cache = isNode ? jQuery.cache : elem,
+
+			// Only defining an ID for JS objects if its cache already exists allows
+			// the code to shortcut on the same path as a DOM node with no cache
+			id = isNode ? elem[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando;
+
+		// Avoid doing any more work than we need to when trying to get data on an
+		// object that has no data at all
+		if ( (!id || (pvt && id && (cache[ id ] && !cache[ id ][ internalKey ]))) && getByName && data === undefined ) {
+			return;
+		}
+
+		if ( !id ) {
+			// Only DOM nodes need a new unique ID for each element since their data
+			// ends up in the global cache
+			if ( isNode ) {
+				elem[ jQuery.expando ] = id = ++jQuery.uuid;
+			} else {
+				id = jQuery.expando;
+			}
+		}
+
+		if ( !cache[ id ] ) {
+			cache[ id ] = {};
+
+			// TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery
+			// metadata on plain JS objects when the object is serialized using
+			// JSON.stringify
+			if ( !isNode ) {
+				cache[ id ].toJSON = jQuery.noop;
+			}
+		}
+
+		// An object can be passed to jQuery.data instead of a key/value pair; this gets
+		// shallow copied over onto the existing cache
+		if ( typeof name === "object" || typeof name === "function" ) {
+			if ( pvt ) {
+				cache[ id ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name);
+			} else {
+				cache[ id ] = jQuery.extend(cache[ id ], name);
+			}
+		}
+
+		thisCache = cache[ id ];
+
+		// Internal jQuery data is stored in a separate object inside the object's data
+		// cache in order to avoid key collisions between internal data and user-defined
+		// data
+		if ( pvt ) {
+			if ( !thisCache[ internalKey ] ) {
+				thisCache[ internalKey ] = {};
+			}
+
+			thisCache = thisCache[ internalKey ];
+		}
+
+		if ( data !== undefined ) {
+			thisCache[ jQuery.camelCase( name ) ] = data;
+		}
+
+		// TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should
+		// not attempt to inspect the internal events object using jQuery.data, as this
+		// internal data object is undocumented and subject to change.
+		if ( name === "events" && !thisCache[name] ) {
+			return thisCache[ internalKey ] && thisCache[ internalKey ].events;
+		}
+
+		// Check for both converted-to-camel and non-converted data property names
+		// If a data property was specified
+		if ( getByName ) {
+
+			// First Try to find as-is property data
+			ret = thisCache[ name ];
+
+			// Test for null|undefined property data
+			if ( ret == null ) {
+
+				// Try to find the camelCased property
+				ret = thisCache[ jQuery.camelCase( name ) ];
+			}
+		} else {
+			ret = thisCache;
+		}
+
+		return ret;
+	},
+
+	removeData: function( elem, name, pvt /* Internal Use Only */ ) {
+		if ( !jQuery.acceptData( elem ) ) {
+			return;
+		}
+
+		var thisCache,
+
+			// Reference to internal data cache key
+			internalKey = jQuery.expando,
+
+			isNode = elem.nodeType,
+
+			// See jQuery.data for more information
+			cache = isNode ? jQuery.cache : elem,
+
+			// See jQuery.data for more information
+			id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
+
+		// If there is already no cache entry for this object, there is no
+		// purpose in continuing
+		if ( !cache[ id ] ) {
+			return;
+		}
+
+		if ( name ) {
+
+			thisCache = pvt ? cache[ id ][ internalKey ] : cache[ id ];
+
+			if ( thisCache ) {
+
+				// Support interoperable removal of hyphenated or camelcased keys
+				if ( !thisCache[ name ] ) {
+					name = jQuery.camelCase( name );
+				}
+
+				delete thisCache[ name ];
+
+				// If there is no data left in the cache, we want to continue
+				// and let the cache object itself get destroyed
+				if ( !isEmptyDataObject(thisCache) ) {
+					return;
+				}
+			}
+		}
+
+		// See jQuery.data for more information
+		if ( pvt ) {
+			delete cache[ id ][ internalKey ];
+
+			// Don't destroy the parent cache unless the internal data object
+			// had been the only thing left in it
+			if ( !isEmptyDataObject(cache[ id ]) ) {
+				return;
+			}
+		}
+
+		var internalCache = cache[ id ][ internalKey ];
+
+		// Browsers that fail expando deletion also refuse to delete expandos on
+		// the window, but it will allow it on all other JS objects; other browsers
+		// don't care
+		// Ensure that `cache` is not a window object #10080
+		if ( jQuery.support.deleteExpando || !cache.setInterval ) {
+			delete cache[ id ];
+		} else {
+			cache[ id ] = null;
+		}
+
+		// We destroyed the entire user cache at once because it's faster than
+		// iterating through each key, but we need to continue to persist internal
+		// data if it existed
+		if ( internalCache ) {
+			cache[ id ] = {};
+			// TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery
+			// metadata on plain JS objects when the object is serialized using
+			// JSON.stringify
+			if ( !isNode ) {
+				cache[ id ].toJSON = jQuery.noop;
+			}
+
+			cache[ id ][ internalKey ] = internalCache;
+
+		// Otherwise, we need to eliminate the expando on the node to avoid
+		// false lookups in the cache for entries that no longer exist
+		} else if ( isNode ) {
+			// IE does not allow us to delete expando properties from nodes,
+			// nor does it have a removeAttribute function on Document nodes;
+			// we must handle all of these cases
+			if ( jQuery.support.deleteExpando ) {
+				delete elem[ jQuery.expando ];
+			} else if ( elem.removeAttribute ) {
+				elem.removeAttribute( jQuery.expando );
+			} else {
+				elem[ jQuery.expando ] = null;
+			}
+		}
+	},
+
+	// For internal use only.
+	_data: function( elem, name, data ) {
+		return jQuery.data( elem, name, data, true );
+	},
+
+	// A method for determining if a DOM node can handle the data expando
+	acceptData: function( elem ) {
+		if ( elem.nodeName ) {
+			var match = jQuery.noData[ elem.nodeName.toLowerCase() ];
+
+			if ( match ) {
+				return !(match === true || elem.getAttribute("classid") !== match);
+			}
+		}
+
+		return true;
+	}
+});
+
+jQuery.fn.extend({
+	data: function( key, value ) {
+		var data = null;
+
+		if ( typeof key === "undefined" ) {
+			if ( this.length ) {
+				data = jQuery.data( this[0] );
+
+				if ( this[0].nodeType === 1 ) {
+			    var attr = this[0].attributes, name;
+					for ( var i = 0, l = attr.length; i < l; i++ ) {
+						name = attr[i].name;
+
+						if ( name.indexOf( "data-" ) === 0 ) {
+							name = jQuery.camelCase( name.substring(5) );
+
+							dataAttr( this[0], name, data[ name ] );
+						}
+					}
+				}
+			}
+
+			return data;
+
+		} else if ( typeof key === "object" ) {
+			return this.each(function() {
+				jQuery.data( this, key );
+			});
+		}
+
+		var parts = key.split(".");
+		parts[1] = parts[1] ? "." + parts[1] : "";
+
+		if ( value === undefined ) {
+			data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
+
+			// Try to fetch any internally stored data first
+			if ( data === undefined && this.length ) {
+				data = jQuery.data( this[0], key );
+				data = dataAttr( this[0], key, data );
+			}
+
+			return data === undefined && parts[1] ?
+				this.data( parts[0] ) :
+				data;
+
+		} else {
+			return this.each(function() {
+				var $this = jQuery( this ),
+					args = [ parts[0], value ];
+
+				$this.triggerHandler( "setData" + parts[1] + "!", args );
+				jQuery.data( this, key, value );
+				$this.triggerHandler( "changeData" + parts[1] + "!", args );
+			});
+		}
+	},
+
+	removeData: function( key ) {
+		return this.each(function() {
+			jQuery.removeData( this, key );
+		});
+	}
+});
+
+function dataAttr( elem, key, data ) {
+	// If nothing was found internally, try to fetch any
+	// data from the HTML5 data-* attribute
+	if ( data === undefined && elem.nodeType === 1 ) {
+
+		var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
+
+		data = elem.getAttribute( name );
+
+		if ( typeof data === "string" ) {
+			try {
+				data = data === "true" ? true :
+				data === "false" ? false :
+				data === "null" ? null :
+				!jQuery.isNaN( data ) ? parseFloat( data ) :
+					rbrace.test( data ) ? jQuery.parseJSON( data ) :
+					data;
+			} catch( e ) {}
+
+			// Make sure we set the data so it isn't changed later
+			jQuery.data( elem, key, data );
+
+		} else {
+			data = undefined;
+		}
+	}
+
+	return data;
+}
+
+// TODO: This is a hack for 1.5 ONLY to allow objects with a single toJSON
+// property to be considered empty objects; this property always exists in
+// order to make sure JSON.stringify does not expose internal metadata
+function isEmptyDataObject( obj ) {
+	for ( var name in obj ) {
+		if ( name !== "toJSON" ) {
+			return false;
+		}
+	}
+
+	return true;
+}
+
+
+
+
+function handleQueueMarkDefer( elem, type, src ) {
+	var deferDataKey = type + "defer",
+		queueDataKey = type + "queue",
+		markDataKey = type + "mark",
+		defer = jQuery.data( elem, deferDataKey, undefined, true );
+	if ( defer &&
+		( src === "queue" || !jQuery.data( elem, queueDataKey, undefined, true ) ) &&
+		( src === "mark" || !jQuery.data( elem, markDataKey, undefined, true ) ) ) {
+		// Give room for hard-coded callbacks to fire first
+		// and eventually mark/queue something else on the element
+		setTimeout( function() {
+			if ( !jQuery.data( elem, queueDataKey, undefined, true ) &&
+				!jQuery.data( elem, markDataKey, undefined, true ) ) {
+				jQuery.removeData( elem, deferDataKey, true );
+				defer.resolve();
+			}
+		}, 0 );
+	}
+}
+
+jQuery.extend({
+
+	_mark: function( elem, type ) {
+		if ( elem ) {
+			type = (type || "fx") + "mark";
+			jQuery.data( elem, type, (jQuery.data(elem,type,undefined,true) || 0) + 1, true );
+		}
+	},
+
+	_unmark: function( force, elem, type ) {
+		if ( force !== true ) {
+			type = elem;
+			elem = force;
+			force = false;
+		}
+		if ( elem ) {
+			type = type || "fx";
+			var key = type + "mark",
+				count = force ? 0 : ( (jQuery.data( elem, key, undefined, true) || 1 ) - 1 );
+			if ( count ) {
+				jQuery.data( elem, key, count, true );
+			} else {
+				jQuery.removeData( elem, key, true );
+				handleQueueMarkDefer( elem, type, "mark" );
+			}
+		}
+	},
+
+	queue: function( elem, type, data ) {
+		if ( elem ) {
+			type = (type || "fx") + "queue";
+			var q = jQuery.data( elem, type, undefined, true );
+			// Speed up dequeue by getting out quickly if this is just a lookup
+			if ( data ) {
+				if ( !q || jQuery.isArray(data) ) {
+					q = jQuery.data( elem, type, jQuery.makeArray(data), true );
+				} else {
+					q.push( data );
+				}
+			}
+			return q || [];
+		}
+	},
+
+	dequeue: function( elem, type ) {
+		type = type || "fx";
+
+		var queue = jQuery.queue( elem, type ),
+			fn = queue.shift(),
+			defer;
+
+		// If the fx queue is dequeued, always remove the progress sentinel
+		if ( fn === "inprogress" ) {
+			fn = queue.shift();
+		}
+
+		if ( fn ) {
+			// Add a progress sentinel to prevent the fx queue from being
+			// automatically dequeued
+			if ( type === "fx" ) {
+				queue.unshift("inprogress");
+			}
+
+			fn.call(elem, function() {
+				jQuery.dequeue(elem, type);
+			});
+		}
+
+		if ( !queue.length ) {
+			jQuery.removeData( elem, type + "queue", true );
+			handleQueueMarkDefer( elem, type, "queue" );
+		}
+	}
+});
+
+jQuery.fn.extend({
+	queue: function( type, data ) {
+		if ( typeof type !== "string" ) {
+			data = type;
+			type = "fx";
+		}
+
+		if ( data === undefined ) {
+			return jQuery.queue( this[0], type );
+		}
+		return this.each(function() {
+			var queue = jQuery.queue( this, type, data );
+
+			if ( type === "fx" && queue[0] !== "inprogress" ) {
+				jQuery.dequeue( this, type );
+			}
+		});
+	},
+	dequeue: function( type ) {
+		return this.each(function() {
+			jQuery.dequeue( this, type );
+		});
+	},
+	// Based off of the plugin by Clint Helfers, with permission.
+	// http://blindsignals.com/index.php/2009/07/jquery-delay/
+	delay: function( time, type ) {
+		time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
+		type = type || "fx";
+
+		return this.queue( type, function() {
+			var elem = this;
+			setTimeout(function() {
+				jQuery.dequeue( elem, type );
+			}, time );
+		});
+	},
+	clearQueue: function( type ) {
+		return this.queue( type || "fx", [] );
+	},
+	// Get a promise resolved when queues of a certain type
+	// are emptied (fx is the type by default)
+	promise: function( type, object ) {
+		if ( typeof type !== "string" ) {
+			object = type;
+			type = undefined;
+		}
+		type = type || "fx";
+		var defer = jQuery.Deferred(),
+			elements = this,
+			i = elements.length,
+			count = 1,
+			deferDataKey = type + "defer",
+			queueDataKey = type + "queue",
+			markDataKey = type + "mark",
+			tmp;
+		function resolve() {
+			if ( !( --count ) ) {
+				defer.resolveWith( elements, [ elements ] );
+			}
+		}
+		while( i-- ) {
+			if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) ||
+					( jQuery.data( elements[ i ], queueDataKey, undefined, true ) ||
+						jQuery.data( elements[ i ], markDataKey, undefined, true ) ) &&
+					jQuery.data( elements[ i ], deferDataKey, jQuery._Deferred(), true ) )) {
+				count++;
+				tmp.done( resolve );
+			}
+		}
+		resolve();
+		return defer.promise();
+	}
+});
+
+
+
+
+var rclass = /[\n\t\r]/g,
+	rspace = /\s+/,
+	rreturn = /\r/g,
+	rtype = /^(?:button|input)$/i,
+	rfocusable = /^(?:button|input|object|select|textarea)$/i,
+	rclickable = /^a(?:rea)?$/i,
+	rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
+	nodeHook, boolHook;
+
+jQuery.fn.extend({
+	attr: function( name, value ) {
+		return jQuery.access( this, name, value, true, jQuery.attr );
+	},
+
+	removeAttr: function( name ) {
+		return this.each(function() {
+			jQuery.removeAttr( this, name );
+		});
+	},
+	
+	prop: function( name, value ) {
+		return jQuery.access( this, name, value, true, jQuery.prop );
+	},
+	
+	removeProp: function( name ) {
+		name = jQuery.propFix[ name ] || name;
+		return this.each(function() {
+			// try/catch handles cases where IE balks (such as removing a property on window)
+			try {
+				this[ name ] = undefined;
+				delete this[ name ];
+			} catch( e ) {}
+		});
+	},
+
+	addClass: function( value ) {
+		var classNames, i, l, elem,
+			setClass, c, cl;
+
+		if ( jQuery.isFunction( value ) ) {
+			return this.each(function( j ) {
+				jQuery( this ).addClass( value.call(this, j, this.className) );
+			});
+		}
+
+		if ( value && typeof value === "string" ) {
+			classNames = value.split( rspace );
+
+			for ( i = 0, l = this.length; i < l; i++ ) {
+				elem = this[ i ];
+
+				if ( elem.nodeType === 1 ) {
+					if ( !elem.className && classNames.length === 1 ) {
+						elem.className = value;
+
+					} else {
+						setClass = " " + elem.className + " ";
+
+						for ( c = 0, cl = classNames.length; c < cl; c++ ) {
+							if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) {
+								setClass += classNames[ c ] + " ";
+							}
+						}
+						elem.className = jQuery.trim( setClass );
+					}
+				}
+			}
+		}
+
+		return this;
+	},
+
+	removeClass: function( value ) {
+		var classNames, i, l, elem, className, c, cl;
+
+		if ( jQuery.isFunction( value ) ) {
+			return this.each(function( j ) {
+				jQuery( this ).removeClass( value.call(this, j, this.className) );
+			});
+		}
+
+		if ( (value && typeof value === "string") || value === undefined ) {
+			classNames = (value || "").split( rspace );
+
+			for ( i = 0, l = this.length; i < l; i++ ) {
+				elem = this[ i ];
+
+				if ( elem.nodeType === 1 && elem.className ) {
+					if ( value ) {
+						className = (" " + elem.className + " ").replace( rclass, " " );
+						for ( c = 0, cl = classNames.length; c < cl; c++ ) {
+							className = className.replace(" " + classNames[ c ] + " ", " ");
+						}
+						elem.className = jQuery.trim( className );
+
+					} else {
+						elem.className = "";
+					}
+				}
+			}
+		}
+
+		return this;
+	},
+
+	toggleClass: function( value, stateVal ) {
+		var type = typeof value,
+			isBool = typeof stateVal === "boolean";
+
+		if ( jQuery.isFunction( value ) ) {
+			return this.each(function( i ) {
+				jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
+			});
+		}
+
+		return this.each(function() {
+			if ( type === "string" ) {
+				// toggle individual class names
+				var className,
+					i = 0,
+					self = jQuery( this ),
+					state = stateVal,
+					classNames = value.split( rspace );
+
+				while ( (className = classNames[ i++ ]) ) {
+					// check each className given, space seperated list
+					state = isBool ? state : !self.hasClass( className );
+					self[ state ? "addClass" : "removeClass" ]( className );
+				}
+
+			} else if ( type === "undefined" || type === "boolean" ) {
+				if ( this.className ) {
+					// store className if set
+					jQuery._data( this, "__className__", this.className );
+				}
+
+				// toggle whole className
+				this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
+			}
+		});
+	},
+
+	hasClass: function( selector ) {
+		var className = " " + selector + " ";
+		for ( var i = 0, l = this.length; i < l; i++ ) {
+			if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
+				return true;
+			}
+		}
+
+		return false;
+	},
+
+	val: function( value ) {
+		var hooks, ret,
+			elem = this[0];
+		
+		if ( !arguments.length ) {
+			if ( elem ) {
+				hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ];
+
+				if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
+					return ret;
+				}
+
+				ret = elem.value;
+
+				return typeof ret === "string" ? 
+					// handle most common string cases
+					ret.replace(rreturn, "") : 
+					// handle cases where value is null/undef or number
+					ret == null ? "" : ret;
+			}
+
+			return undefined;
+		}
+
+		var isFunction = jQuery.isFunction( value );
+
+		return this.each(function( i ) {
+			var self = jQuery(this), val;
+
+			if ( this.nodeType !== 1 ) {
+				return;
+			}
+
+			if ( isFunction ) {
+				val = value.call( this, i, self.val() );
+			} else {
+				val = value;
+			}
+
+			// Treat null/undefined as ""; convert numbers to string
+			if ( val == null ) {
+				val = "";
+			} else if ( typeof val === "number" ) {
+				val += "";
+			} else if ( jQuery.isArray( val ) ) {
+				val = jQuery.map(val, function ( value ) {
+					return value == null ? "" : value + "";
+				});
+			}
+
+			hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ];
+
+			// If set returns undefined, fall back to normal setting
+			if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
+				this.value = val;
+			}
+		});
+	}
+});
+
+jQuery.extend({
+	valHooks: {
+		option: {
+			get: function( elem ) {
+				// attributes.value is undefined in Blackberry 4.7 but
+				// uses .value. See #6932
+				var val = elem.attributes.value;
+				return !val || val.specified ? elem.value : elem.text;
+			}
+		},
+		select: {
+			get: function( elem ) {
+				var value,
+					index = elem.selectedIndex,
+					values = [],
+					options = elem.options,
+					one = elem.type === "select-one";
+
+				// Nothing was selected
+				if ( index < 0 ) {
+					return null;
+				}
+
+				// Loop through all the selected options
+				for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
+					var option = options[ i ];
+
+					// Don't return options that are disabled or in a disabled optgroup
+					if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
+							(!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) {
+
+						// Get the specific value for the option
+						value = jQuery( option ).val();
+
+						// We don't need an array for one selects
+						if ( one ) {
+							return value;
+						}
+
+						// Multi-Selects return an array
+						values.push( value );
+					}
+				}
+
+				// Fixes Bug #2551 -- select.val() broken in IE after form.reset()
+				if ( one && !values.length && options.length ) {
+					return jQuery( options[ index ] ).val();
+				}
+
+				return values;
+			},
+
+			set: function( elem, value ) {
+				var values = jQuery.makeArray( value );
+
+				jQuery(elem).find("option").each(function() {
+					this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
+				});
+
+				if ( !values.length ) {
+					elem.selectedIndex = -1;
+				}
+				return values;
+			}
+		}
+	},
+
+	attrFn: {
+		val: true,
+		css: true,
+		html: true,
+		text: true,
+		data: true,
+		width: true,
+		height: true,
+		offset: true
+	},
+	
+	attrFix: {
+		// Always normalize to ensure hook usage
+		tabindex: "tabIndex"
+	},
+	
+	attr: function( elem, name, value, pass ) {
+		var nType = elem.nodeType;
+		
+		// don't get/set attributes on text, comment and attribute nodes
+		if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
+			return undefined;
+		}
+
+		if ( pass && name in jQuery.attrFn ) {
+			return jQuery( elem )[ name ]( value );
+		}
+
+		// Fallback to prop when attributes are not supported
+		if ( !("getAttribute" in elem) ) {
+			return jQuery.prop( elem, name, value );
+		}
+
+		var ret, hooks,
+			notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
+
+		// Normalize the name if needed
+		if ( notxml ) {
+			name = jQuery.attrFix[ name ] || name;
+
+			hooks = jQuery.attrHooks[ name ];
+
+			if ( !hooks ) {
+				// Use boolHook for boolean attributes
+				if ( rboolean.test( name ) ) {
+					hooks = boolHook;
+
+				// Use nodeHook if available( IE6/7 )
+				} else if ( nodeHook ) {
+					hooks = nodeHook;
+				}
+			}
+		}
+
+		if ( value !== undefined ) {
+
+			if ( value === null ) {
+				jQuery.removeAttr( elem, name );
+				return undefined;
+
+			} else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
+				return ret;
+
+			} else {
+				elem.setAttribute( name, "" + value );
+				return value;
+			}
+
+		} else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
+			return ret;
+
+		} else {
+
+			ret = elem.getAttribute( name );
+
+			// Non-existent attributes return null, we normalize to undefined
+			return ret === null ?
+				undefined :
+				ret;
+		}
+	},
+
+	removeAttr: function( elem, name ) {
+		var propName;
+		if ( elem.nodeType === 1 ) {
+			name = jQuery.attrFix[ name ] || name;
+
+			jQuery.attr( elem, name, "" );
+			elem.removeAttribute( name );
+
+			// Set corresponding property to false for boolean attributes
+			if ( rboolean.test( name ) && (propName = jQuery.propFix[ name ] || name) in elem ) {
+				elem[ propName ] = false;
+			}
+		}
+	},
+
+	attrHooks: {
+		type: {
+			set: function( elem, value ) {
+				// We can't allow the type property to be changed (since it causes problems in IE)
+				if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
+					jQuery.error( "type property can't be changed" );
+				} else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
+					// Setting the type on a radio button after the value resets the value in IE6-9
+					// Reset value to it's default in case type is set after value
+					// This is for element creation
+					var val = elem.value;
+					elem.setAttribute( "type", value );
+					if ( val ) {
+						elem.value = val;
+					}
+					return value;
+				}
+			}
+		},
+		// Use the value property for back compat
+		// Use the nodeHook for button elements in IE6/7 (#1954)
+		value: {
+			get: function( elem, name ) {
+				if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
+					return nodeHook.get( elem, name );
+				}
+				return name in elem ?
+					elem.value :
+					null;
+			},
+			set: function( elem, value, name ) {
+				if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
+					return nodeHook.set( elem, value, name );
+				}
+				// Does not return so that setAttribute is also used
+				elem.value = value;
+			}
+		}
+	},
+
+	propFix: {
+		tabindex: "tabIndex",
+		readonly: "readOnly",
+		"for": "htmlFor",
+		"class": "className",
+		maxlength: "maxLength",
+		cellspacing: "cellSpacing",
+		cellpadding: "cellPadding",
+		rowspan: "rowSpan",
+		colspan: "colSpan",
+		usemap: "useMap",
+		frameborder: "frameBorder",
+		contenteditable: "contentEditable"
+	},
+	
+	prop: function( elem, name, value ) {
+		var nType = elem.nodeType;
+
+		// don't get/set properties on text, comment and attribute nodes
+		if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
+			return undefined;
+		}
+
+		var ret, hooks,
+			notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
+
+		if ( notxml ) {
+			// Fix name and attach hooks
+			name = jQuery.propFix[ name ] || name;
+			hooks = jQuery.propHooks[ name ];
+		}
+
+		if ( value !== undefined ) {
+			if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
+				return ret;
+
+			} else {
+				return (elem[ name ] = value);
+			}
+
+		} else {
+			if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
+				return ret;
+
+			} else {
+				return elem[ name ];
+			}
+		}
+	},
+	
+	propHooks: {
+		tabIndex: {
+			get: function( elem ) {
+				// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
+				// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
+				var attributeNode = elem.getAttributeNode("tabindex");
+
+				return attributeNode && attributeNode.specified ?
+					parseInt( attributeNode.value, 10 ) :
+					rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
+						0 :
+						undefined;
+			}
+		}
+	}
+});
+
+// Add the tabindex propHook to attrHooks for back-compat
+jQuery.attrHooks.tabIndex = jQuery.propHooks.tabIndex;
+
+// Hook for boolean attributes
+boolHook = {
+	get: function( elem, name ) {
+		// Align boolean attributes with corresponding properties
+		// Fall back to attribute presence where some booleans are not supported
+		var attrNode;
+		return jQuery.prop( elem, name ) === true || ( attrNode = elem.getAttributeNode( name ) ) && attrNode.nodeValue !== false ?
+			name.toLowerCase() :
+			undefined;
+	},
+	set: function( elem, value, name ) {
+		var propName;
+		if ( value === false ) {
+			// Remove boolean attributes when set to false
+			jQuery.removeAttr( elem, name );
+		} else {
+			// value is true since we know at this point it's type boolean and not false
+			// Set boolean attributes to the same name and set the DOM property
+			propName = jQuery.propFix[ name ] || name;
+			if ( propName in elem ) {
+				// Only set the IDL specifically if it already exists on the element
+				elem[ propName ] = true;
+			}
+
+			elem.setAttribute( name, name.toLowerCase() );
+		}
+		return name;
+	}
+};
+
+// IE6/7 do not support getting/setting some attributes with get/setAttribute
+if ( !jQuery.support.getSetAttribute ) {
+	
+	// Use this for any attribute in IE6/7
+	// This fixes almost every IE6/7 issue
+	nodeHook = jQuery.valHooks.button = {
+		get: function( elem, name ) {
+			var ret;
+			ret = elem.getAttributeNode( name );
+			// Return undefined if nodeValue is empty string
+			return ret && ret.nodeValue !== "" ?
+				ret.nodeValue :
+				undefined;
+		},
+		set: function( elem, value, name ) {
+			// Set the existing or create a new attribute node
+			var ret = elem.getAttributeNode( name );
+			if ( !ret ) {
+				ret = document.createAttribute( name );
+				elem.setAttributeNode( ret );
+			}
+			return (ret.nodeValue = value + "");
+		}
+	};
+
+	// Set width and height to auto instead of 0 on empty string( Bug #8150 )
+	// This is for removals
+	jQuery.each([ "width", "height" ], function( i, name ) {
+		jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
+			set: function( elem, value ) {
+				if ( value === "" ) {
+					elem.setAttribute( name, "auto" );
+					return value;
+				}
+			}
+		});
+	});
+}
+
+
+// Some attributes require a special call on IE
+if ( !jQuery.support.hrefNormalized ) {
+	jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
+		jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
+			get: function( elem ) {
+				var ret = elem.getAttribute( name, 2 );
+				return ret === null ? undefined : ret;
+			}
+		});
+	});
+}
+
+if ( !jQuery.support.style ) {
+	jQuery.attrHooks.style = {
+		get: function( elem ) {
+			// Return undefined in the case of empty string
+			// Normalize to lowercase since IE uppercases css property names
+			return elem.style.cssText.toLowerCase() || undefined;
+		},
+		set: function( elem, value ) {
+			return (elem.style.cssText = "" + value);
+		}
+	};
+}
+
+// Safari mis-reports the default selected property of an option
+// Accessing the parent's selectedIndex property fixes it
+if ( !jQuery.support.optSelected ) {
+	jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
+		get: function( elem ) {
+			var parent = elem.parentNode;
+
+			if ( parent ) {
+				parent.selectedIndex;
+
+				// Make sure that it also works with optgroups, see #5701
+				if ( parent.parentNode ) {
+					parent.parentNode.selectedIndex;
+				}
+			}
+			return null;
+		}
+	});
+}
+
+// Radios and checkboxes getter/setter
+if ( !jQuery.support.checkOn ) {
+	jQuery.each([ "radio", "checkbox" ], function() {
+		jQuery.valHooks[ this ] = {
+			get: function( elem ) {
+				// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
+				return elem.getAttribute("value") === null ? "on" : elem.value;
+			}
+		};
+	});
+}
+jQuery.each([ "radio", "checkbox" ], function() {
+	jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
+		set: function( elem, value ) {
+			if ( jQuery.isArray( value ) ) {
+				return (elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0);
+			}
+		}
+	});
+});
+
+
+
+
+var rnamespaces = /\.(.*)$/,
+	rformElems = /^(?:textarea|input|select)$/i,
+	rperiod = /\./g,
+	rspaces = / /g,
+	rescape = /[^\w\s.|`]/g,
+	fcleanup = function( nm ) {
+		return nm.replace(rescape, "\\$&");
+	};
+
+/*
+ * A number of helper functions used for managing events.
+ * Many of the ideas behind this code originated from
+ * Dean Edwards' addEvent library.
+ */
+jQuery.event = {
+
+	// Bind an event to an element
+	// Original by Dean Edwards
+	add: function( elem, types, handler, data ) {
+		if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
+			return;
+		}
+
+		if ( handler === false ) {
+			handler = returnFalse;
+		} else if ( !handler ) {
+			// Fixes bug #7229. Fix recommended by jdalton
+			return;
+		}
+
+		var handleObjIn, handleObj;
+
+		if ( handler.handler ) {
+			handleObjIn = handler;
+			handler = handleObjIn.handler;
+		}
+
+		// Make sure that the function being executed has a unique ID
+		if ( !handler.guid ) {
+			handler.guid = jQuery.guid++;
+		}
+
+		// Init the element's event structure
+		var elemData = jQuery._data( elem );
+
+		// If no elemData is found then we must be trying to bind to one of the
+		// banned noData elements
+		if ( !elemData ) {
+			return;
+		}
+
+		var events = elemData.events,
+			eventHandle = elemData.handle;
+
+		if ( !events ) {
+			elemData.events = events = {};
+		}
+
+		if ( !eventHandle ) {
+			elemData.handle = eventHandle = function( e ) {
+				// Discard the second event of a jQuery.event.trigger() and
+				// when an event is called after a page has unloaded
+				return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
+					jQuery.event.handle.apply( eventHandle.elem, arguments ) :
+					undefined;
+			};
+		}
+
+		// Add elem as a property of the handle function
+		// This is to prevent a memory leak with non-native events in IE.
+		eventHandle.elem = elem;
+
+		// Handle multiple events separated by a space
+		// jQuery(...).bind("mouseover mouseout", fn);
+		types = types.split(" ");
+
+		var type, i = 0, namespaces;
+
+		while ( (type = types[ i++ ]) ) {
+			handleObj = handleObjIn ?
+				jQuery.extend({}, handleObjIn) :
+				{ handler: handler, data: data };
+
+			// Namespaced event handlers
+			if ( type.indexOf(".") > -1 ) {
+				namespaces = type.split(".");
+				type = namespaces.shift();
+				handleObj.namespace = namespaces.slice(0).sort().join(".");
+
+			} else {
+				namespaces = [];
+				handleObj.namespace = "";
+			}
+
+			handleObj.type = type;
+			if ( !handleObj.guid ) {
+				handleObj.guid = handler.guid;
+			}
+
+			// Get the current list of functions bound to this event
+			var handlers = events[ type ],
+				special = jQuery.event.special[ type ] || {};
+
+			// Init the event handler queue
+			if ( !handlers ) {
+				handlers = events[ type ] = [];
+
+				// Check for a special event handler
+				// Only use addEventListener/attachEvent if the special
+				// events handler returns false
+				if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
+					// Bind the global event handler to the element
+					if ( elem.addEventListener ) {
+						elem.addEventListener( type, eventHandle, false );
+
+					} else if ( elem.attachEvent ) {
+						elem.attachEvent( "on" + type, eventHandle );
+					}
+				}
+			}
+
+			if ( special.add ) {
+				special.add.call( elem, handleObj );
+
+				if ( !handleObj.handler.guid ) {
+					handleObj.handler.guid = handler.guid;
+				}
+			}
+
+			// Add the function to the element's handler list
+			handlers.push( handleObj );
+
+			// Keep track of which events have been used, for event optimization
+			jQuery.event.global[ type ] = true;
+		}
+
+		// Nullify elem to prevent memory leaks in IE
+		elem = null;
+	},
+
+	global: {},
+
+	// Detach an event or set of events from an element
+	remove: function( elem, types, handler, pos ) {
+		// don't do events on text and comment nodes
+		if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
+			return;
+		}
+
+		if ( handler === false ) {
+			handler = returnFalse;
+		}
+
+		var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType,
+			elemData = jQuery.hasData( elem ) && jQuery._data( elem ),
+			events = elemData && elemData.events;
+
+		if ( !elemData || !events ) {
+			return;
+		}
+
+		// types is actually an event object here
+		if ( types && types.type ) {
+			handler = types.handler;
+			types = types.type;
+		}
+
+		// Unbind all events for the element
+		if ( !types || typeof types === "string" && types.charAt(0) === "." ) {
+			types = types || "";
+
+			for ( type in events ) {
+				jQuery.event.remove( elem, type + types );
+			}
+
+			return;
+		}
+
+		// Handle multiple events separated by a space
+		// jQuery(...).unbind("mouseover mouseout", fn);
+		types = types.split(" ");
+
+		while ( (type = types[ i++ ]) ) {
+			origType = type;
+			handleObj = null;
+			all = type.indexOf(".") < 0;
+			namespaces = [];
+
+			if ( !all ) {
+				// Namespaced event handlers
+				namespaces = type.split(".");
+				type = namespaces.shift();
+
+				namespace = new RegExp("(^|\\.)" +
+					jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)");
+			}
+
+			eventType = events[ type ];
+
+			if ( !eventType ) {
+				continue;
+			}
+
+			if ( !handler ) {
+				for ( j = 0; j < eventType.length; j++ ) {
+					handleObj = eventType[ j ];
+
+					if ( all || namespace.test( handleObj.namespace ) ) {
+						jQuery.event.remove( elem, origType, handleObj.handler, j );
+						eventType.splice( j--, 1 );
+					}
+				}
+
+				continue;
+			}
+
+			special = jQuery.event.special[ type ] || {};
+
+			for ( j = pos || 0; j < eventType.length; j++ ) {
+				handleObj = eventType[ j ];
+
+				if ( handler.guid === handleObj.guid ) {
+					// remove the given handler for the given type
+					if ( all || namespace.test( handleObj.namespace ) ) {
+						if ( pos == null ) {
+							eventType.splice( j--, 1 );
+						}
+
+						if ( special.remove ) {
+							special.remove.call( elem, handleObj );
+						}
+					}
+
+					if ( pos != null ) {
+						break;
+					}
+				}
+			}
+
+			// remove generic event handler if no more handlers exist
+			if ( eventType.length === 0 || pos != null && eventType.length === 1 ) {
+				if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) {
+					jQuery.removeEvent( elem, type, elemData.handle );
+				}
+
+				ret = null;
+				delete events[ type ];
+			}
+		}
+
+		// Remove the expando if it's no longer used
+		if ( jQuery.isEmptyObject( events ) ) {
+			var handle = elemData.handle;
+			if ( handle ) {
+				handle.elem = null;
+			}
+
+			delete elemData.events;
+			delete elemData.handle;
+
+			if ( jQuery.isEmptyObject( elemData ) ) {
+				jQuery.removeData( elem, undefined, true );
+			}
+		}
+	},
+	
+	// Events that are safe to short-circuit if no handlers are attached.
+	// Native DOM events should not be added, they may have inline handlers.
+	customEvent: {
+		"getData": true,
+		"setData": true,
+		"changeData": true
+	},
+
+	trigger: function( event, data, elem, onlyHandlers ) {
+		// Event object or event type
+		var type = event.type || event,
+			namespaces = [],
+			exclusive;
+
+		if ( type.indexOf("!") >= 0 ) {
+			// Exclusive events trigger only for the exact event (no namespaces)
+			type = type.slice(0, -1);
+			exclusive = true;
+		}
+
+		if ( type.indexOf(".") >= 0 ) {
+			// Namespaced trigger; create a regexp to match event type in handle()
+			namespaces = type.split(".");
+			type = namespaces.shift();
+			namespaces.sort();
+		}
+
+		if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
+			// No jQuery handlers for this event type, and it can't have inline handlers
+			return;
+		}
+
+		// Caller can pass in an Event, Object, or just an event type string
+		event = typeof event === "object" ?
+			// jQuery.Event object
+			event[ jQuery.expando ] ? event :
+			// Object literal
+			new jQuery.Event( type, event ) :
+			// Just the event type (string)
+			new jQuery.Event( type );
+
+		event.type = type;
+		event.exclusive = exclusive;
+		event.namespace = namespaces.join(".");
+		event.namespace_re = new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)");
+		
+		// triggerHandler() and global events don't bubble or run the default action
+		if ( onlyHandlers || !elem ) {
+			event.preventDefault();
+			event.stopPropagation();
+		}
+
+		// Handle a global trigger
+		if ( !elem ) {
+			// TODO: Stop taunting the data cache; remove global events and always attach to document
+			jQuery.each( jQuery.cache, function() {
+				// internalKey variable is just used to make it easier to find
+				// and potentially change this stuff later; currently it just
+				// points to jQuery.expando
+				var internalKey = jQuery.expando,
+					internalCache = this[ internalKey ];
+				if ( internalCache && internalCache.events && internalCache.events[ type ] ) {
+					jQuery.event.trigger( event, data, internalCache.handle.elem );
+				}
+			});
+			return;
+		}
+
+		// Don't do events on text and comment nodes
+		if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
+			return;
+		}
+
+		// Clean up the event in case it is being reused
+		event.result = undefined;
+		event.target = elem;
+
+		// Clone any incoming data and prepend the event, creating the handler arg list
+		data = data != null ? jQuery.makeArray( data ) : [];
+		data.unshift( event );
+
+		var cur = elem,
+			// IE doesn't like method names with a colon (#3533, #8272)
+			ontype = type.indexOf(":") < 0 ? "on" + type : "";
+
+		// Fire event on the current element, then bubble up the DOM tree
+		do {
+			var handle = jQuery._data( cur, "handle" );
+
+			event.currentTarget = cur;
+			if ( handle ) {
+				handle.apply( cur, data );
+			}
+
+			// Trigger an inline bound script
+			if ( ontype && jQuery.acceptData( cur ) && cur[ ontype ] && cur[ ontype ].apply( cur, data ) === false ) {
+				event.result = false;
+				event.preventDefault();
+			}
+
+			// Bubble up to document, then to window
+			cur = cur.parentNode || cur.ownerDocument || cur === event.target.ownerDocument && window;
+		} while ( cur && !event.isPropagationStopped() );
+
+		// If nobody prevented the default action, do it now
+		if ( !event.isDefaultPrevented() ) {
+			var old,
+				special = jQuery.event.special[ type ] || {};
+
+			if ( (!special._default || special._default.call( elem.ownerDocument, event ) === false) &&
+				!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
+
+				// Call a native DOM method on the target with the same name name as the event.
+				// Can't use an .isFunction)() check here because IE6/7 fails that test.
+				// IE<9 dies on focus to hidden element (#1486), may want to revisit a try/catch.
+				try {
+					if ( ontype && elem[ type ] ) {
+						// Don't re-trigger an onFOO event when we call its FOO() method
+						old = elem[ ontype ];
+
+						if ( old ) {
+							elem[ ontype ] = null;
+						}
+
+						jQuery.event.triggered = type;
+						elem[ type ]();
+					}
+				} catch ( ieError ) {}
+
+				if ( old ) {
+					elem[ ontype ] = old;
+				}
+
+				jQuery.event.triggered = undefined;
+			}
+		}
+		
+		return event.result;
+	},
+
+	handle: function( event ) {
+		event = jQuery.event.fix( event || window.event );
+		// Snapshot the handlers list since a called handler may add/remove events.
+		var handlers = ((jQuery._data( this, "events" ) || {})[ event.type ] || []).slice(0),
+			run_all = !event.exclusive && !event.namespace,
+			args = Array.prototype.slice.call( arguments, 0 );
+
+		// Use the fix-ed Event rather than the (read-only) native event
+		args[0] = event;
+		event.currentTarget = this;
+
+		for ( var j = 0, l = handlers.length; j < l; j++ ) {
+			var handleObj = handlers[ j ];
+
+			// Triggered event must 1) be non-exclusive and have no namespace, or
+			// 2) have namespace(s) a subset or equal to those in the bound event.
+			if ( run_all || event.namespace_re.test( handleObj.namespace ) ) {
+				// Pass in a reference to the handler function itself
+				// So that we can later remove it
+				event.handler = handleObj.handler;
+				event.data = handleObj.data;
+				event.handleObj = handleObj;
+
+				var ret = handleObj.handler.apply( this, args );
+
+				if ( ret !== undefined ) {
+					event.result = ret;
+					if ( ret === false ) {
+						event.preventDefault();
+						event.stopPropagation();
+					}
+				}
+
+				if ( event.isImmediatePropagationStopped() ) {
+					break;
+				}
+			}
+		}
+		return event.result;
+	},
+
+	props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
+
+	fix: function( event ) {
+		if ( event[ jQuery.expando ] ) {
+			return event;
+		}
+
+		// store a copy of the original event object
+		// and "clone" to set read-only properties
+		var originalEvent = event;
+		event = jQuery.Event( originalEvent );
+
+		for ( var i = this.props.length, prop; i; ) {
+			prop = this.props[ --i ];
+			event[ prop ] = originalEvent[ prop ];
+		}
+
+		// Fix target property, if necessary
+		if ( !event.target ) {
+			// Fixes #1925 where srcElement might not be defined either
+			event.target = event.srcElement || document;
+		}
+
+		// check if target is a textnode (safari)
+		if ( event.target.nodeType === 3 ) {
+			event.target = event.target.parentNode;
+		}
+
+		// Add relatedTarget, if necessary
+		if ( !event.relatedTarget && event.fromElement ) {
+			event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
+		}
+
+		// Calculate pageX/Y if missing and clientX/Y available
+		if ( event.pageX == null && event.clientX != null ) {
+			var eventDocument = event.target.ownerDocument || document,
+				doc = eventDocument.documentElement,
+				body = eventDocument.body;
+
+			event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
+			event.pageY = event.clientY + (doc && doc.scrollTop  || body && body.scrollTop  || 0) - (doc && doc.clientTop  || body && body.clientTop  || 0);
+		}
+
+		// Add which for key events
+		if ( event.which == null && (event.charCode != null || event.keyCode != null) ) {
+			event.which = event.charCode != null ? event.charCode : event.keyCode;
+		}
+
+		// Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
+		if ( !event.metaKey && event.ctrlKey ) {
+			event.metaKey = event.ctrlKey;
+		}
+
+		// Add which for click: 1 === left; 2 === middle; 3 === right
+		// Note: button is not normalized, so don't use it
+		if ( !event.which && event.button !== undefined ) {
+			event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
+		}
+
+		return event;
+	},
+
+	// Deprecated, use jQuery.guid instead
+	guid: 1E8,
+
+	// Deprecated, use jQuery.proxy instead
+	proxy: jQuery.proxy,
+
+	special: {
+		ready: {
+			// Make sure the ready event is setup
+			setup: jQuery.bindReady,
+			teardown: jQuery.noop
+		},
+
+		live: {
+			add: function( handleObj ) {
+				jQuery.event.add( this,
+					liveConvert( handleObj.origType, handleObj.selector ),
+					jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) );
+			},
+
+			remove: function( handleObj ) {
+				jQuery.event.remove( this, liveConvert( handleObj.origType, handleObj.selector ), handleObj );
+			}
+		},
+
+		beforeunload: {
+			setup: function( data, namespaces, eventHandle ) {
+				// We only want to do this special case on windows
+				if ( jQuery.isWindow( this ) ) {
+					this.onbeforeunload = eventHandle;
+				}
+			},
+
+			teardown: function( namespaces, eventHandle ) {
+				if ( this.onbeforeunload === eventHandle ) {
+					this.onbeforeunload = null;
+				}
+			}
+		}
+	}
+};
+
+jQuery.removeEvent = document.removeEventListener ?
+	function( elem, type, handle ) {
+		if ( elem.removeEventListener ) {
+			elem.removeEventListener( type, handle, false );
+		}
+	} :
+	function( elem, type, handle ) {
+		if ( elem.detachEvent ) {
+			elem.detachEvent( "on" + type, handle );
+		}
+	};
+
+jQuery.Event = function( src, props ) {
+	// Allow instantiation without the 'new' keyword
+	if ( !this.preventDefault ) {
+		return new jQuery.Event( src, props );
+	}
+
+	// Event object
+	if ( src && src.type ) {
+		this.originalEvent = src;
+		this.type = src.type;
+
+		// Events bubbling up the document may have been marked as prevented
+		// by a handler lower down the tree; reflect the correct value.
+		this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false ||
+			src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse;
+
+	// Event type
+	} else {
+		this.type = src;
+	}
+
+	// Put explicitly provided properties onto the event object
+	if ( props ) {
+		jQuery.extend( this, props );
+	}
+
+	// timeStamp is buggy for some events on Firefox(#3843)
+	// So we won't rely on the native value
+	this.timeStamp = jQuery.now();
+
+	// Mark it as fixed
+	this[ jQuery.expando ] = true;
+};
+
+function returnFalse() {
+	return false;
+}
+function returnTrue() {
+	return true;
+}
+
+// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
+// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
+jQuery.Event.prototype = {
+	preventDefault: function() {
+		this.isDefaultPrevented = returnTrue;
+
+		var e = this.originalEvent;
+		if ( !e ) {
+			return;
+		}
+
+		// if preventDefault exists run it on the original event
+		if ( e.preventDefault ) {
+			e.preventDefault();
+
+		// otherwise set the returnValue property of the original event to false (IE)
+		} else {
+			e.returnValue = false;
+		}
+	},
+	stopPropagation: function() {
+		this.isPropagationStopped = returnTrue;
+
+		var e = this.originalEvent;
+		if ( !e ) {
+			return;
+		}
+		// if stopPropagation exists run it on the original event
+		if ( e.stopPropagation ) {
+			e.stopPropagation();
+		}
+		// otherwise set the cancelBubble property of the original event to true (IE)
+		e.cancelBubble = true;
+	},
+	stopImmediatePropagation: function() {
+		this.isImmediatePropagationStopped = returnTrue;
+		this.stopPropagation();
+	},
+	isDefaultPrevented: returnFalse,
+	isPropagationStopped: returnFalse,
+	isImmediatePropagationStopped: returnFalse
+};
+
+// Checks if an event happened on an element within another element
+// Used in jQuery.event.special.mouseenter and mouseleave handlers
+var withinElement = function( event ) {
+
+	// Check if mouse(over|out) are still within the same parent element
+	var related = event.relatedTarget,
+		inside = false,
+		eventType = event.type;
+
+	event.type = event.data;
+
+	if ( related !== this ) {
+
+		if ( related ) {
+			inside = jQuery.contains( this, related );
+		}
+
+		if ( !inside ) {
+
+			jQuery.event.handle.apply( this, arguments );
+
+			event.type = eventType;
+		}
+	}
+},
+
+// In case of event delegation, we only need to rename the event.type,
+// liveHandler will take care of the rest.
+delegate = function( event ) {
+	event.type = event.data;
+	jQuery.event.handle.apply( this, arguments );
+};
+
+// Create mouseenter and mouseleave events
+jQuery.each({
+	mouseenter: "mouseover",
+	mouseleave: "mouseout"
+}, function( orig, fix ) {
+	jQuery.event.special[ orig ] = {
+		setup: function( data ) {
+			jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig );
+		},
+		teardown: function( data ) {
+			jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement );
+		}
+	};
+});
+
+// submit delegation
+if ( !jQuery.support.submitBubbles ) {
+
+	jQuery.event.special.submit = {
+		setup: function( data, namespaces ) {
+			if ( !jQuery.nodeName( this, "form" ) ) {
+				jQuery.event.add(this, "click.specialSubmit", function( e ) {
+					// Avoid triggering error on non-existent type attribute in IE VML (#7071)
+					var elem = e.target,
+						type = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.type : "";
+
+					if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) {
+						trigger( "submit", this, arguments );
+					}
+				});
+
+				jQuery.event.add(this, "keypress.specialSubmit", function( e ) {
+					var elem = e.target,
+						type = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.type : "";
+
+					if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) {
+						trigger( "submit", this, arguments );
+					}
+				});
+
+			} else {
+				return false;
+			}
+		},
+
+		teardown: function( namespaces ) {
+			jQuery.event.remove( this, ".specialSubmit" );
+		}
+	};
+
+}
+
+// change delegation, happens here so we have bind.
+if ( !jQuery.support.changeBubbles ) {
+
+	var changeFilters,
+
+	getVal = function( elem ) {
+		var type = jQuery.nodeName( elem, "input" ) ? elem.type : "",
+			val = elem.value;
+
+		if ( type === "radio" || type === "checkbox" ) {
+			val = elem.checked;
+
+		} else if ( type === "select-multiple" ) {
+			val = elem.selectedIndex > -1 ?
+				jQuery.map( elem.options, function( elem ) {
+					return elem.selected;
+				}).join("-") :
+				"";
+
+		} else if ( jQuery.nodeName( elem, "select" ) ) {
+			val = elem.selectedIndex;
+		}
+
+		return val;
+	},
+
+	testChange = function testChange( e ) {
+		var elem = e.target, data, val;
+
+		if ( !rformElems.test( elem.nodeName ) || elem.readOnly ) {
+			return;
+		}
+
+		data = jQuery._data( elem, "_change_data" );
+		val = getVal(elem);
+
+		// the current data will be also retrieved by beforeactivate
+		if ( e.type !== "focusout" || elem.type !== "radio" ) {
+			jQuery._data( elem, "_change_data", val );
+		}
+
+		if ( data === undefined || val === data ) {
+			return;
+		}
+
+		if ( data != null || val ) {
+			e.type = "change";
+			e.liveFired = undefined;
+			jQuery.event.trigger( e, arguments[1], elem );
+		}
+	};
+
+	jQuery.event.special.change = {
+		filters: {
+			focusout: testChange,
+
+			beforedeactivate: testChange,
+
+			click: function( e ) {
+				var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : "";
+
+				if ( type === "radio" || type === "checkbox" || jQuery.nodeName( elem, "select" ) ) {
+					testChange.call( this, e );
+				}
+			},
+
+			// Change has to be called before submit
+			// Keydown will be called before keypress, which is used in submit-event delegation
+			keydown: function( e ) {
+				var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : "";
+
+				if ( (e.keyCode === 13 && !jQuery.nodeName( elem, "textarea" ) ) ||
+					(e.keyCode === 32 && (type === "checkbox" || type === "radio")) ||
+					type === "select-multiple" ) {
+					testChange.call( this, e );
+				}
+			},
+
+			// Beforeactivate happens also before the previous element is blurred
+			// with this event you can't trigger a change event, but you can store
+			// information
+			beforeactivate: function( e ) {
+				var elem = e.target;
+				jQuery._data( elem, "_change_data", getVal(elem) );
+			}
+		},
+
+		setup: function( data, namespaces ) {
+			if ( this.type === "file" ) {
+				return false;
+			}
+
+			for ( var type in changeFilters ) {
+				jQuery.event.add( this, type + ".specialChange", changeFilters[type] );
+			}
+
+			return rformElems.test( this.nodeName );
+		},
+
+		teardown: function( namespaces ) {
+			jQuery.event.remove( this, ".specialChange" );
+
+			return rformElems.test( this.nodeName );
+		}
+	};
+
+	changeFilters = jQuery.event.special.change.filters;
+
+	// Handle when the input is .focus()'d
+	changeFilters.focus = changeFilters.beforeactivate;
+}
+
+function trigger( type, elem, args ) {
+	// Piggyback on a donor event to simulate a different one.
+	// Fake originalEvent to avoid donor's stopPropagation, but if the
+	// simulated event prevents default then we do the same on the donor.
+	// Don't pass args or remember liveFired; they apply to the donor event.
+	var event = jQuery.extend( {}, args[ 0 ] );
+	event.type = type;
+	event.originalEvent = {};
+	event.liveFired = undefined;
+	jQuery.event.handle.call( elem, event );
+	if ( event.isDefaultPrevented() ) {
+		args[ 0 ].preventDefault();
+	}
+}
+
+// Create "bubbling" focus and blur events
+if ( !jQuery.support.focusinBubbles ) {
+	jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
+
+		// Attach a single capturing handler while someone wants focusin/focusout
+		var attaches = 0;
+
+		jQuery.event.special[ fix ] = {
+			setup: function() {
+				if ( attaches++ === 0 ) {
+					document.addEventListener( orig, handler, true );
+				}
+			},
+			teardown: function() {
+				if ( --attaches === 0 ) {
+					document.removeEventListener( orig, handler, true );
+				}
+			}
+		};
+
+		function handler( donor ) {
+			// Donor event is always a native one; fix it and switch its type.
+			// Let focusin/out handler cancel the donor focus/blur event.
+			var e = jQuery.event.fix( donor );
+			e.type = fix;
+			e.originalEvent = {};
+			jQuery.event.trigger( e, null, e.target );
+			if ( e.isDefaultPrevented() ) {
+				donor.preventDefault();
+			}
+		}
+	});
+}
+
+jQuery.each(["bind", "one"], function( i, name ) {
+	jQuery.fn[ name ] = function( type, data, fn ) {
+		var handler;
+
+		// Handle object literals
+		if ( typeof type === "object" ) {
+			for ( var key in type ) {
+				this[ name ](key, data, type[key], fn);
+			}
+			return this;
+		}
+
+		if ( arguments.length === 2 || data === false ) {
+			fn = data;
+			data = undefined;
+		}
+
+		if ( name === "one" ) {
+			handler = function( event ) {
+				jQuery( this ).unbind( event, handler );
+				return fn.apply( this, arguments );
+			};
+			handler.guid = fn.guid || jQuery.guid++;
+		} else {
+			handler = fn;
+		}
+
+		if ( type === "unload" && name !== "one" ) {
+			this.one( type, data, fn );
+
+		} else {
+			for ( var i = 0, l = this.length; i < l; i++ ) {
+				jQuery.event.add( this[i], type, handler, data );
+			}
+		}
+
+		return this;
+	};
+});
+
+jQuery.fn.extend({
+	unbind: function( type, fn ) {
+		// Handle object literals
+		if ( typeof type === "object" && !type.preventDefault ) {
+			for ( var key in type ) {
+				this.unbind(key, type[key]);
+			}
+
+		} else {
+			for ( var i = 0, l = this.length; i < l; i++ ) {
+				jQuery.event.remove( this[i], type, fn );
+			}
+		}
+
+		return this;
+	},
+
+	delegate: function( selector, types, data, fn ) {
+		return this.live( types, data, fn, selector );
+	},
+
+	undelegate: function( selector, types, fn ) {
+		if ( arguments.length === 0 ) {
+			return this.unbind( "live" );
+
+		} else {
+			return this.die( types, null, fn, selector );
+		}
+	},
+
+	trigger: function( type, data ) {
+		return this.each(function() {
+			jQuery.event.trigger( type, data, this );
+		});
+	},
+
+	triggerHandler: function( type, data ) {
+		if ( this[0] ) {
+			return jQuery.event.trigger( type, data, this[0], true );
+		}
+	},
+
+	toggle: function( fn ) {
+		// Save reference to arguments for access in closure
+		var args = arguments,
+			guid = fn.guid || jQuery.guid++,
+			i = 0,
+			toggler = function( event ) {
+				// Figure out which function to execute
+				var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i;
+				jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 );
+
+				// Make sure that clicks stop
+				event.preventDefault();
+
+				// and execute the function
+				return args[ lastToggle ].apply( this, arguments ) || false;
+			};
+
+		// link all the functions, so any of them can unbind this click handler
+		toggler.guid = guid;
+		while ( i < args.length ) {
+			args[ i++ ].guid = guid;
+		}
+
+		return this.click( toggler );
+	},
+
+	hover: function( fnOver, fnOut ) {
+		return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
+	}
+});
+
+var liveMap = {
+	focus: "focusin",
+	blur: "focusout",
+	mouseenter: "mouseover",
+	mouseleave: "mouseout"
+};
+
+jQuery.each(["live", "die"], function( i, name ) {
+	jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) {
+		var type, i = 0, match, namespaces, preType,
+			selector = origSelector || this.selector,
+			context = origSelector ? this : jQuery( this.context );
+
+		if ( typeof types === "object" && !types.preventDefault ) {
+			for ( var key in types ) {
+				context[ name ]( key, data, types[key], selector );
+			}
+
+			return this;
+		}
+
+		if ( name === "die" && !types &&
+					origSelector && origSelector.charAt(0) === "." ) {
+
+			context.unbind( origSelector );
+
+			return this;
+		}
+
+		if ( data === false || jQuery.isFunction( data ) ) {
+			fn = data || returnFalse;
+			data = undefined;
+		}
+
+		types = (types || "").split(" ");
+
+		while ( (type = types[ i++ ]) != null ) {
+			match = rnamespaces.exec( type );
+			namespaces = "";
+
+			if ( match )  {
+				namespaces = match[0];
+				type = type.replace( rnamespaces, "" );
+			}
+
+			if ( type === "hover" ) {
+				types.push( "mouseenter" + namespaces, "mouseleave" + namespaces );
+				continue;
+			}
+
+			preType = type;
+
+			if ( liveMap[ type ] ) {
+				types.push( liveMap[ type ] + namespaces );
+				type = type + namespaces;
+
+			} else {
+				type = (liveMap[ type ] || type) + namespaces;
+			}
+
+			if ( name === "live" ) {
+				// bind live handler
+				for ( var j = 0, l = context.length; j < l; j++ ) {
+					jQuery.event.add( context[j], "live." + liveConvert( type, selector ),
+						{ data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } );
+				}
+
+			} else {
+				// unbind live handler
+				context.unbind( "live." + liveConvert( type, selector ), fn );
+			}
+		}
+
+		return this;
+	};
+});
+
+function liveHandler( event ) {
+	var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret,
+		elems = [],
+		selectors = [],
+		events = jQuery._data( this, "events" );
+
+	// Make sure we avoid non-left-click bubbling in Firefox (#3861) and disabled elements in IE (#6911)
+	if ( event.liveFired === this || !events || !events.live || event.target.disabled || event.button && event.type === "click" ) {
+		return;
+	}
+
+	if ( event.namespace ) {
+		namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)");
+	}
+
+	event.liveFired = this;
+
+	var live = events.live.slice(0);
+
+	for ( j = 0; j < live.length; j++ ) {
+		handleObj = live[j];
+
+		if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) {
+			selectors.push( handleObj.selector );
+
+		} else {
+			live.splice( j--, 1 );
+		}
+	}
+
+	match = jQuery( event.target ).closest( selectors, event.currentTarget );
+
+	for ( i = 0, l = match.length; i < l; i++ ) {
+		close = match[i];
+
+		for ( j = 0; j < live.length; j++ ) {
+			handleObj = live[j];
+
+			if ( close.selector === handleObj.selector && (!namespace || namespace.test( handleObj.namespace )) && !close.elem.disabled ) {
+				elem = close.elem;
+				related = null;
+
+				// Those two events require additional checking
+				if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) {
+					event.type = handleObj.preType;
+					related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0];
+
+					// Make sure not to accidentally match a child element with the same selector
+					if ( related && jQuery.contains( elem, related ) ) {
+						related = elem;
+					}
+				}
+
+				if ( !related || related !== elem ) {
+					elems.push({ elem: elem, handleObj: handleObj, level: close.level });
+				}
+			}
+		}
+	}
+
+	for ( i = 0, l = elems.length; i < l; i++ ) {
+		match = elems[i];
+
+		if ( maxLevel && match.level > maxLevel ) {
+			break;
+		}
+
+		event.currentTarget = match.elem;
+		event.data = match.handleObj.data;
+		event.handleObj = match.handleObj;
+
+		ret = match.handleObj.origHandler.apply( match.elem, arguments );
+
+		if ( ret === false || event.isPropagationStopped() ) {
+			maxLevel = match.level;
+
+			if ( ret === false ) {
+				stop = false;
+			}
+			if ( event.isImmediatePropagationStopped() ) {
+				break;
+			}
+		}
+	}
+
+	return stop;
+}
+
+function liveConvert( type, selector ) {
+	return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspaces, "&");
+}
+
+jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
+	"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
+	"change select submit keydown keypress keyup error").split(" "), function( i, name ) {
+
+	// Handle event binding
+	jQuery.fn[ name ] = function( data, fn ) {
+		if ( fn == null ) {
+			fn = data;
+			data = null;
+		}
+
+		return arguments.length > 0 ?
+			this.bind( name, data, fn ) :
+			this.trigger( name );
+	};
+
+	if ( jQuery.attrFn ) {
+		jQuery.attrFn[ name ] = true;
+	}
+});
+
+
+
+/*!
+ * Sizzle CSS Selector Engine
+ *  Copyright 2011, The Dojo Foundation
+ *  Released under the MIT, BSD, and GPL Licenses.
+ *  More information: http://sizzlejs.com/
  */
-(function(A,w){function ma(){if(!c.isReady){try{s.documentElement.doScroll("left")}catch(a){setTimeout(ma,1);return}c.ready()}}function Qa(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function X(a,b,d,f,e,j){var i=a.length;if(typeof b==="object"){for(var o in b)X(a,o,b[o],f,e,d);return a}if(d!==w){f=!j&&f&&c.isFunction(d);for(o=0;o<i;o++)e(a[o],b,f?d.call(a[o],o,e(a[o],b)):d,j);return a}return i?
-e(a[0],b):w}function J(){return(new Date).getTime()}function Y(){return false}function Z(){return true}function na(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function oa(a){var b,d=[],f=[],e=arguments,j,i,o,k,n,r;i=c.data(this,"events");if(!(a.liveFired===this||!i||!i.live||a.button&&a.type==="click")){a.liveFired=this;var u=i.live.slice(0);for(k=0;k<u.length;k++){i=u[k];i.origType.replace(O,"")===a.type?f.push(i.selector):u.splice(k--,1)}j=c(a.target).closest(f,a.currentTarget);n=0;for(r=
-j.length;n<r;n++)for(k=0;k<u.length;k++){i=u[k];if(j[n].selector===i.selector){o=j[n].elem;f=null;if(i.preType==="mouseenter"||i.preType==="mouseleave")f=c(a.relatedTarget).closest(i.selector)[0];if(!f||f!==o)d.push({elem:o,handleObj:i})}}n=0;for(r=d.length;n<r;n++){j=d[n];a.currentTarget=j.elem;a.data=j.handleObj.data;a.handleObj=j.handleObj;if(j.handleObj.origHandler.apply(j.elem,e)===false){b=false;break}}return b}}function pa(a,b){return"live."+(a&&a!=="*"?a+".":"")+b.replace(/\./g,"`").replace(/ /g,
-"&")}function qa(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function ra(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var f=c.data(a[d++]),e=c.data(this,f);if(f=f&&f.events){delete e.handle;e.events={};for(var j in f)for(var i in f[j])c.event.add(this,j,f[j][i],f[j][i].data)}}})}function sa(a,b,d){var f,e,j;b=b&&b[0]?b[0].ownerDocument||b[0]:s;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&b===s&&!ta.test(a[0])&&(c.support.checkClone||!ua.test(a[0]))){e=
-true;if(j=c.fragments[a[0]])if(j!==1)f=j}if(!f){f=b.createDocumentFragment();c.clean(a,b,f,d)}if(e)c.fragments[a[0]]=j?f:1;return{fragment:f,cacheable:e}}function K(a,b){var d={};c.each(va.concat.apply([],va.slice(0,b)),function(){d[this]=a});return d}function wa(a){return"scrollTo"in a&&a.document?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var c=function(a,b){return new c.fn.init(a,b)},Ra=A.jQuery,Sa=A.$,s=A.document,T,Ta=/^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,Ua=/^.[^:#\[\.,]*$/,Va=/\S/,
-Wa=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,Xa=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,P=navigator.userAgent,xa=false,Q=[],L,$=Object.prototype.toString,aa=Object.prototype.hasOwnProperty,ba=Array.prototype.push,R=Array.prototype.slice,ya=Array.prototype.indexOf;c.fn=c.prototype={init:function(a,b){var d,f;if(!a)return this;if(a.nodeType){this.context=this[0]=a;this.length=1;return this}if(a==="body"&&!b){this.context=s;this[0]=s.body;this.selector="body";this.length=1;return this}if(typeof a==="string")if((d=Ta.exec(a))&&
-(d[1]||!b))if(d[1]){f=b?b.ownerDocument||b:s;if(a=Xa.exec(a))if(c.isPlainObject(b)){a=[s.createElement(a[1])];c.fn.attr.call(a,b,true)}else a=[f.createElement(a[1])];else{a=sa([d[1]],[f]);a=(a.cacheable?a.fragment.cloneNode(true):a.fragment).childNodes}return c.merge(this,a)}else{if(b=s.getElementById(d[2])){if(b.id!==d[2])return T.find(a);this.length=1;this[0]=b}this.context=s;this.selector=a;return this}else if(!b&&/^\w+$/.test(a)){this.selector=a;this.context=s;a=s.getElementsByTagName(a);return c.merge(this,
-a)}else return!b||b.jquery?(b||T).find(a):c(b).find(a);else if(c.isFunction(a))return T.ready(a);if(a.selector!==w){this.selector=a.selector;this.context=a.context}return c.makeArray(a,this)},selector:"",jquery:"1.4.2",length:0,size:function(){return this.length},toArray:function(){return R.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this.slice(a)[0]:this[a]},pushStack:function(a,b,d){var f=c();c.isArray(a)?ba.apply(f,a):c.merge(f,a);f.prevObject=this;f.context=this.context;if(b===
-"find")f.selector=this.selector+(this.selector?" ":"")+d;else if(b)f.selector=this.selector+"."+b+"("+d+")";return f},each:function(a,b){return c.each(this,a,b)},ready:function(a){c.bindReady();if(c.isReady)a.call(s,c);else Q&&Q.push(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(R.apply(this,arguments),"slice",R.call(arguments).join(","))},map:function(a){return this.pushStack(c.map(this,
-function(b,d){return a.call(b,d,b)}))},end:function(){return this.prevObject||c(null)},push:ba,sort:[].sort,splice:[].splice};c.fn.init.prototype=c.fn;c.extend=c.fn.extend=function(){var a=arguments[0]||{},b=1,d=arguments.length,f=false,e,j,i,o;if(typeof a==="boolean"){f=a;a=arguments[1]||{};b=2}if(typeof a!=="object"&&!c.isFunction(a))a={};if(d===b){a=this;--b}for(;b<d;b++)if((e=arguments[b])!=null)for(j in e){i=a[j];o=e[j];if(a!==o)if(f&&o&&(c.isPlainObject(o)||c.isArray(o))){i=i&&(c.isPlainObject(i)||
-c.isArray(i))?i:c.isArray(o)?[]:{};a[j]=c.extend(f,i,o)}else if(o!==w)a[j]=o}return a};c.extend({noConflict:function(a){A.$=Sa;if(a)A.jQuery=Ra;return c},isReady:false,ready:function(){if(!c.isReady){if(!s.body)return setTimeout(c.ready,13);c.isReady=true;if(Q){for(var a,b=0;a=Q[b++];)a.call(s,c);Q=null}c.fn.triggerHandler&&c(s).triggerHandler("ready")}},bindReady:function(){if(!xa){xa=true;if(s.readyState==="complete")return c.ready();if(s.addEventListener){s.addEventListener("DOMContentLoaded",
-L,false);A.addEventListener("load",c.ready,false)}else if(s.attachEvent){s.attachEvent("onreadystatechange",L);A.attachEvent("onload",c.ready);var a=false;try{a=A.frameElement==null}catch(b){}s.documentElement.doScroll&&a&&ma()}}},isFunction:function(a){return $.call(a)==="[object Function]"},isArray:function(a){return $.call(a)==="[object Array]"},isPlainObject:function(a){if(!a||$.call(a)!=="[object Object]"||a.nodeType||a.setInterval)return false;if(a.constructor&&!aa.call(a,"constructor")&&!aa.call(a.constructor.prototype,
-"isPrototypeOf"))return false;var b;for(b in a);return b===w||aa.call(a,b)},isEmptyObject:function(a){for(var b in a)return false;return true},error:function(a){throw a;},parseJSON:function(a){if(typeof a!=="string"||!a)return null;a=c.trim(a);if(/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return A.JSON&&A.JSON.parse?A.JSON.parse(a):(new Function("return "+
-a))();else c.error("Invalid JSON: "+a)},noop:function(){},globalEval:function(a){if(a&&Va.test(a)){var b=s.getElementsByTagName("head")[0]||s.documentElement,d=s.createElement("script");d.type="text/javascript";if(c.support.scriptEval)d.appendChild(s.createTextNode(a));else d.text=a;b.insertBefore(d,b.firstChild);b.removeChild(d)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,b,d){var f,e=0,j=a.length,i=j===w||c.isFunction(a);if(d)if(i)for(f in a){if(b.apply(a[f],
-d)===false)break}else for(;e<j;){if(b.apply(a[e++],d)===false)break}else if(i)for(f in a){if(b.call(a[f],f,a[f])===false)break}else for(d=a[0];e<j&&b.call(d,e,d)!==false;d=a[++e]);return a},trim:function(a){return(a||"").replace(Wa,"")},makeArray:function(a,b){b=b||[];if(a!=null)a.length==null||typeof a==="string"||c.isFunction(a)||typeof a!=="function"&&a.setInterval?ba.call(b,a):c.merge(b,a);return b},inArray:function(a,b){if(b.indexOf)return b.indexOf(a);for(var d=0,f=b.length;d<f;d++)if(b[d]===
-a)return d;return-1},merge:function(a,b){var d=a.length,f=0;if(typeof b.length==="number")for(var e=b.length;f<e;f++)a[d++]=b[f];else for(;b[f]!==w;)a[d++]=b[f++];a.length=d;return a},grep:function(a,b,d){for(var f=[],e=0,j=a.length;e<j;e++)!d!==!b(a[e],e)&&f.push(a[e]);return f},map:function(a,b,d){for(var f=[],e,j=0,i=a.length;j<i;j++){e=b(a[j],j,d);if(e!=null)f[f.length]=e}return f.concat.apply([],f)},guid:1,proxy:function(a,b,d){if(arguments.length===2)if(typeof b==="string"){d=a;a=d[b];b=w}else if(b&&
-!c.isFunction(b)){d=b;b=w}if(!b&&a)b=function(){return a.apply(d||this,arguments)};if(a)b.guid=a.guid=a.guid||b.guid||c.guid++;return b},uaMatch:function(a){a=a.toLowerCase();a=/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version)?[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||!/compatible/.test(a)&&/(mozilla)(?:.*? rv:([\w.]+))?/.exec(a)||[];return{browser:a[1]||"",version:a[2]||"0"}},browser:{}});P=c.uaMatch(P);if(P.browser){c.browser[P.browser]=true;c.browser.version=P.version}if(c.browser.webkit)c.browser.safari=
-true;if(ya)c.inArray=function(a,b){return ya.call(b,a)};T=c(s);if(s.addEventListener)L=function(){s.removeEventListener("DOMContentLoaded",L,false);c.ready()};else if(s.attachEvent)L=function(){if(s.readyState==="complete"){s.detachEvent("onreadystatechange",L);c.ready()}};(function(){c.support={};var a=s.documentElement,b=s.createElement("script"),d=s.createElement("div"),f="script"+J();d.style.display="none";d.innerHTML="   <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
-var e=d.getElementsByTagName("*"),j=d.getElementsByTagName("a")[0];if(!(!e||!e.length||!j)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(j.getAttribute("style")),hrefNormalized:j.getAttribute("href")==="/a",opacity:/^0.55$/.test(j.style.opacity),cssFloat:!!j.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:s.createElement("select").appendChild(s.createElement("option")).selected,
-parentNode:d.removeChild(d.appendChild(s.createElement("div"))).parentNode===null,deleteExpando:true,checkClone:false,scriptEval:false,noCloneEvent:true,boxModel:null};b.type="text/javascript";try{b.appendChild(s.createTextNode("window."+f+"=1;"))}catch(i){}a.insertBefore(b,a.firstChild);if(A[f]){c.support.scriptEval=true;delete A[f]}try{delete b.test}catch(o){c.support.deleteExpando=false}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function k(){c.support.noCloneEvent=
-false;d.detachEvent("onclick",k)});d.cloneNode(true).fireEvent("onclick")}d=s.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=s.createDocumentFragment();a.appendChild(d.firstChild);c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var k=s.createElement("div");k.style.width=k.style.paddingLeft="1px";s.body.appendChild(k);c.boxModel=c.support.boxModel=k.offsetWidth===2;s.body.removeChild(k).style.display="none"});a=function(k){var n=
-s.createElement("div");k="on"+k;var r=k in n;if(!r){n.setAttribute(k,"return;");r=typeof n[k]==="function"}return r};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=e=j=null}})();c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};var G="jQuery"+J(),Ya=0,za={};c.extend({cache:{},expando:G,noData:{embed:true,object:true,
-applet:true},data:function(a,b,d){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var f=a[G],e=c.cache;if(!f&&typeof b==="string"&&d===w)return null;f||(f=++Ya);if(typeof b==="object"){a[G]=f;e[f]=c.extend(true,{},b)}else if(!e[f]){a[G]=f;e[f]={}}a=e[f];if(d!==w)a[b]=d;return typeof b==="string"?a[b]:a}},removeData:function(a,b){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var d=a[G],f=c.cache,e=f[d];if(b){if(e){delete e[b];c.isEmptyObject(e)&&c.removeData(a)}}else{if(c.support.deleteExpando)delete a[c.expando];
-else a.removeAttribute&&a.removeAttribute(c.expando);delete f[d]}}}});c.fn.extend({data:function(a,b){if(typeof a==="undefined"&&this.length)return c.data(this[0]);else if(typeof a==="object")return this.each(function(){c.data(this,a)});var d=a.split(".");d[1]=d[1]?"."+d[1]:"";if(b===w){var f=this.triggerHandler("getData"+d[1]+"!",[d[0]]);if(f===w&&this.length)f=c.data(this[0],a);return f===w&&d[1]?this.data(d[0]):f}else return this.trigger("setData"+d[1]+"!",[d[0],b]).each(function(){c.data(this,
-a,b)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var f=c.data(a,b);if(!d)return f||[];if(!f||c.isArray(d))f=c.data(a,b,c.makeArray(d));else f.push(d);return f}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),f=d.shift();if(f==="inprogress")f=d.shift();if(f){b==="fx"&&d.unshift("inprogress");f.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b===
-w)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this,a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var Aa=/[\n\t]/g,ca=/\s+/,Za=/\r/g,$a=/href|src|style/,ab=/(button|input)/i,bb=/(button|input|object|select|textarea)/i,
-cb=/^(a|area)$/i,Ba=/radio|checkbox/;c.fn.extend({attr:function(a,b){return X(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(n){var r=c(this);r.addClass(a.call(this,n,r.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1)if(e.className){for(var j=" "+e.className+" ",
-i=e.className,o=0,k=b.length;o<k;o++)if(j.indexOf(" "+b[o]+" ")<0)i+=" "+b[o];e.className=c.trim(i)}else e.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(k){var n=c(this);n.removeClass(a.call(this,k,n.attr("class")))});if(a&&typeof a==="string"||a===w)for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1&&e.className)if(a){for(var j=(" "+e.className+" ").replace(Aa," "),i=0,o=b.length;i<o;i++)j=j.replace(" "+b[i]+" ",
-" ");e.className=c.trim(j)}else e.className=""}return this},toggleClass:function(a,b){var d=typeof a,f=typeof b==="boolean";if(c.isFunction(a))return this.each(function(e){var j=c(this);j.toggleClass(a.call(this,e,j.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var e,j=0,i=c(this),o=b,k=a.split(ca);e=k[j++];){o=f?o:!i.hasClass(e);i[o?"addClass":"removeClass"](e)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this,"__className__",this.className);this.className=
-this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(Aa," ").indexOf(a)>-1)return true;return false},val:function(a){if(a===w){var b=this[0];if(b){if(c.nodeName(b,"option"))return(b.attributes.value||{}).specified?b.value:b.text;if(c.nodeName(b,"select")){var d=b.selectedIndex,f=[],e=b.options;b=b.type==="select-one";if(d<0)return null;var j=b?d:0;for(d=b?d+1:e.length;j<d;j++){var i=
-e[j];if(i.selected){a=c(i).val();if(b)return a;f.push(a)}}return f}if(Ba.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Za,"")}return w}var o=c.isFunction(a);return this.each(function(k){var n=c(this),r=a;if(this.nodeType===1){if(o)r=a.call(this,k,n.val());if(typeof r==="number")r+="";if(c.isArray(r)&&Ba.test(this.type))this.checked=c.inArray(n.val(),r)>=0;else if(c.nodeName(this,"select")){var u=c.makeArray(r);c("option",this).each(function(){this.selected=
-c.inArray(c(this).val(),u)>=0});if(!u.length)this.selectedIndex=-1}else this.value=r}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(a,b,d,f){if(!a||a.nodeType===3||a.nodeType===8)return w;if(f&&b in c.attrFn)return c(a)[b](d);f=a.nodeType!==1||!c.isXMLDoc(a);var e=d!==w;b=f&&c.props[b]||b;if(a.nodeType===1){var j=$a.test(b);if(b in a&&f&&!j){if(e){b==="type"&&ab.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed");
-a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&&b.specified?b.value:bb.test(a.nodeName)||cb.test(a.nodeName)&&a.href?0:w;return a[b]}if(!c.support.style&&f&&b==="style"){if(e)a.style.cssText=""+d;return a.style.cssText}e&&a.setAttribute(b,""+d);a=!c.support.hrefNormalized&&f&&j?a.getAttribute(b,2):a.getAttribute(b);return a===null?w:a}return c.style(a,b,d)}});var O=/\.(.*)$/,db=function(a){return a.replace(/[^\w\s\.\|`]/g,
-function(b){return"\\"+b})};c.event={add:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){if(a.setInterval&&a!==A&&!a.frameElement)a=A;var e,j;if(d.handler){e=d;d=e.handler}if(!d.guid)d.guid=c.guid++;if(j=c.data(a)){var i=j.events=j.events||{},o=j.handle;if(!o)j.handle=o=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(o.elem,arguments):w};o.elem=a;b=b.split(" ");for(var k,n=0,r;k=b[n++];){j=e?c.extend({},e):{handler:d,data:f};if(k.indexOf(".")>-1){r=k.split(".");
-k=r.shift();j.namespace=r.slice(0).sort().join(".")}else{r=[];j.namespace=""}j.type=k;j.guid=d.guid;var u=i[k],z=c.event.special[k]||{};if(!u){u=i[k]=[];if(!z.setup||z.setup.call(a,f,r,o)===false)if(a.addEventListener)a.addEventListener(k,o,false);else a.attachEvent&&a.attachEvent("on"+k,o)}if(z.add){z.add.call(a,j);if(!j.handler.guid)j.handler.guid=d.guid}u.push(j);c.event.global[k]=true}a=null}}},global:{},remove:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){var e,j=0,i,o,k,n,r,u,z=c.data(a),
-C=z&&z.events;if(z&&C){if(b&&b.type){d=b.handler;b=b.type}if(!b||typeof b==="string"&&b.charAt(0)==="."){b=b||"";for(e in C)c.event.remove(a,e+b)}else{for(b=b.split(" ");e=b[j++];){n=e;i=e.indexOf(".")<0;o=[];if(!i){o=e.split(".");e=o.shift();k=new RegExp("(^|\\.)"+c.map(o.slice(0).sort(),db).join("\\.(?:.*\\.)?")+"(\\.|$)")}if(r=C[e])if(d){n=c.event.special[e]||{};for(B=f||0;B<r.length;B++){u=r[B];if(d.guid===u.guid){if(i||k.test(u.namespace)){f==null&&r.splice(B--,1);n.remove&&n.remove.call(a,u)}if(f!=
-null)break}}if(r.length===0||f!=null&&r.length===1){if(!n.teardown||n.teardown.call(a,o)===false)Ca(a,e,z.handle);delete C[e]}}else for(var B=0;B<r.length;B++){u=r[B];if(i||k.test(u.namespace)){c.event.remove(a,n,u.handler,B);r.splice(B--,1)}}}if(c.isEmptyObject(C)){if(b=z.handle)b.elem=null;delete z.events;delete z.handle;c.isEmptyObject(z)&&c.removeData(a)}}}}},trigger:function(a,b,d,f){var e=a.type||a;if(!f){a=typeof a==="object"?a[G]?a:c.extend(c.Event(e),a):c.Event(e);if(e.indexOf("!")>=0){a.type=
-e=e.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();c.event.global[e]&&c.each(c.cache,function(){this.events&&this.events[e]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType===8)return w;a.result=w;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(f=c.data(d,"handle"))&&f.apply(d,b);f=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+e]&&d["on"+e].apply(d,b)===false)a.result=false}catch(j){}if(!a.isPropagationStopped()&&
-f)c.event.trigger(a,b,f,true);else if(!a.isDefaultPrevented()){f=a.target;var i,o=c.nodeName(f,"a")&&e==="click",k=c.event.special[e]||{};if((!k._default||k._default.call(d,a)===false)&&!o&&!(f&&f.nodeName&&c.noData[f.nodeName.toLowerCase()])){try{if(f[e]){if(i=f["on"+e])f["on"+e]=null;c.event.triggered=true;f[e]()}}catch(n){}if(i)f["on"+e]=i;c.event.triggered=false}}},handle:function(a){var b,d,f,e;a=arguments[0]=c.event.fix(a||A.event);a.currentTarget=this;b=a.type.indexOf(".")<0&&!a.exclusive;
-if(!b){d=a.type.split(".");a.type=d.shift();f=new RegExp("(^|\\.)"+d.slice(0).sort().join("\\.(?:.*\\.)?")+"(\\.|$)")}e=c.data(this,"events");d=e[a.type];if(e&&d){d=d.slice(0);e=0;for(var j=d.length;e<j;e++){var i=d[e];if(b||f.test(i.namespace)){a.handler=i.handler;a.data=i.data;a.handleObj=i;i=i.handler.apply(this,arguments);if(i!==w){a.result=i;if(i===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}}return a.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
-fix:function(a){if(a[G])return a;var b=a;a=c.Event(b);for(var d=this.props.length,f;d;){f=this.props[--d];a[f]=b[f]}if(!a.target)a.target=a.srcElement||s;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=s.documentElement;d=s.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop||
-d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(!a.which&&(a.charCode||a.charCode===0?a.charCode:a.keyCode))a.which=a.charCode||a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==w)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a){c.event.add(this,a.origType,c.extend({},a,{handler:oa}))},remove:function(a){var b=true,d=a.origType.replace(O,"");c.each(c.data(this,
-"events").live||[],function(){if(d===this.origType.replace(O,""))return b=false});b&&c.event.remove(this,a.origType,oa)}},beforeunload:{setup:function(a,b,d){if(this.setInterval)this.onbeforeunload=d;return false},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};var Ca=s.removeEventListener?function(a,b,d){a.removeEventListener(b,d,false)}:function(a,b,d){a.detachEvent("on"+b,d)};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent=
-a;this.type=a.type}else this.type=a;this.timeStamp=J();this[G]=true};c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=Z;var a=this.originalEvent;if(a){a.preventDefault&&a.preventDefault();a.returnValue=false}},stopPropagation:function(){this.isPropagationStopped=Z;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=Z;this.stopPropagation()},isDefaultPrevented:Y,isPropagationStopped:Y,
-isImmediatePropagationStopped:Y};var Da=function(a){var b=a.relatedTarget;try{for(;b&&b!==this;)b=b.parentNode;if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}}catch(d){}},Ea=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?Ea:Da,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?Ea:Da)}}});if(!c.support.submitBubbles)c.event.special.submit=
-{setup:function(){if(this.nodeName.toLowerCase()!=="form"){c.event.add(this,"click.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="submit"||d==="image")&&c(b).closest("form").length)return na("submit",this,arguments)});c.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="text"||d==="password")&&c(b).closest("form").length&&a.keyCode===13)return na("submit",this,arguments)})}else return false},teardown:function(){c.event.remove(this,".specialSubmit")}};
-if(!c.support.changeBubbles){var da=/textarea|input|select/i,ea,Fa=function(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(f){return f.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d},fa=function(a,b){var d=a.target,f,e;if(!(!da.test(d.nodeName)||d.readOnly)){f=c.data(d,"_change_data");e=Fa(d);if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data",
-e);if(!(f===w||e===f))if(f!=null||e){a.type="change";return c.event.trigger(a,b,d)}}};c.event.special.change={filters:{focusout:fa,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return fa.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return fa.call(this,a)},beforeactivate:function(a){a=a.target;c.data(a,
-"_change_data",Fa(a))}},setup:function(){if(this.type==="file")return false;for(var a in ea)c.event.add(this,a+".specialChange",ea[a]);return da.test(this.nodeName)},teardown:function(){c.event.remove(this,".specialChange");return da.test(this.nodeName)}};ea=c.event.special.change.filters}s.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(f){f=c.event.fix(f);f.type=b;return c.event.handle.call(this,f)}c.event.special[b]={setup:function(){this.addEventListener(a,
-d,true)},teardown:function(){this.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,f,e){if(typeof d==="object"){for(var j in d)this[b](j,f,d[j],e);return this}if(c.isFunction(f)){e=f;f=w}var i=b==="one"?c.proxy(e,function(k){c(this).unbind(k,i);return e.apply(this,arguments)}):e;if(d==="unload"&&b!=="one")this.one(d,f,e);else{j=0;for(var o=this.length;j<o;j++)c.event.add(this[j],d,i,f)}return this}});c.fn.extend({unbind:function(a,b){if(typeof a==="object"&&
-!a.preventDefault)for(var d in a)this.unbind(d,a[d]);else{d=0;for(var f=this.length;d<f;d++)c.event.remove(this[d],a,b)}return this},delegate:function(a,b,d,f){return this.live(b,d,f,a)},undelegate:function(a,b,d){return arguments.length===0?this.unbind("live"):this.die(b,null,d,a)},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){a=c.Event(a);a.preventDefault();a.stopPropagation();c.event.trigger(a,b,this[0]);return a.result}},
-toggle:function(a){for(var b=arguments,d=1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(f){var e=(c.data(this,"lastToggle"+a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,e+1);f.preventDefault();return b[e].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var Ga={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};c.each(["live","die"],function(a,b){c.fn[b]=function(d,f,e,j){var i,o=0,k,n,r=j||this.selector,
-u=j?this:c(this.context);if(c.isFunction(f)){e=f;f=w}for(d=(d||"").split(" ");(i=d[o++])!=null;){j=O.exec(i);k="";if(j){k=j[0];i=i.replace(O,"")}if(i==="hover")d.push("mouseenter"+k,"mouseleave"+k);else{n=i;if(i==="focus"||i==="blur"){d.push(Ga[i]+k);i+=k}else i=(Ga[i]||i)+k;b==="live"?u.each(function(){c.event.add(this,pa(i,r),{data:f,selector:r,handler:e,origType:i,origHandler:e,preType:n})}):u.unbind(pa(i,r),e)}}return this}});c.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "),
-function(a,b){c.fn[b]=function(d){return d?this.bind(b,d):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});A.attachEvent&&!A.addEventListener&&A.attachEvent("onunload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}});(function(){function a(g){for(var h="",l,m=0;g[m];m++){l=g[m];if(l.nodeType===3||l.nodeType===4)h+=l.nodeValue;else if(l.nodeType!==8)h+=a(l.childNodes)}return h}function b(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q];
-if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1&&!p){t.sizcache=l;t.sizset=q}if(t.nodeName.toLowerCase()===h){y=t;break}t=t[g]}m[q]=y}}}function d(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q];if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1){if(!p){t.sizcache=l;t.sizset=q}if(typeof h!=="string"){if(t===h){y=true;break}}else if(k.filter(h,[t]).length>0){y=t;break}}t=t[g]}m[q]=y}}}var f=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
-e=0,j=Object.prototype.toString,i=false,o=true;[0,0].sort(function(){o=false;return 0});var k=function(g,h,l,m){l=l||[];var q=h=h||s;if(h.nodeType!==1&&h.nodeType!==9)return[];if(!g||typeof g!=="string")return l;for(var p=[],v,t,y,S,H=true,M=x(h),I=g;(f.exec(""),v=f.exec(I))!==null;){I=v[3];p.push(v[1]);if(v[2]){S=v[3];break}}if(p.length>1&&r.exec(g))if(p.length===2&&n.relative[p[0]])t=ga(p[0]+p[1],h);else for(t=n.relative[p[0]]?[h]:k(p.shift(),h);p.length;){g=p.shift();if(n.relative[g])g+=p.shift();
-t=ga(g,t)}else{if(!m&&p.length>1&&h.nodeType===9&&!M&&n.match.ID.test(p[0])&&!n.match.ID.test(p[p.length-1])){v=k.find(p.shift(),h,M);h=v.expr?k.filter(v.expr,v.set)[0]:v.set[0]}if(h){v=m?{expr:p.pop(),set:z(m)}:k.find(p.pop(),p.length===1&&(p[0]==="~"||p[0]==="+")&&h.parentNode?h.parentNode:h,M);t=v.expr?k.filter(v.expr,v.set):v.set;if(p.length>0)y=z(t);else H=false;for(;p.length;){var D=p.pop();v=D;if(n.relative[D])v=p.pop();else D="";if(v==null)v=h;n.relative[D](y,v,M)}}else y=[]}y||(y=t);y||k.error(D||
-g);if(j.call(y)==="[object Array]")if(H)if(h&&h.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&E(h,y[g])))l.push(t[g])}else for(g=0;y[g]!=null;g++)y[g]&&y[g].nodeType===1&&l.push(t[g]);else l.push.apply(l,y);else z(y,l);if(S){k(S,q,l,m);k.uniqueSort(l)}return l};k.uniqueSort=function(g){if(B){i=o;g.sort(B);if(i)for(var h=1;h<g.length;h++)g[h]===g[h-1]&&g.splice(h--,1)}return g};k.matches=function(g,h){return k(g,null,null,h)};k.find=function(g,h,l){var m,q;if(!g)return[];
-for(var p=0,v=n.order.length;p<v;p++){var t=n.order[p];if(q=n.leftMatch[t].exec(g)){var y=q[1];q.splice(1,1);if(y.substr(y.length-1)!=="\\"){q[1]=(q[1]||"").replace(/\\/g,"");m=n.find[t](q,h,l);if(m!=null){g=g.replace(n.match[t],"");break}}}}m||(m=h.getElementsByTagName("*"));return{set:m,expr:g}};k.filter=function(g,h,l,m){for(var q=g,p=[],v=h,t,y,S=h&&h[0]&&x(h[0]);g&&h.length;){for(var H in n.filter)if((t=n.leftMatch[H].exec(g))!=null&&t[2]){var M=n.filter[H],I,D;D=t[1];y=false;t.splice(1,1);if(D.substr(D.length-
-1)!=="\\"){if(v===p)p=[];if(n.preFilter[H])if(t=n.preFilter[H](t,v,l,p,m,S)){if(t===true)continue}else y=I=true;if(t)for(var U=0;(D=v[U])!=null;U++)if(D){I=M(D,t,U,v);var Ha=m^!!I;if(l&&I!=null)if(Ha)y=true;else v[U]=false;else if(Ha){p.push(D);y=true}}if(I!==w){l||(v=p);g=g.replace(n.match[H],"");if(!y)return[];break}}}if(g===q)if(y==null)k.error(g);else break;q=g}return v};k.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var n=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF-]|\\.)+)/,
-CLASS:/\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(g){return g.getAttribute("href")}},
-relative:{"+":function(g,h){var l=typeof h==="string",m=l&&!/\W/.test(h);l=l&&!m;if(m)h=h.toLowerCase();m=0;for(var q=g.length,p;m<q;m++)if(p=g[m]){for(;(p=p.previousSibling)&&p.nodeType!==1;);g[m]=l||p&&p.nodeName.toLowerCase()===h?p||false:p===h}l&&k.filter(h,g,true)},">":function(g,h){var l=typeof h==="string";if(l&&!/\W/.test(h)){h=h.toLowerCase();for(var m=0,q=g.length;m<q;m++){var p=g[m];if(p){l=p.parentNode;g[m]=l.nodeName.toLowerCase()===h?l:false}}}else{m=0;for(q=g.length;m<q;m++)if(p=g[m])g[m]=
-l?p.parentNode:p.parentNode===h;l&&k.filter(h,g,true)}},"":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("parentNode",h,m,g,p,l)},"~":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("previousSibling",h,m,g,p,l)}},find:{ID:function(g,h,l){if(typeof h.getElementById!=="undefined"&&!l)return(g=h.getElementById(g[1]))?[g]:[]},NAME:function(g,h){if(typeof h.getElementsByName!=="undefined"){var l=[];
-h=h.getElementsByName(g[1]);for(var m=0,q=h.length;m<q;m++)h[m].getAttribute("name")===g[1]&&l.push(h[m]);return l.length===0?null:l}},TAG:function(g,h){return h.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,h,l,m,q,p){g=" "+g[1].replace(/\\/g,"")+" ";if(p)return g;p=0;for(var v;(v=h[p])!=null;p++)if(v)if(q^(v.className&&(" "+v.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))l||m.push(v);else if(l)h[p]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()},
-CHILD:function(g){if(g[1]==="nth"){var h=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=h[1]+(h[2]||1)-0;g[3]=h[3]-0}g[0]=e++;return g},ATTR:function(g,h,l,m,q,p){h=g[1].replace(/\\/g,"");if(!p&&n.attrMap[h])g[1]=n.attrMap[h];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,h,l,m,q){if(g[1]==="not")if((f.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=k(g[3],null,null,h);else{g=k.filter(g[3],h,l,true^q);l||m.push.apply(m,
-g);return false}else if(n.match.POS.test(g[0])||n.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled===true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,h,l){return!!k(l[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)},
-text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"===g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}},
-setFilters:{first:function(g,h){return h===0},last:function(g,h,l,m){return h===m.length-1},even:function(g,h){return h%2===0},odd:function(g,h){return h%2===1},lt:function(g,h,l){return h<l[3]-0},gt:function(g,h,l){return h>l[3]-0},nth:function(g,h,l){return l[3]-0===h},eq:function(g,h,l){return l[3]-0===h}},filter:{PSEUDO:function(g,h,l,m){var q=h[1],p=n.filters[q];if(p)return p(g,l,h,m);else if(q==="contains")return(g.textContent||g.innerText||a([g])||"").indexOf(h[3])>=0;else if(q==="not"){h=
-h[3];l=0;for(m=h.length;l<m;l++)if(h[l]===g)return false;return true}else k.error("Syntax error, unrecognized expression: "+q)},CHILD:function(g,h){var l=h[1],m=g;switch(l){case "only":case "first":for(;m=m.previousSibling;)if(m.nodeType===1)return false;if(l==="first")return true;m=g;case "last":for(;m=m.nextSibling;)if(m.nodeType===1)return false;return true;case "nth":l=h[2];var q=h[3];if(l===1&&q===0)return true;h=h[0];var p=g.parentNode;if(p&&(p.sizcache!==h||!g.nodeIndex)){var v=0;for(m=p.firstChild;m;m=
-m.nextSibling)if(m.nodeType===1)m.nodeIndex=++v;p.sizcache=h}g=g.nodeIndex-q;return l===0?g===0:g%l===0&&g/l>=0}},ID:function(g,h){return g.nodeType===1&&g.getAttribute("id")===h},TAG:function(g,h){return h==="*"&&g.nodeType===1||g.nodeName.toLowerCase()===h},CLASS:function(g,h){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(h)>-1},ATTR:function(g,h){var l=h[1];g=n.attrHandle[l]?n.attrHandle[l](g):g[l]!=null?g[l]:g.getAttribute(l);l=g+"";var m=h[2];h=h[4];return g==null?m==="!=":m===
-"="?l===h:m==="*="?l.indexOf(h)>=0:m==="~="?(" "+l+" ").indexOf(h)>=0:!h?l&&g!==false:m==="!="?l!==h:m==="^="?l.indexOf(h)===0:m==="$="?l.substr(l.length-h.length)===h:m==="|="?l===h||l.substr(0,h.length+1)===h+"-":false},POS:function(g,h,l,m){var q=n.setFilters[h[2]];if(q)return q(g,l,h,m)}}},r=n.match.POS;for(var u in n.match){n.match[u]=new RegExp(n.match[u].source+/(?![^\[]*\])(?![^\(]*\))/.source);n.leftMatch[u]=new RegExp(/(^(?:.|\r|\n)*?)/.source+n.match[u].source.replace(/\\(\d+)/g,function(g,
-h){return"\\"+(h-0+1)}))}var z=function(g,h){g=Array.prototype.slice.call(g,0);if(h){h.push.apply(h,g);return h}return g};try{Array.prototype.slice.call(s.documentElement.childNodes,0)}catch(C){z=function(g,h){h=h||[];if(j.call(g)==="[object Array]")Array.prototype.push.apply(h,g);else if(typeof g.length==="number")for(var l=0,m=g.length;l<m;l++)h.push(g[l]);else for(l=0;g[l];l++)h.push(g[l]);return h}}var B;if(s.documentElement.compareDocumentPosition)B=function(g,h){if(!g.compareDocumentPosition||
-!h.compareDocumentPosition){if(g==h)i=true;return g.compareDocumentPosition?-1:1}g=g.compareDocumentPosition(h)&4?-1:g===h?0:1;if(g===0)i=true;return g};else if("sourceIndex"in s.documentElement)B=function(g,h){if(!g.sourceIndex||!h.sourceIndex){if(g==h)i=true;return g.sourceIndex?-1:1}g=g.sourceIndex-h.sourceIndex;if(g===0)i=true;return g};else if(s.createRange)B=function(g,h){if(!g.ownerDocument||!h.ownerDocument){if(g==h)i=true;return g.ownerDocument?-1:1}var l=g.ownerDocument.createRange(),m=
-h.ownerDocument.createRange();l.setStart(g,0);l.setEnd(g,0);m.setStart(h,0);m.setEnd(h,0);g=l.compareBoundaryPoints(Range.START_TO_END,m);if(g===0)i=true;return g};(function(){var g=s.createElement("div"),h="script"+(new Date).getTime();g.innerHTML="<a name='"+h+"'/>";var l=s.documentElement;l.insertBefore(g,l.firstChild);if(s.getElementById(h)){n.find.ID=function(m,q,p){if(typeof q.getElementById!=="undefined"&&!p)return(q=q.getElementById(m[1]))?q.id===m[1]||typeof q.getAttributeNode!=="undefined"&&
-q.getAttributeNode("id").nodeValue===m[1]?[q]:w:[]};n.filter.ID=function(m,q){var p=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&p&&p.nodeValue===q}}l.removeChild(g);l=g=null})();(function(){var g=s.createElement("div");g.appendChild(s.createComment(""));if(g.getElementsByTagName("*").length>0)n.find.TAG=function(h,l){l=l.getElementsByTagName(h[1]);if(h[1]==="*"){h=[];for(var m=0;l[m];m++)l[m].nodeType===1&&h.push(l[m]);l=h}return l};g.innerHTML="<a href='#'></a>";
-if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")n.attrHandle.href=function(h){return h.getAttribute("href",2)};g=null})();s.querySelectorAll&&function(){var g=k,h=s.createElement("div");h.innerHTML="<p class='TEST'></p>";if(!(h.querySelectorAll&&h.querySelectorAll(".TEST").length===0)){k=function(m,q,p,v){q=q||s;if(!v&&q.nodeType===9&&!x(q))try{return z(q.querySelectorAll(m),p)}catch(t){}return g(m,q,p,v)};for(var l in g)k[l]=g[l];h=null}}();
-(function(){var g=s.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){n.order.splice(1,0,"CLASS");n.find.CLASS=function(h,l,m){if(typeof l.getElementsByClassName!=="undefined"&&!m)return l.getElementsByClassName(h[1])};g=null}}})();var E=s.compareDocumentPosition?function(g,h){return!!(g.compareDocumentPosition(h)&16)}:
-function(g,h){return g!==h&&(g.contains?g.contains(h):true)},x=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false},ga=function(g,h){var l=[],m="",q;for(h=h.nodeType?[h]:h;q=n.match.PSEUDO.exec(g);){m+=q[0];g=g.replace(n.match.PSEUDO,"")}g=n.relative[g]?g+"*":g;q=0;for(var p=h.length;q<p;q++)k(g,h[q],l);return k.filter(m,l)};c.find=k;c.expr=k.selectors;c.expr[":"]=c.expr.filters;c.unique=k.uniqueSort;c.text=a;c.isXMLDoc=x;c.contains=E})();var eb=/Until$/,fb=/^(?:parents|prevUntil|prevAll)/,
-gb=/,/;R=Array.prototype.slice;var Ia=function(a,b,d){if(c.isFunction(b))return c.grep(a,function(e,j){return!!b.call(e,j,e)===d});else if(b.nodeType)return c.grep(a,function(e){return e===b===d});else if(typeof b==="string"){var f=c.grep(a,function(e){return e.nodeType===1});if(Ua.test(b))return c.filter(b,f,!d);else b=c.filter(b,f)}return c.grep(a,function(e){return c.inArray(e,b)>=0===d})};c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,f=0,e=this.length;f<e;f++){d=b.length;
-c.find(a,this[f],b);if(f>0)for(var j=d;j<b.length;j++)for(var i=0;i<d;i++)if(b[i]===b[j]){b.splice(j--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=0,f=b.length;d<f;d++)if(c.contains(this,b[d]))return true})},not:function(a){return this.pushStack(Ia(this,a,false),"not",a)},filter:function(a){return this.pushStack(Ia(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){if(c.isArray(a)){var d=[],f=this[0],e,j=
-{},i;if(f&&a.length){e=0;for(var o=a.length;e<o;e++){i=a[e];j[i]||(j[i]=c.expr.match.POS.test(i)?c(i,b||this.context):i)}for(;f&&f.ownerDocument&&f!==b;){for(i in j){e=j[i];if(e.jquery?e.index(f)>-1:c(f).is(e)){d.push({selector:i,elem:f});delete j[i]}}f=f.parentNode}}return d}var k=c.expr.match.POS.test(a)?c(a,b||this.context):null;return this.map(function(n,r){for(;r&&r.ownerDocument&&r!==b;){if(k?k.index(r)>-1:c(r).is(a))return r;r=r.parentNode}return null})},index:function(a){if(!a||typeof a===
-"string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){a=typeof a==="string"?c(a,b||this.context):c.makeArray(a);b=c.merge(this.get(),a);return this.pushStack(qa(a[0])||qa(b[0])?b:c.unique(b))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode",
-d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a,2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")?
-a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a,b){c.fn[a]=function(d,f){var e=c.map(this,b,d);eb.test(a)||(f=d);if(f&&typeof f==="string")e=c.filter(f,e);e=this.length>1?c.unique(e):e;if((this.length>1||gb.test(f))&&fb.test(a))e=e.reverse();return this.pushStack(e,a,R.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return c.find.matches(a,b)},dir:function(a,b,d){var f=[];for(a=a[b];a&&a.nodeType!==9&&(d===w||a.nodeType!==1||!c(a).is(d));){a.nodeType===
-1&&f.push(a);a=a[b]}return f},nth:function(a,b,d){b=b||1;for(var f=0;a;a=a[d])if(a.nodeType===1&&++f===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var Ja=/ jQuery\d+="(?:\d+|null)"/g,V=/^\s+/,Ka=/(<([\w:]+)[^>]*?)\/>/g,hb=/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,La=/<([\w:]+)/,ib=/<tbody/i,jb=/<|&#?\w+;/,ta=/<script|<object|<embed|<option|<style/i,ua=/checked\s*(?:[^=]|=\s*.checked.)/i,Ma=function(a,b,d){return hb.test(d)?
-a:b+"></"+d+">"},F={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};F.optgroup=F.option;F.tbody=F.tfoot=F.colgroup=F.caption=F.thead;F.th=F.td;if(!c.support.htmlSerialize)F._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d=
-c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==w)return this.empty().append((this[0]&&this[0].ownerDocument||s).createTextNode(a));return c.text(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this},
-wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})},
-prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,
-this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},remove:function(a,b){for(var d=0,f;(f=this[d])!=null;d++)if(!a||c.filter(a,[f]).length){if(!b&&f.nodeType===1){c.cleanData(f.getElementsByTagName("*"));c.cleanData([f])}f.parentNode&&f.parentNode.removeChild(f)}return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++)for(b.nodeType===1&&c.cleanData(b.getElementsByTagName("*"));b.firstChild;)b.removeChild(b.firstChild);
-return this},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,f=this.ownerDocument;if(!d){d=f.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(Ja,"").replace(/=([^="'>\s]+\/)>/g,'="$1">').replace(V,"")],f)[0]}else return this.cloneNode(true)});if(a===true){ra(this,b);ra(this.find("*"),b.find("*"))}return b},html:function(a){if(a===w)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(Ja,
-""):null;else if(typeof a==="string"&&!ta.test(a)&&(c.support.leadingWhitespace||!V.test(a))&&!F[(La.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Ka,Ma);try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(f){this.empty().append(a)}}else c.isFunction(a)?this.each(function(e){var j=c(this),i=j.html();j.empty().append(function(){return a.call(this,e,i)})}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&
-this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d=c(this),f=d.html();d.replaceWith(a.call(this,b,f))});if(typeof a!=="string")a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){function f(u){return c.nodeName(u,"table")?u.getElementsByTagName("tbody")[0]||
-u.appendChild(u.ownerDocument.createElement("tbody")):u}var e,j,i=a[0],o=[],k;if(!c.support.checkClone&&arguments.length===3&&typeof i==="string"&&ua.test(i))return this.each(function(){c(this).domManip(a,b,d,true)});if(c.isFunction(i))return this.each(function(u){var z=c(this);a[0]=i.call(this,u,b?z.html():w);z.domManip(a,b,d)});if(this[0]){e=i&&i.parentNode;e=c.support.parentNode&&e&&e.nodeType===11&&e.childNodes.length===this.length?{fragment:e}:sa(a,this,o);k=e.fragment;if(j=k.childNodes.length===
-1?(k=k.firstChild):k.firstChild){b=b&&c.nodeName(j,"tr");for(var n=0,r=this.length;n<r;n++)d.call(b?f(this[n],j):this[n],n>0||e.cacheable||this.length>1?k.cloneNode(true):k)}o.length&&c.each(o,Qa)}return this}});c.fragments={};c.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var f=[];d=c(d);var e=this.length===1&&this[0].parentNode;if(e&&e.nodeType===11&&e.childNodes.length===1&&d.length===1){d[b](this[0]);
-return this}else{e=0;for(var j=d.length;e<j;e++){var i=(e>0?this.clone(true):this).get();c.fn[b].apply(c(d[e]),i);f=f.concat(i)}return this.pushStack(f,a,d.selector)}}});c.extend({clean:function(a,b,d,f){b=b||s;if(typeof b.createElement==="undefined")b=b.ownerDocument||b[0]&&b[0].ownerDocument||s;for(var e=[],j=0,i;(i=a[j])!=null;j++){if(typeof i==="number")i+="";if(i){if(typeof i==="string"&&!jb.test(i))i=b.createTextNode(i);else if(typeof i==="string"){i=i.replace(Ka,Ma);var o=(La.exec(i)||["",
-""])[1].toLowerCase(),k=F[o]||F._default,n=k[0],r=b.createElement("div");for(r.innerHTML=k[1]+i+k[2];n--;)r=r.lastChild;if(!c.support.tbody){n=ib.test(i);o=o==="table"&&!n?r.firstChild&&r.firstChild.childNodes:k[1]==="<table>"&&!n?r.childNodes:[];for(k=o.length-1;k>=0;--k)c.nodeName(o[k],"tbody")&&!o[k].childNodes.length&&o[k].parentNode.removeChild(o[k])}!c.support.leadingWhitespace&&V.test(i)&&r.insertBefore(b.createTextNode(V.exec(i)[0]),r.firstChild);i=r.childNodes}if(i.nodeType)e.push(i);else e=
-c.merge(e,i)}}if(d)for(j=0;e[j];j++)if(f&&c.nodeName(e[j],"script")&&(!e[j].type||e[j].type.toLowerCase()==="text/javascript"))f.push(e[j].parentNode?e[j].parentNode.removeChild(e[j]):e[j]);else{e[j].nodeType===1&&e.splice.apply(e,[j+1,0].concat(c.makeArray(e[j].getElementsByTagName("script"))));d.appendChild(e[j])}return e},cleanData:function(a){for(var b,d,f=c.cache,e=c.event.special,j=c.support.deleteExpando,i=0,o;(o=a[i])!=null;i++)if(d=o[c.expando]){b=f[d];if(b.events)for(var k in b.events)e[k]?
-c.event.remove(o,k):Ca(o,k,b.handle);if(j)delete o[c.expando];else o.removeAttribute&&o.removeAttribute(c.expando);delete f[d]}}});var kb=/z-?index|font-?weight|opacity|zoom|line-?height/i,Na=/alpha\([^)]*\)/,Oa=/opacity=([^)]*)/,ha=/float/i,ia=/-([a-z])/ig,lb=/([A-Z])/g,mb=/^-?\d+(?:px)?$/i,nb=/^-?\d/,ob={position:"absolute",visibility:"hidden",display:"block"},pb=["Left","Right"],qb=["Top","Bottom"],rb=s.defaultView&&s.defaultView.getComputedStyle,Pa=c.support.cssFloat?"cssFloat":"styleFloat",ja=
-function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){return X(this,a,b,true,function(d,f,e){if(e===w)return c.curCSS(d,f);if(typeof e==="number"&&!kb.test(f))e+="px";c.style(d,f,e)})};c.extend({style:function(a,b,d){if(!a||a.nodeType===3||a.nodeType===8)return w;if((b==="width"||b==="height")&&parseFloat(d)<0)d=w;var f=a.style||a,e=d!==w;if(!c.support.opacity&&b==="opacity"){if(e){f.zoom=1;b=parseInt(d,10)+""==="NaN"?"":"alpha(opacity="+d*100+")";a=f.filter||c.curCSS(a,"filter")||"";f.filter=
-Na.test(a)?a.replace(Na,b):b}return f.filter&&f.filter.indexOf("opacity=")>=0?parseFloat(Oa.exec(f.filter)[1])/100+"":""}if(ha.test(b))b=Pa;b=b.replace(ia,ja);if(e)f[b]=d;return f[b]},css:function(a,b,d,f){if(b==="width"||b==="height"){var e,j=b==="width"?pb:qb;function i(){e=b==="width"?a.offsetWidth:a.offsetHeight;f!=="border"&&c.each(j,function(){f||(e-=parseFloat(c.curCSS(a,"padding"+this,true))||0);if(f==="margin")e+=parseFloat(c.curCSS(a,"margin"+this,true))||0;else e-=parseFloat(c.curCSS(a,
-"border"+this+"Width",true))||0})}a.offsetWidth!==0?i():c.swap(a,ob,i);return Math.max(0,Math.round(e))}return c.curCSS(a,b,d)},curCSS:function(a,b,d){var f,e=a.style;if(!c.support.opacity&&b==="opacity"&&a.currentStyle){f=Oa.test(a.currentStyle.filter||"")?parseFloat(RegExp.$1)/100+"":"";return f===""?"1":f}if(ha.test(b))b=Pa;if(!d&&e&&e[b])f=e[b];else if(rb){if(ha.test(b))b="float";b=b.replace(lb,"-$1").toLowerCase();e=a.ownerDocument.defaultView;if(!e)return null;if(a=e.getComputedStyle(a,null))f=
-a.getPropertyValue(b);if(b==="opacity"&&f==="")f="1"}else if(a.currentStyle){d=b.replace(ia,ja);f=a.currentStyle[b]||a.currentStyle[d];if(!mb.test(f)&&nb.test(f)){b=e.left;var j=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;e.left=d==="fontSize"?"1em":f||0;f=e.pixelLeft+"px";e.left=b;a.runtimeStyle.left=j}}return f},swap:function(a,b,d){var f={};for(var e in b){f[e]=a.style[e];a.style[e]=b[e]}d.call(a);for(e in b)a.style[e]=f[e]}});if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b=
-a.offsetWidth,d=a.offsetHeight,f=a.nodeName.toLowerCase()==="tr";return b===0&&d===0&&!f?true:b>0&&d>0&&!f?false:c.curCSS(a,"display")==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var sb=J(),tb=/<script(.|\s)*?\/script>/gi,ub=/select|textarea/i,vb=/color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,N=/=\?(&|$)/,ka=/\?/,wb=/(\?|&)_=.*?(&|$)/,xb=/^(\w+:)?\/\/([^\/?#]+)/,yb=/%20/g,zb=c.fn.load;c.fn.extend({load:function(a,b,d){if(typeof a!==
-"string")return zb.call(this,a);else if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var e=a.slice(f,a.length);a=a.slice(0,f)}f="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b==="object"){b=c.param(b,c.ajaxSettings.traditional);f="POST"}var j=this;c.ajax({url:a,type:f,dataType:"html",data:b,complete:function(i,o){if(o==="success"||o==="notmodified")j.html(e?c("<div />").append(i.responseText.replace(tb,"")).find(e):i.responseText);d&&j.each(d,[i.responseText,o,i])}});return this},
-serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||ub.test(this.nodeName)||vb.test(this.type))}).map(function(a,b){a=c(this).val();return a==null?null:c.isArray(a)?c.map(a,function(d){return{name:b.name,value:d}}):{name:b.name,value:a}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),
-function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:f})},getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:f})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href,
-global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:A.XMLHttpRequest&&(A.location.protocol!=="file:"||!A.ActiveXObject)?function(){return new A.XMLHttpRequest}:function(){try{return new A.ActiveXObject("Microsoft.XMLHTTP")}catch(a){}},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},etag:{},ajax:function(a){function b(){e.success&&
-e.success.call(k,o,i,x);e.global&&f("ajaxSuccess",[x,e])}function d(){e.complete&&e.complete.call(k,x,i);e.global&&f("ajaxComplete",[x,e]);e.global&&!--c.active&&c.event.trigger("ajaxStop")}function f(q,p){(e.context?c(e.context):c.event).trigger(q,p)}var e=c.extend(true,{},c.ajaxSettings,a),j,i,o,k=a&&a.context||e,n=e.type.toUpperCase();if(e.data&&e.processData&&typeof e.data!=="string")e.data=c.param(e.data,e.traditional);if(e.dataType==="jsonp"){if(n==="GET")N.test(e.url)||(e.url+=(ka.test(e.url)?
-"&":"?")+(e.jsonp||"callback")+"=?");else if(!e.data||!N.test(e.data))e.data=(e.data?e.data+"&":"")+(e.jsonp||"callback")+"=?";e.dataType="json"}if(e.dataType==="json"&&(e.data&&N.test(e.data)||N.test(e.url))){j=e.jsonpCallback||"jsonp"+sb++;if(e.data)e.data=(e.data+"").replace(N,"="+j+"$1");e.url=e.url.replace(N,"="+j+"$1");e.dataType="script";A[j]=A[j]||function(q){o=q;b();d();A[j]=w;try{delete A[j]}catch(p){}z&&z.removeChild(C)}}if(e.dataType==="script"&&e.cache===null)e.cache=false;if(e.cache===
-false&&n==="GET"){var r=J(),u=e.url.replace(wb,"$1_="+r+"$2");e.url=u+(u===e.url?(ka.test(e.url)?"&":"?")+"_="+r:"")}if(e.data&&n==="GET")e.url+=(ka.test(e.url)?"&":"?")+e.data;e.global&&!c.active++&&c.event.trigger("ajaxStart");r=(r=xb.exec(e.url))&&(r[1]&&r[1]!==location.protocol||r[2]!==location.host);if(e.dataType==="script"&&n==="GET"&&r){var z=s.getElementsByTagName("head")[0]||s.documentElement,C=s.createElement("script");C.src=e.url;if(e.scriptCharset)C.charset=e.scriptCharset;if(!j){var B=
-false;C.onload=C.onreadystatechange=function(){if(!B&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){B=true;b();d();C.onload=C.onreadystatechange=null;z&&C.parentNode&&z.removeChild(C)}}}z.insertBefore(C,z.firstChild);return w}var E=false,x=e.xhr();if(x){e.username?x.open(n,e.url,e.async,e.username,e.password):x.open(n,e.url,e.async);try{if(e.data||a&&a.contentType)x.setRequestHeader("Content-Type",e.contentType);if(e.ifModified){c.lastModified[e.url]&&x.setRequestHeader("If-Modified-Since",
-c.lastModified[e.url]);c.etag[e.url]&&x.setRequestHeader("If-None-Match",c.etag[e.url])}r||x.setRequestHeader("X-Requested-With","XMLHttpRequest");x.setRequestHeader("Accept",e.dataType&&e.accepts[e.dataType]?e.accepts[e.dataType]+", */*":e.accepts._default)}catch(ga){}if(e.beforeSend&&e.beforeSend.call(k,x,e)===false){e.global&&!--c.active&&c.event.trigger("ajaxStop");x.abort();return false}e.global&&f("ajaxSend",[x,e]);var g=x.onreadystatechange=function(q){if(!x||x.readyState===0||q==="abort"){E||
-d();E=true;if(x)x.onreadystatechange=c.noop}else if(!E&&x&&(x.readyState===4||q==="timeout")){E=true;x.onreadystatechange=c.noop;i=q==="timeout"?"timeout":!c.httpSuccess(x)?"error":e.ifModified&&c.httpNotModified(x,e.url)?"notmodified":"success";var p;if(i==="success")try{o=c.httpData(x,e.dataType,e)}catch(v){i="parsererror";p=v}if(i==="success"||i==="notmodified")j||b();else c.handleError(e,x,i,p);d();q==="timeout"&&x.abort();if(e.async)x=null}};try{var h=x.abort;x.abort=function(){x&&h.call(x);
-g("abort")}}catch(l){}e.async&&e.timeout>0&&setTimeout(function(){x&&!E&&g("timeout")},e.timeout);try{x.send(n==="POST"||n==="PUT"||n==="DELETE"?e.data:null)}catch(m){c.handleError(e,x,null,m);d()}e.async||g();return x}},handleError:function(a,b,d,f){if(a.error)a.error.call(a.context||a,b,d,f);if(a.global)(a.context?c(a.context):c.event).trigger("ajaxError",[b,a,f])},active:0,httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status===
-1223||a.status===0}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"),f=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(f)c.etag[b]=f;return a.status===304||a.status===0},httpData:function(a,b,d){var f=a.getResponseHeader("content-type")||"",e=b==="xml"||!b&&f.indexOf("xml")>=0;a=e?a.responseXML:a.responseText;e&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b===
-"json"||!b&&f.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&f.indexOf("javascript")>=0)c.globalEval(a);return a},param:function(a,b){function d(i,o){if(c.isArray(o))c.each(o,function(k,n){b||/\[\]$/.test(i)?f(i,n):d(i+"["+(typeof n==="object"||c.isArray(n)?k:"")+"]",n)});else!b&&o!=null&&typeof o==="object"?c.each(o,function(k,n){d(i+"["+k+"]",n)}):f(i,o)}function f(i,o){o=c.isFunction(o)?o():o;e[e.length]=encodeURIComponent(i)+"="+encodeURIComponent(o)}var e=[];if(b===w)b=c.ajaxSettings.traditional;
-if(c.isArray(a)||a.jquery)c.each(a,function(){f(this.name,this.value)});else for(var j in a)d(j,a[j]);return e.join("&").replace(yb,"+")}});var la={},Ab=/toggle|show|hide/,Bb=/^([+-]=)?([\d+-.]+)(.*)$/,W,va=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b){if(a||a===0)return this.animate(K("show",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");
-this[a].style.display=d||"";if(c.css(this[a],"display")==="none"){d=this[a].nodeName;var f;if(la[d])f=la[d];else{var e=c("<"+d+" />").appendTo("body");f=e.css("display");if(f==="none")f="block";e.remove();la[d]=f}c.data(this[a],"olddisplay",f)}}a=0;for(b=this.length;a<b;a++)this[a].style.display=c.data(this[a],"olddisplay")||"";return this}},hide:function(a,b){if(a||a===0)return this.animate(K("hide",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");!d&&d!=="none"&&c.data(this[a],
-"olddisplay",c.css(this[a],"display"))}a=0;for(b=this.length;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b){var d=typeof a==="boolean";if(c.isFunction(a)&&c.isFunction(b))this._toggle.apply(this,arguments);else a==null||d?this.each(function(){var f=d?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(K("toggle",3),a,b);return this},fadeTo:function(a,b,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d)},
-animate:function(a,b,d,f){var e=c.speed(b,d,f);if(c.isEmptyObject(a))return this.each(e.complete);return this[e.queue===false?"each":"queue"](function(){var j=c.extend({},e),i,o=this.nodeType===1&&c(this).is(":hidden"),k=this;for(i in a){var n=i.replace(ia,ja);if(i!==n){a[n]=a[i];delete a[i];i=n}if(a[i]==="hide"&&o||a[i]==="show"&&!o)return j.complete.call(this);if((i==="height"||i==="width")&&this.style){j.display=c.css(this,"display");j.overflow=this.style.overflow}if(c.isArray(a[i])){(j.specialEasing=
-j.specialEasing||{})[i]=a[i][1];a[i]=a[i][0]}}if(j.overflow!=null)this.style.overflow="hidden";j.curAnim=c.extend({},a);c.each(a,function(r,u){var z=new c.fx(k,j,r);if(Ab.test(u))z[u==="toggle"?o?"show":"hide":u](a);else{var C=Bb.exec(u),B=z.cur(true)||0;if(C){u=parseFloat(C[2]);var E=C[3]||"px";if(E!=="px"){k.style[r]=(u||1)+E;B=(u||1)/z.cur(true)*B;k.style[r]=B+E}if(C[1])u=(C[1]==="-="?-1:1)*u+B;z.custom(B,u,E)}else z.custom(B,u,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]);
-this.each(function(){for(var f=d.length-1;f>=0;f--)if(d[f].elem===this){b&&d[f](true);d.splice(f,1)}});b||this.dequeue();return this}});c.each({slideDown:K("show",1),slideUp:K("hide",1),slideToggle:K("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(a,b){c.fn[a]=function(d,f){return this.animate(b,d,f)}});c.extend({speed:function(a,b,d){var f=a&&typeof a==="object"?a:{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};f.duration=c.fx.off?0:typeof f.duration===
-"number"?f.duration:c.fx.speeds[f.duration]||c.fx.speeds._default;f.old=f.complete;f.complete=function(){f.queue!==false&&c(this).dequeue();c.isFunction(f.old)&&f.old.call(this)};return f},easing:{linear:function(a,b,d,f){return d+f*a},swing:function(a,b,d,f){return(-Math.cos(a*Math.PI)/2+0.5)*f+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]||
-c.fx.step._default)(this);if((this.prop==="height"||this.prop==="width")&&this.elem.style)this.elem.style.display="block"},cur:function(a){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];return(a=parseFloat(c.css(this.elem,this.prop,a)))&&a>-10000?a:parseFloat(c.curCSS(this.elem,this.prop))||0},custom:function(a,b,d){function f(j){return e.step(j)}this.startTime=J();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start;
-this.pos=this.state=0;var e=this;f.elem=this.elem;if(f()&&c.timers.push(f)&&!W)W=setInterval(c.fx.tick,13)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(a){var b=J(),d=true;if(a||b>=this.options.duration+this.startTime){this.now=
-this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var f in this.options.curAnim)if(this.options.curAnim[f]!==true)d=false;if(d){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;a=c.data(this.elem,"olddisplay");this.elem.style.display=a?a:this.options.display;if(c.css(this.elem,"display")==="none")this.elem.style.display="block"}this.options.hide&&c(this.elem).hide();if(this.options.hide||this.options.show)for(var e in this.options.curAnim)c.style(this.elem,
-e,this.options.orig[e]);this.options.complete.call(this.elem)}return false}else{e=b-this.startTime;this.state=e/this.options.duration;a=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||a](this.state,e,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a=c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||
-c.fx.stop()},stop:function(){clearInterval(W);W=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(a.elem.style&&a.elem.style[a.prop]!=null)a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a===b.elem}).length};c.fn.offset="getBoundingClientRect"in s.documentElement?
-function(a){var b=this[0];if(a)return this.each(function(e){c.offset.setOffset(this,a,e)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);var d=b.getBoundingClientRect(),f=b.ownerDocument;b=f.body;f=f.documentElement;return{top:d.top+(self.pageYOffset||c.support.boxModel&&f.scrollTop||b.scrollTop)-(f.clientTop||b.clientTop||0),left:d.left+(self.pageXOffset||c.support.boxModel&&f.scrollLeft||b.scrollLeft)-(f.clientLeft||b.clientLeft||0)}}:function(a){var b=
-this[0];if(a)return this.each(function(r){c.offset.setOffset(this,a,r)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d=b.offsetParent,f=b,e=b.ownerDocument,j,i=e.documentElement,o=e.body;f=(e=e.defaultView)?e.getComputedStyle(b,null):b.currentStyle;for(var k=b.offsetTop,n=b.offsetLeft;(b=b.parentNode)&&b!==o&&b!==i;){if(c.offset.supportsFixedPosition&&f.position==="fixed")break;j=e?e.getComputedStyle(b,null):b.currentStyle;
-k-=b.scrollTop;n-=b.scrollLeft;if(b===d){k+=b.offsetTop;n+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(b.nodeName))){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=d;d=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&j.overflow!=="visible"){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=j}if(f.position==="relative"||f.position==="static"){k+=o.offsetTop;n+=o.offsetLeft}if(c.offset.supportsFixedPosition&&
-f.position==="fixed"){k+=Math.max(i.scrollTop,o.scrollTop);n+=Math.max(i.scrollLeft,o.scrollLeft)}return{top:k,left:n}};c.offset={initialize:function(){var a=s.body,b=s.createElement("div"),d,f,e,j=parseFloat(c.curCSS(a,"marginTop",true))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"});b.innerHTML="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";
-a.insertBefore(b,a.firstChild);d=b.firstChild;f=d.firstChild;e=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=f.offsetTop!==5;this.doesAddBorderForTableAndCells=e.offsetTop===5;f.style.position="fixed";f.style.top="20px";this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15;f.style.position=f.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==j;a.removeChild(b);
-c.offset.initialize=c.noop},bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.curCSS(a,"marginTop",true))||0;d+=parseFloat(c.curCSS(a,"marginLeft",true))||0}return{top:b,left:d}},setOffset:function(a,b,d){if(/static/.test(c.curCSS(a,"position")))a.style.position="relative";var f=c(a),e=f.offset(),j=parseInt(c.curCSS(a,"top",true),10)||0,i=parseInt(c.curCSS(a,"left",true),10)||0;if(c.isFunction(b))b=b.call(a,
-d,e);d={top:b.top-e.top+j,left:b.left-e.left+i};"using"in b?b.using.call(a,d):f.css(d)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),f=/^body|html$/i.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.curCSS(a,"marginTop",true))||0;d.left-=parseFloat(c.curCSS(a,"marginLeft",true))||0;f.top+=parseFloat(c.curCSS(b[0],"borderTopWidth",true))||0;f.left+=parseFloat(c.curCSS(b[0],"borderLeftWidth",true))||0;return{top:d.top-
-f.top,left:d.left-f.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||s.body;a&&!/^body|html$/i.test(a.nodeName)&&c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(f){var e=this[0],j;if(!e)return null;if(f!==w)return this.each(function(){if(j=wa(this))j.scrollTo(!a?f:c(j).scrollLeft(),a?f:c(j).scrollTop());else this[d]=f});else return(j=wa(e))?"pageXOffset"in j?j[a?"pageYOffset":
-"pageXOffset"]:c.support.boxModel&&j.document.documentElement[d]||j.document.body[d]:e[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();c.fn["inner"+b]=function(){return this[0]?c.css(this[0],d,false,"padding"):null};c.fn["outer"+b]=function(f){return this[0]?c.css(this[0],d,false,f?"margin":"border"):null};c.fn[d]=function(f){var e=this[0];if(!e)return f==null?null:this;if(c.isFunction(f))return this.each(function(j){var i=c(this);i[d](f.call(this,j,i[d]()))});return"scrollTo"in
-e&&e.document?e.document.compatMode==="CSS1Compat"&&e.document.documentElement["client"+b]||e.document.body["client"+b]:e.nodeType===9?Math.max(e.documentElement["client"+b],e.body["scroll"+b],e.documentElement["scroll"+b],e.body["offset"+b],e.documentElement["offset"+b]):f===w?c.css(e,d):this.css(d,typeof f==="string"?f:f+"px")}});A.jQuery=A.$=c})(window);
+(function(){
+
+var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
+	done = 0,
+	toString = Object.prototype.toString,
+	hasDuplicate = false,
+	baseHasDuplicate = true,
+	rBackslash = /\\/g,
+	rNonWord = /\W/;
+
+// Here we check if the JavaScript engine is using some sort of
+// optimization where it does not always call our comparision
+// function. If that is the case, discard the hasDuplicate value.
+//   Thus far that includes Google Chrome.
+[0, 0].sort(function() {
+	baseHasDuplicate = false;
+	return 0;
+});
+
+var Sizzle = function( selector, context, results, seed ) {
+	results = results || [];
+	context = context || document;
+
+	var origContext = context;
+
+	if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
+		return [];
+	}
+	
+	if ( !selector || typeof selector !== "string" ) {
+		return results;
+	}
+
+	var m, set, checkSet, extra, ret, cur, pop, i,
+		prune = true,
+		contextXML = Sizzle.isXML( context ),
+		parts = [],
+		soFar = selector;
+	
+	// Reset the position of the chunker regexp (start from head)
+	do {
+		chunker.exec( "" );
+		m = chunker.exec( soFar );
+
+		if ( m ) {
+			soFar = m[3];
+		
+			parts.push( m[1] );
+		
+			if ( m[2] ) {
+				extra = m[3];
+				break;
+			}
+		}
+	} while ( m );
+
+	if ( parts.length > 1 && origPOS.exec( selector ) ) {
+
+		if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
+			set = posProcess( parts[0] + parts[1], context );
+
+		} else {
+			set = Expr.relative[ parts[0] ] ?
+				[ context ] :
+				Sizzle( parts.shift(), context );
+
+			while ( parts.length ) {
+				selector = parts.shift();
+
+				if ( Expr.relative[ selector ] ) {
+					selector += parts.shift();
+				}
+				
+				set = posProcess( selector, set );
+			}
+		}
+
+	} else {
+		// Take a shortcut and set the context if the root selector is an ID
+		// (but not if it'll be faster if the inner selector is an ID)
+		if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
+				Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
+
+			ret = Sizzle.find( parts.shift(), context, contextXML );
+			context = ret.expr ?
+				Sizzle.filter( ret.expr, ret.set )[0] :
+				ret.set[0];
+		}
+
+		if ( context ) {
+			ret = seed ?
+				{ expr: parts.pop(), set: makeArray(seed) } :
+				Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
+
+			set = ret.expr ?
+				Sizzle.filter( ret.expr, ret.set ) :
+				ret.set;
+
+			if ( parts.length > 0 ) {
+				checkSet = makeArray( set );
+
+			} else {
+				prune = false;
+			}
+
+			while ( parts.length ) {
+				cur = parts.pop();
+				pop = cur;
+
+				if ( !Expr.relative[ cur ] ) {
+					cur = "";
+				} else {
+					pop = parts.pop();
+				}
+
+				if ( pop == null ) {
+					pop = context;
+				}
+
+				Expr.relative[ cur ]( checkSet, pop, contextXML );
+			}
+
+		} else {
+			checkSet = parts = [];
+		}
+	}
+
+	if ( !checkSet ) {
+		checkSet = set;
+	}
+
+	if ( !checkSet ) {
+		Sizzle.error( cur || selector );
+	}
+
+	if ( toString.call(checkSet) === "[object Array]" ) {
+		if ( !prune ) {
+			results.push.apply( results, checkSet );
+
+		} else if ( context && context.nodeType === 1 ) {
+			for ( i = 0; checkSet[i] != null; i++ ) {
+				if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {
+					results.push( set[i] );
+				}
+			}
+
+		} else {
+			for ( i = 0; checkSet[i] != null; i++ ) {
+				if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
+					results.push( set[i] );
+				}
+			}
+		}
+
+	} else {
+		makeArray( checkSet, results );
+	}
+
+	if ( extra ) {
+		Sizzle( extra, origContext, results, seed );
+		Sizzle.uniqueSort( results );
+	}
+
+	return results;
+};
+
+Sizzle.uniqueSort = function( results ) {
+	if ( sortOrder ) {
+		hasDuplicate = baseHasDuplicate;
+		results.sort( sortOrder );
+
+		if ( hasDuplicate ) {
+			for ( var i = 1; i < results.length; i++ ) {
+				if ( results[i] === results[ i - 1 ] ) {
+					results.splice( i--, 1 );
+				}
+			}
+		}
+	}
+
+	return results;
+};
+
+Sizzle.matches = function( expr, set ) {
+	return Sizzle( expr, null, null, set );
+};
+
+Sizzle.matchesSelector = function( node, expr ) {
+	return Sizzle( expr, null, null, [node] ).length > 0;
+};
+
+Sizzle.find = function( expr, context, isXML ) {
+	var set;
+
+	if ( !expr ) {
+		return [];
+	}
+
+	for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
+		var match,
+			type = Expr.order[i];
+		
+		if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
+			var left = match[1];
+			match.splice( 1, 1 );
+
+			if ( left.substr( left.length - 1 ) !== "\\" ) {
+				match[1] = (match[1] || "").replace( rBackslash, "" );
+				set = Expr.find[ type ]( match, context, isXML );
+
+				if ( set != null ) {
+					expr = expr.replace( Expr.match[ type ], "" );
+					break;
+				}
+			}
+		}
+	}
+
+	if ( !set ) {
+		set = typeof context.getElementsByTagName !== "undefined" ?
+			context.getElementsByTagName( "*" ) :
+			[];
+	}
+
+	return { set: set, expr: expr };
+};
+
+Sizzle.filter = function( expr, set, inplace, not ) {
+	var match, anyFound,
+		old = expr,
+		result = [],
+		curLoop = set,
+		isXMLFilter = set && set[0] && Sizzle.isXML( set[0] );
+
+	while ( expr && set.length ) {
+		for ( var type in Expr.filter ) {
+			if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
+				var found, item,
+					filter = Expr.filter[ type ],
+					left = match[1];
+
+				anyFound = false;
+
+				match.splice(1,1);
+
+				if ( left.substr( left.length - 1 ) === "\\" ) {
+					continue;
+				}
+
+				if ( curLoop === result ) {
+					result = [];
+				}
+
+				if ( Expr.preFilter[ type ] ) {
+					match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
+
+					if ( !match ) {
+						anyFound = found = true;
+
+					} else if ( match === true ) {
+						continue;
+					}
+				}
+
+				if ( match ) {
+					for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
+						if ( item ) {
+							found = filter( item, match, i, curLoop );
+							var pass = not ^ !!found;
+
+							if ( inplace && found != null ) {
+								if ( pass ) {
+									anyFound = true;
+
+								} else {
+									curLoop[i] = false;
+								}
+
+							} else if ( pass ) {
+								result.push( item );
+								anyFound = true;
+							}
+						}
+					}
+				}
+
+				if ( found !== undefined ) {
+					if ( !inplace ) {
+						curLoop = result;
+					}
+
+					expr = expr.replace( Expr.match[ type ], "" );
+
+					if ( !anyFound ) {
+						return [];
+					}
+
+					break;
+				}
+			}
+		}
+
+		// Improper expression
+		if ( expr === old ) {
+			if ( anyFound == null ) {
+				Sizzle.error( expr );
+
+			} else {
+				break;
+			}
+		}
+
+		old = expr;
+	}
+
+	return curLoop;
+};
+
+Sizzle.error = function( msg ) {
+	throw "Syntax error, unrecognized expression: " + msg;
+};
+
+var Expr = Sizzle.selectors = {
+	order: [ "ID", "NAME", "TAG" ],
+
+	match: {
+		ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
+		CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
+		NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
+		ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,
+		TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
+		CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,
+		POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
+		PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
+	},
+
+	leftMatch: {},
+
+	attrMap: {
+		"class": "className",
+		"for": "htmlFor"
+	},
+
+	attrHandle: {
+		href: function( elem ) {
+			return elem.getAttribute( "href" );
+		},
+		type: function( elem ) {
+			return elem.getAttribute( "type" );
+		}
+	},
+
+	relative: {
+		"+": function(checkSet, part){
+			var isPartStr = typeof part === "string",
+				isTag = isPartStr && !rNonWord.test( part ),
+				isPartStrNotTag = isPartStr && !isTag;
+
+			if ( isTag ) {
+				part = part.toLowerCase();
+			}
+
+			for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
+				if ( (elem = checkSet[i]) ) {
+					while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
+
+					checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
+						elem || false :
+						elem === part;
+				}
+			}
+
+			if ( isPartStrNotTag ) {
+				Sizzle.filter( part, checkSet, true );
+			}
+		},
+
+		">": function( checkSet, part ) {
+			var elem,
+				isPartStr = typeof part === "string",
+				i = 0,
+				l = checkSet.length;
+
+			if ( isPartStr && !rNonWord.test( part ) ) {
+				part = part.toLowerCase();
+
+				for ( ; i < l; i++ ) {
+					elem = checkSet[i];
+
+					if ( elem ) {
+						var parent = elem.parentNode;
+						checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
+					}
+				}
+
+			} else {
+				for ( ; i < l; i++ ) {
+					elem = checkSet[i];
+
+					if ( elem ) {
+						checkSet[i] = isPartStr ?
+							elem.parentNode :
+							elem.parentNode === part;
+					}
+				}
+
+				if ( isPartStr ) {
+					Sizzle.filter( part, checkSet, true );
+				}
+			}
+		},
+
+		"": function(checkSet, part, isXML){
+			var nodeCheck,
+				doneName = done++,
+				checkFn = dirCheck;
+
+			if ( typeof part === "string" && !rNonWord.test( part ) ) {
+				part = part.toLowerCase();
+				nodeCheck = part;
+				checkFn = dirNodeCheck;
+			}
+
+			checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML );
+		},
+
+		"~": function( checkSet, part, isXML ) {
+			var nodeCheck,
+				doneName = done++,
+				checkFn = dirCheck;
+
+			if ( typeof part === "string" && !rNonWord.test( part ) ) {
+				part = part.toLowerCase();
+				nodeCheck = part;
+				checkFn = dirNodeCheck;
+			}
+
+			checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML );
+		}
+	},
+
+	find: {
+		ID: function( match, context, isXML ) {
+			if ( typeof context.getElementById !== "undefined" && !isXML ) {
+				var m = context.getElementById(match[1]);
+				// Check parentNode to catch when Blackberry 4.6 returns
+				// nodes that are no longer in the document #6963
+				return m && m.parentNode ? [m] : [];
+			}
+		},
+
+		NAME: function( match, context ) {
+			if ( typeof context.getElementsByName !== "undefined" ) {
+				var ret = [],
+					results = context.getElementsByName( match[1] );
+
+				for ( var i = 0, l = results.length; i < l; i++ ) {
+					if ( results[i].getAttribute("name") === match[1] ) {
+						ret.push( results[i] );
+					}
+				}
+
+				return ret.length === 0 ? null : ret;
+			}
+		},
+
+		TAG: function( match, context ) {
+			if ( typeof context.getElementsByTagName !== "undefined" ) {
+				return context.getElementsByTagName( match[1] );
+			}
+		}
+	},
+	preFilter: {
+		CLASS: function( match, curLoop, inplace, result, not, isXML ) {
+			match = " " + match[1].replace( rBackslash, "" ) + " ";
+
+			if ( isXML ) {
+				return match;
+			}
+
+			for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
+				if ( elem ) {
+					if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) {
+						if ( !inplace ) {
+							result.push( elem );
+						}
+
+					} else if ( inplace ) {
+						curLoop[i] = false;
+					}
+				}
+			}
+
+			return false;
+		},
+
+		ID: function( match ) {
+			return match[1].replace( rBackslash, "" );
+		},
+
+		TAG: function( match, curLoop ) {
+			return match[1].replace( rBackslash, "" ).toLowerCase();
+		},
+
+		CHILD: function( match ) {
+			if ( match[1] === "nth" ) {
+				if ( !match[2] ) {
+					Sizzle.error( match[0] );
+				}
+
+				match[2] = match[2].replace(/^\+|\s*/g, '');
+
+				// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
+				var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec(
+					match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
+					!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
+
+				// calculate the numbers (first)n+(last) including if they are negative
+				match[2] = (test[1] + (test[2] || 1)) - 0;
+				match[3] = test[3] - 0;
+			}
+			else if ( match[2] ) {
+				Sizzle.error( match[0] );
+			}
+
+			// TODO: Move to normal caching system
+			match[0] = done++;
+
+			return match;
+		},
+
+		ATTR: function( match, curLoop, inplace, result, not, isXML ) {
+			var name = match[1] = match[1].replace( rBackslash, "" );
+			
+			if ( !isXML && Expr.attrMap[name] ) {
+				match[1] = Expr.attrMap[name];
+			}
+
+			// Handle if an un-quoted value was used
+			match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" );
+
+			if ( match[2] === "~=" ) {
+				match[4] = " " + match[4] + " ";
+			}
+
+			return match;
+		},
+
+		PSEUDO: function( match, curLoop, inplace, result, not ) {
+			if ( match[1] === "not" ) {
+				// If we're dealing with a complex expression, or a simple one
+				if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
+					match[3] = Sizzle(match[3], null, null, curLoop);
+
+				} else {
+					var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
+
+					if ( !inplace ) {
+						result.push.apply( result, ret );
+					}
+
+					return false;
+				}
+
+			} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
+				return true;
+			}
+			
+			return match;
+		},
+
+		POS: function( match ) {
+			match.unshift( true );
+
+			return match;
+		}
+	},
+	
+	filters: {
+		enabled: function( elem ) {
+			return elem.disabled === false && elem.type !== "hidden";
+		},
+
+		disabled: function( elem ) {
+			return elem.disabled === true;
+		},
+
+		checked: function( elem ) {
+			return elem.checked === true;
+		},
+		
+		selected: function( elem ) {
+			// Accessing this property makes selected-by-default
+			// options in Safari work properly
+			if ( elem.parentNode ) {
+				elem.parentNode.selectedIndex;
+			}
+			
+			return elem.selected === true;
+		},
+
+		parent: function( elem ) {
+			return !!elem.firstChild;
+		},
+
+		empty: function( elem ) {
+			return !elem.firstChild;
+		},
+
+		has: function( elem, i, match ) {
+			return !!Sizzle( match[3], elem ).length;
+		},
+
+		header: function( elem ) {
+			return (/h\d/i).test( elem.nodeName );
+		},
+
+		text: function( elem ) {
+			var attr = elem.getAttribute( "type" ), type = elem.type;
+			// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) 
+			// use getAttribute instead to test this case
+			return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null );
+		},
+
+		radio: function( elem ) {
+			return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type;
+		},
+
+		checkbox: function( elem ) {
+			return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type;
+		},
+
+		file: function( elem ) {
+			return elem.nodeName.toLowerCase() === "input" && "file" === elem.type;
+		},
+
+		password: function( elem ) {
+			return elem.nodeName.toLowerCase() === "input" && "password" === elem.type;
+		},
+
+		submit: function( elem ) {
+			var name = elem.nodeName.toLowerCase();
+			return (name === "input" || name === "button") && "submit" === elem.type;
+		},
+
+		image: function( elem ) {
+			return elem.nodeName.toLowerCase() === "input" && "image" === elem.type;
+		},
+
+		reset: function( elem ) {
+			var name = elem.nodeName.toLowerCase();
+			return (name === "input" || name === "button") && "reset" === elem.type;
+		},
+
+		button: function( elem ) {
+			var name = elem.nodeName.toLowerCase();
+			return name === "input" && "button" === elem.type || name === "button";
+		},
+
+		input: function( elem ) {
+			return (/input|select|textarea|button/i).test( elem.nodeName );
+		},
+
+		focus: function( elem ) {
+			return elem === elem.ownerDocument.activeElement;
+		}
+	},
+	setFilters: {
+		first: function( elem, i ) {
+			return i === 0;
+		},
+
+		last: function( elem, i, match, array ) {
+			return i === array.length - 1;
+		},
+
+		even: function( elem, i ) {
+			return i % 2 === 0;
+		},
+
+		odd: function( elem, i ) {
+			return i % 2 === 1;
+		},
+
+		lt: function( elem, i, match ) {
+			return i < match[3] - 0;
+		},
+
+		gt: function( elem, i, match ) {
+			return i > match[3] - 0;
+		},
+
+		nth: function( elem, i, match ) {
+			return match[3] - 0 === i;
+		},
+
+		eq: function( elem, i, match ) {
+			return match[3] - 0 === i;
+		}
+	},
+	filter: {
+		PSEUDO: function( elem, match, i, array ) {
+			var name = match[1],
+				filter = Expr.filters[ name ];
+
+			if ( filter ) {
+				return filter( elem, i, match, array );
+
+			} else if ( name === "contains" ) {
+				return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0;
+
+			} else if ( name === "not" ) {
+				var not = match[3];
+
+				for ( var j = 0, l = not.length; j < l; j++ ) {
+					if ( not[j] === elem ) {
+						return false;
+					}
+				}
+
+				return true;
+
+			} else {
+				Sizzle.error( name );
+			}
+		},
+
+		CHILD: function( elem, match ) {
+			var type = match[1],
+				node = elem;
+
+			switch ( type ) {
+				case "only":
+				case "first":
+					while ( (node = node.previousSibling) )	 {
+						if ( node.nodeType === 1 ) { 
+							return false; 
+						}
+					}
+
+					if ( type === "first" ) { 
+						return true; 
+					}
+
+					node = elem;
+
+				case "last":
+					while ( (node = node.nextSibling) )	 {
+						if ( node.nodeType === 1 ) { 
+							return false; 
+						}
+					}
+
+					return true;
+
+				case "nth":
+					var first = match[2],
+						last = match[3];
+
+					if ( first === 1 && last === 0 ) {
+						return true;
+					}
+					
+					var doneName = match[0],
+						parent = elem.parentNode;
+	
+					if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
+						var count = 0;
+						
+						for ( node = parent.firstChild; node; node = node.nextSibling ) {
+							if ( node.nodeType === 1 ) {
+								node.nodeIndex = ++count;
+							}
+						} 
+
+						parent.sizcache = doneName;
+					}
+					
+					var diff = elem.nodeIndex - last;
+
+					if ( first === 0 ) {
+						return diff === 0;
+
+					} else {
+						return ( diff % first === 0 && diff / first >= 0 );
+					}
+			}
+		},
+
+		ID: function( elem, match ) {
+			return elem.nodeType === 1 && elem.getAttribute("id") === match;
+		},
+
+		TAG: function( elem, match ) {
+			return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match;
+		},
+		
+		CLASS: function( elem, match ) {
+			return (" " + (elem.className || elem.getAttribute("class")) + " ")
+				.indexOf( match ) > -1;
+		},
+
+		ATTR: function( elem, match ) {
+			var name = match[1],
+				result = Expr.attrHandle[ name ] ?
+					Expr.attrHandle[ name ]( elem ) :
+					elem[ name ] != null ?
+						elem[ name ] :
+						elem.getAttribute( name ),
+				value = result + "",
+				type = match[2],
+				check = match[4];
+
+			return result == null ?
+				type === "!=" :
+				type === "=" ?
+				value === check :
+				type === "*=" ?
+				value.indexOf(check) >= 0 :
+				type === "~=" ?
+				(" " + value + " ").indexOf(check) >= 0 :
+				!check ?
+				value && result !== false :
+				type === "!=" ?
+				value !== check :
+				type === "^=" ?
+				value.indexOf(check) === 0 :
+				type === "$=" ?
+				value.substr(value.length - check.length) === check :
+				type === "|=" ?
+				value === check || value.substr(0, check.length + 1) === check + "-" :
+				false;
+		},
+
+		POS: function( elem, match, i, array ) {
+			var name = match[2],
+				filter = Expr.setFilters[ name ];
+
+			if ( filter ) {
+				return filter( elem, i, match, array );
+			}
+		}
+	}
+};
+
+var origPOS = Expr.match.POS,
+	fescape = function(all, num){
+		return "\\" + (num - 0 + 1);
+	};
+
+for ( var type in Expr.match ) {
+	Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
+	Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
+}
+
+var makeArray = function( array, results ) {
+	array = Array.prototype.slice.call( array, 0 );
+
+	if ( results ) {
+		results.push.apply( results, array );
+		return results;
+	}
+	
+	return array;
+};
+
+// Perform a simple check to determine if the browser is capable of
+// converting a NodeList to an array using builtin methods.
+// Also verifies that the returned array holds DOM nodes
+// (which is not the case in the Blackberry browser)
+try {
+	Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;
+
+// Provide a fallback method if it does not work
+} catch( e ) {
+	makeArray = function( array, results ) {
+		var i = 0,
+			ret = results || [];
+
+		if ( toString.call(array) === "[object Array]" ) {
+			Array.prototype.push.apply( ret, array );
+
+		} else {
+			if ( typeof array.length === "number" ) {
+				for ( var l = array.length; i < l; i++ ) {
+					ret.push( array[i] );
+				}
+
+			} else {
+				for ( ; array[i]; i++ ) {
+					ret.push( array[i] );
+				}
+			}
+		}
+
+		return ret;
+	};
+}
+
+var sortOrder, siblingCheck;
+
+if ( document.documentElement.compareDocumentPosition ) {
+	sortOrder = function( a, b ) {
+		if ( a === b ) {
+			hasDuplicate = true;
+			return 0;
+		}
+
+		if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
+			return a.compareDocumentPosition ? -1 : 1;
+		}
+
+		return a.compareDocumentPosition(b) & 4 ? -1 : 1;
+	};
+
+} else {
+	sortOrder = function( a, b ) {
+		// The nodes are identical, we can exit early
+		if ( a === b ) {
+			hasDuplicate = true;
+			return 0;
+
+		// Fallback to using sourceIndex (in IE) if it's available on both nodes
+		} else if ( a.sourceIndex && b.sourceIndex ) {
+			return a.sourceIndex - b.sourceIndex;
+		}
+
+		var al, bl,
+			ap = [],
+			bp = [],
+			aup = a.parentNode,
+			bup = b.parentNode,
+			cur = aup;
+
+		// If the nodes are siblings (or identical) we can do a quick check
+		if ( aup === bup ) {
+			return siblingCheck( a, b );
+
+		// If no parents were found then the nodes are disconnected
+		} else if ( !aup ) {
+			return -1;
+
+		} else if ( !bup ) {
+			return 1;
+		}
+
+		// Otherwise they're somewhere else in the tree so we need
+		// to build up a full list of the parentNodes for comparison
+		while ( cur ) {
+			ap.unshift( cur );
+			cur = cur.parentNode;
+		}
+
+		cur = bup;
+
+		while ( cur ) {
+			bp.unshift( cur );
+			cur = cur.parentNode;
+		}
+
+		al = ap.length;
+		bl = bp.length;
+
+		// Start walking down the tree looking for a discrepancy
+		for ( var i = 0; i < al && i < bl; i++ ) {
+			if ( ap[i] !== bp[i] ) {
+				return siblingCheck( ap[i], bp[i] );
+			}
+		}
+
+		// We ended someplace up the tree so do a sibling check
+		return i === al ?
+			siblingCheck( a, bp[i], -1 ) :
+			siblingCheck( ap[i], b, 1 );
+	};
+
+	siblingCheck = function( a, b, ret ) {
+		if ( a === b ) {
+			return ret;
+		}
+
+		var cur = a.nextSibling;
+
+		while ( cur ) {
+			if ( cur === b ) {
+				return -1;
+			}
+
+			cur = cur.nextSibling;
+		}
+
+		return 1;
+	};
+}
+
+// Utility function for retreiving the text value of an array of DOM nodes
+Sizzle.getText = function( elems ) {
+	var ret = "", elem;
+
+	for ( var i = 0; elems[i]; i++ ) {
+		elem = elems[i];
+
+		// Get the text from text nodes and CDATA nodes
+		if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
+			ret += elem.nodeValue;
+
+		// Traverse everything else, except comment nodes
+		} else if ( elem.nodeType !== 8 ) {
+			ret += Sizzle.getText( elem.childNodes );
+		}
+	}
+
+	return ret;
+};
+
+// Check to see if the browser returns elements by name when
+// querying by getElementById (and provide a workaround)
+(function(){
+	// We're going to inject a fake input element with a specified name
+	var form = document.createElement("div"),
+		id = "script" + (new Date()).getTime(),
+		root = document.documentElement;
+
+	form.innerHTML = "<a name='" + id + "'/>";
+
+	// Inject it into the root element, check its status, and remove it quickly
+	root.insertBefore( form, root.firstChild );
+
+	// The workaround has to do additional checks after a getElementById
+	// Which slows things down for other browsers (hence the branching)
+	if ( document.getElementById( id ) ) {
+		Expr.find.ID = function( match, context, isXML ) {
+			if ( typeof context.getElementById !== "undefined" && !isXML ) {
+				var m = context.getElementById(match[1]);
+
+				return m ?
+					m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ?
+						[m] :
+						undefined :
+					[];
+			}
+		};
+
+		Expr.filter.ID = function( elem, match ) {
+			var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
+
+			return elem.nodeType === 1 && node && node.nodeValue === match;
+		};
+	}
+
+	root.removeChild( form );
+
+	// release memory in IE
+	root = form = null;
+})();
+
+(function(){
+	// Check to see if the browser returns only elements
+	// when doing getElementsByTagName("*")
+
+	// Create a fake element
+	var div = document.createElement("div");
+	div.appendChild( document.createComment("") );
+
+	// Make sure no comments are found
+	if ( div.getElementsByTagName("*").length > 0 ) {
+		Expr.find.TAG = function( match, context ) {
+			var results = context.getElementsByTagName( match[1] );
+
+			// Filter out possible comments
+			if ( match[1] === "*" ) {
+				var tmp = [];
+
+				for ( var i = 0; results[i]; i++ ) {
+					if ( results[i].nodeType === 1 ) {
+						tmp.push( results[i] );
+					}
+				}
+
+				results = tmp;
+			}
+
+			return results;
+		};
+	}
+
+	// Check to see if an attribute returns normalized href attributes
+	div.innerHTML = "<a href='#'></a>";
+
+	if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
+			div.firstChild.getAttribute("href") !== "#" ) {
+
+		Expr.attrHandle.href = function( elem ) {
+			return elem.getAttribute( "href", 2 );
+		};
+	}
+
+	// release memory in IE
+	div = null;
+})();
+
+if ( document.querySelectorAll ) {
+	(function(){
+		var oldSizzle = Sizzle,
+			div = document.createElement("div"),
+			id = "__sizzle__";
+
+		div.innerHTML = "<p class='TEST'></p>";
+
+		// Safari can't handle uppercase or unicode characters when
+		// in quirks mode.
+		if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
+			return;
+		}
+	
+		Sizzle = function( query, context, extra, seed ) {
+			context = context || document;
+
+			// Only use querySelectorAll on non-XML documents
+			// (ID selectors don't work in non-HTML documents)
+			if ( !seed && !Sizzle.isXML(context) ) {
+				// See if we find a selector to speed up
+				var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query );
+				
+				if ( match && (context.nodeType === 1 || context.nodeType === 9) ) {
+					// Speed-up: Sizzle("TAG")
+					if ( match[1] ) {
+						return makeArray( context.getElementsByTagName( query ), extra );
+					
+					// Speed-up: Sizzle(".CLASS")
+					} else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) {
+						return makeArray( context.getElementsByClassName( match[2] ), extra );
+					}
+				}
+				
+				if ( context.nodeType === 9 ) {
+					// Speed-up: Sizzle("body")
+					// The body element only exists once, optimize finding it
+					if ( query === "body" && context.body ) {
+						return makeArray( [ context.body ], extra );
+						
+					// Speed-up: Sizzle("#ID")
+					} else if ( match && match[3] ) {
+						var elem = context.getElementById( match[3] );
+
+						// Check parentNode to catch when Blackberry 4.6 returns
+						// nodes that are no longer in the document #6963
+						if ( elem && elem.parentNode ) {
+							// Handle the case where IE and Opera return items
+							// by name instead of ID
+							if ( elem.id === match[3] ) {
+								return makeArray( [ elem ], extra );
+							}
+							
+						} else {
+							return makeArray( [], extra );
+						}
+					}
+					
+					try {
+						return makeArray( context.querySelectorAll(query), extra );
+					} catch(qsaError) {}
+
+				// qSA works strangely on Element-rooted queries
+				// We can work around this by specifying an extra ID on the root
+				// and working up from there (Thanks to Andrew Dupont for the technique)
+				// IE 8 doesn't work on object elements
+				} else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
+					var oldContext = context,
+						old = context.getAttribute( "id" ),
+						nid = old || id,
+						hasParent = context.parentNode,
+						relativeHierarchySelector = /^\s*[+~]/.test( query );
+
+					if ( !old ) {
+						context.setAttribute( "id", nid );
+					} else {
+						nid = nid.replace( /'/g, "\\$&" );
+					}
+					if ( relativeHierarchySelector && hasParent ) {
+						context = context.parentNode;
+					}
+
+					try {
+						if ( !relativeHierarchySelector || hasParent ) {
+							return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra );
+						}
+
+					} catch(pseudoError) {
+					} finally {
+						if ( !old ) {
+							oldContext.removeAttribute( "id" );
+						}
+					}
+				}
+			}
+		
+			return oldSizzle(query, context, extra, seed);
+		};
+
+		for ( var prop in oldSizzle ) {
+			Sizzle[ prop ] = oldSizzle[ prop ];
+		}
+
+		// release memory in IE
+		div = null;
+	})();
+}
+
+(function(){
+	var html = document.documentElement,
+		matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector;
+
+	if ( matches ) {
+		// Check to see if it's possible to do matchesSelector
+		// on a disconnected node (IE 9 fails this)
+		var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ),
+			pseudoWorks = false;
+
+		try {
+			// This should fail with an exception
+			// Gecko does not error, returns false instead
+			matches.call( document.documentElement, "[test!='']:sizzle" );
+	
+		} catch( pseudoError ) {
+			pseudoWorks = true;
+		}
+
+		Sizzle.matchesSelector = function( node, expr ) {
+			// Make sure that attribute selectors are quoted
+			expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
+
+			if ( !Sizzle.isXML( node ) ) {
+				try { 
+					if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) {
+						var ret = matches.call( node, expr );
+
+						// IE 9's matchesSelector returns false on disconnected nodes
+						if ( ret || !disconnectedMatch ||
+								// As well, disconnected nodes are said to be in a document
+								// fragment in IE 9, so check for that
+								node.document && node.document.nodeType !== 11 ) {
+							return ret;
+						}
+					}
+				} catch(e) {}
+			}
+
+			return Sizzle(expr, null, null, [node]).length > 0;
+		};
+	}
+})();
+
+(function(){
+	var div = document.createElement("div");
+
+	div.innerHTML = "<div class='test e'></div><div class='test'></div>";
+
+	// Opera can't find a second classname (in 9.6)
+	// Also, make sure that getElementsByClassName actually exists
+	if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
+		return;
+	}
+
+	// Safari caches class attributes, doesn't catch changes (in 3.2)
+	div.lastChild.className = "e";
+
+	if ( div.getElementsByClassName("e").length === 1 ) {
+		return;
+	}
+	
+	Expr.order.splice(1, 0, "CLASS");
+	Expr.find.CLASS = function( match, context, isXML ) {
+		if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
+			return context.getElementsByClassName(match[1]);
+		}
+	};
+
+	// release memory in IE
+	div = null;
+})();
+
+function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
+	for ( var i = 0, l = checkSet.length; i < l; i++ ) {
+		var elem = checkSet[i];
+
+		if ( elem ) {
+			var match = false;
+
+			elem = elem[dir];
+
+			while ( elem ) {
+				if ( elem.sizcache === doneName ) {
+					match = checkSet[elem.sizset];
+					break;
+				}
+
+				if ( elem.nodeType === 1 && !isXML ){
+					elem.sizcache = doneName;
+					elem.sizset = i;
+				}
+
+				if ( elem.nodeName.toLowerCase() === cur ) {
+					match = elem;
+					break;
+				}
+
+				elem = elem[dir];
+			}
+
+			checkSet[i] = match;
+		}
+	}
+}
+
+function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
+	for ( var i = 0, l = checkSet.length; i < l; i++ ) {
+		var elem = checkSet[i];
+
+		if ( elem ) {
+			var match = false;
+			
+			elem = elem[dir];
+
+			while ( elem ) {
+				if ( elem.sizcache === doneName ) {
+					match = checkSet[elem.sizset];
+					break;
+				}
+
+				if ( elem.nodeType === 1 ) {
+					if ( !isXML ) {
+						elem.sizcache = doneName;
+						elem.sizset = i;
+					}
+
+					if ( typeof cur !== "string" ) {
+						if ( elem === cur ) {
+							match = true;
+							break;
+						}
+
+					} else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
+						match = elem;
+						break;
+					}
+				}
+
+				elem = elem[dir];
+			}
+
+			checkSet[i] = match;
+		}
+	}
+}
+
+if ( document.documentElement.contains ) {
+	Sizzle.contains = function( a, b ) {
+		return a !== b && (a.contains ? a.contains(b) : true);
+	};
+
+} else if ( document.documentElement.compareDocumentPosition ) {
+	Sizzle.contains = function( a, b ) {
+		return !!(a.compareDocumentPosition(b) & 16);
+	};
+
+} else {
+	Sizzle.contains = function() {
+		return false;
+	};
+}
+
+Sizzle.isXML = function( elem ) {
+	// documentElement is verified for cases where it doesn't yet exist
+	// (such as loading iframes in IE - #4833) 
+	var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
+
+	return documentElement ? documentElement.nodeName !== "HTML" : false;
+};
+
+var posProcess = function( selector, context ) {
+	var match,
+		tmpSet = [],
+		later = "",
+		root = context.nodeType ? [context] : context;
+
+	// Position selectors must be done after the filter
+	// And so must :not(positional) so we move all PSEUDOs to the end
+	while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
+		later += match[0];
+		selector = selector.replace( Expr.match.PSEUDO, "" );
+	}
+
+	selector = Expr.relative[selector] ? selector + "*" : selector;
+
+	for ( var i = 0, l = root.length; i < l; i++ ) {
+		Sizzle( selector, root[i], tmpSet );
+	}
+
+	return Sizzle.filter( later, tmpSet );
+};
+
+// EXPOSE
+jQuery.find = Sizzle;
+jQuery.expr = Sizzle.selectors;
+jQuery.expr[":"] = jQuery.expr.filters;
+jQuery.unique = Sizzle.uniqueSort;
+jQuery.text = Sizzle.getText;
+jQuery.isXMLDoc = Sizzle.isXML;
+jQuery.contains = Sizzle.contains;
+
+
+})();
+
+
+var runtil = /Until$/,
+	rparentsprev = /^(?:parents|prevUntil|prevAll)/,
+	// Note: This RegExp should be improved, or likely pulled from Sizzle
+	rmultiselector = /,/,
+	isSimple = /^.[^:#\[\.,]*$/,
+	slice = Array.prototype.slice,
+	POS = jQuery.expr.match.POS,
+	// methods guaranteed to produce a unique set when starting from a unique set
+	guaranteedUnique = {
+		children: true,
+		contents: true,
+		next: true,
+		prev: true
+	};
+
+jQuery.fn.extend({
+	find: function( selector ) {
+		var self = this,
+			i, l;
+
+		if ( typeof selector !== "string" ) {
+			return jQuery( selector ).filter(function() {
+				for ( i = 0, l = self.length; i < l; i++ ) {
+					if ( jQuery.contains( self[ i ], this ) ) {
+						return true;
+					}
+				}
+			});
+		}
+
+		var ret = this.pushStack( "", "find", selector ),
+			length, n, r;
+
+		for ( i = 0, l = this.length; i < l; i++ ) {
+			length = ret.length;
+			jQuery.find( selector, this[i], ret );
+
+			if ( i > 0 ) {
+				// Make sure that the results are unique
+				for ( n = length; n < ret.length; n++ ) {
+					for ( r = 0; r < length; r++ ) {
+						if ( ret[r] === ret[n] ) {
+							ret.splice(n--, 1);
+							break;
+						}
+					}
+				}
+			}
+		}
+
+		return ret;
+	},
+
+	has: function( target ) {
+		var targets = jQuery( target );
+		return this.filter(function() {
+			for ( var i = 0, l = targets.length; i < l; i++ ) {
+				if ( jQuery.contains( this, targets[i] ) ) {
+					return true;
+				}
+			}
+		});
+	},
+
+	not: function( selector ) {
+		return this.pushStack( winnow(this, selector, false), "not", selector);
+	},
+
+	filter: function( selector ) {
+		return this.pushStack( winnow(this, selector, true), "filter", selector );
+	},
+
+	is: function( selector ) {
+		return !!selector && ( typeof selector === "string" ?
+			jQuery.filter( selector, this ).length > 0 :
+			this.filter( selector ).length > 0 );
+	},
+
+	closest: function( selectors, context ) {
+		var ret = [], i, l, cur = this[0];
+		
+		// Array
+		if ( jQuery.isArray( selectors ) ) {
+			var match, selector,
+				matches = {},
+				level = 1;
+
+			if ( cur && selectors.length ) {
+				for ( i = 0, l = selectors.length; i < l; i++ ) {
+					selector = selectors[i];
+
+					if ( !matches[ selector ] ) {
+						matches[ selector ] = POS.test( selector ) ?
+							jQuery( selector, context || this.context ) :
+							selector;
+					}
+				}
+
+				while ( cur && cur.ownerDocument && cur !== context ) {
+					for ( selector in matches ) {
+						match = matches[ selector ];
+
+						if ( match.jquery ? match.index( cur ) > -1 : jQuery( cur ).is( match ) ) {
+							ret.push({ selector: selector, elem: cur, level: level });
+						}
+					}
+
+					cur = cur.parentNode;
+					level++;
+				}
+			}
+
+			return ret;
+		}
+
+		// String
+		var pos = POS.test( selectors ) || typeof selectors !== "string" ?
+				jQuery( selectors, context || this.context ) :
+				0;
+
+		for ( i = 0, l = this.length; i < l; i++ ) {
+			cur = this[i];
+
+			while ( cur ) {
+				if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
+					ret.push( cur );
+					break;
+
+				} else {
+					cur = cur.parentNode;
+					if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) {
+						break;
+					}
+				}
+			}
+		}
+
+		ret = ret.length > 1 ? jQuery.unique( ret ) : ret;
+
+		return this.pushStack( ret, "closest", selectors );
+	},
+
+	// Determine the position of an element within
+	// the matched set of elements
+	index: function( elem ) {
+
+		// No argument, return index in parent
+		if ( !elem ) {
+			return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
+		}
+
+		// index in selector
+		if ( typeof elem === "string" ) {
+			return jQuery.inArray( this[0], jQuery( elem ) );
+		}
+
+		// Locate the position of the desired element
+		return jQuery.inArray(
+			// If it receives a jQuery object, the first element is used
+			elem.jquery ? elem[0] : elem, this );
+	},
+
+	add: function( selector, context ) {
+		var set = typeof selector === "string" ?
+				jQuery( selector, context ) :
+				jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
+			all = jQuery.merge( this.get(), set );
+
+		return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
+			all :
+			jQuery.unique( all ) );
+	},
+
+	andSelf: function() {
+		return this.add( this.prevObject );
+	}
+});
+
+// A painfully simple check to see if an element is disconnected
+// from a document (should be improved, where feasible).
+function isDisconnected( node ) {
+	return !node || !node.parentNode || node.parentNode.nodeType === 11;
+}
+
+jQuery.each({
+	parent: function( elem ) {
+		var parent = elem.parentNode;
+		return parent && parent.nodeType !== 11 ? parent : null;
+	},
+	parents: function( elem ) {
+		return jQuery.dir( elem, "parentNode" );
+	},
+	parentsUntil: function( elem, i, until ) {
+		return jQuery.dir( elem, "parentNode", until );
+	},
+	next: function( elem ) {
+		return jQuery.nth( elem, 2, "nextSibling" );
+	},
+	prev: function( elem ) {
+		return jQuery.nth( elem, 2, "previousSibling" );
+	},
+	nextAll: function( elem ) {
+		return jQuery.dir( elem, "nextSibling" );
+	},
+	prevAll: function( elem ) {
+		return jQuery.dir( elem, "previousSibling" );
+	},
+	nextUntil: function( elem, i, until ) {
+		return jQuery.dir( elem, "nextSibling", until );
+	},
+	prevUntil: function( elem, i, until ) {
+		return jQuery.dir( elem, "previousSibling", until );
+	},
+	siblings: function( elem ) {
+		return jQuery.sibling( elem.parentNode.firstChild, elem );
+	},
+	children: function( elem ) {
+		return jQuery.sibling( elem.firstChild );
+	},
+	contents: function( elem ) {
+		return jQuery.nodeName( elem, "iframe" ) ?
+			elem.contentDocument || elem.contentWindow.document :
+			jQuery.makeArray( elem.childNodes );
+	}
+}, function( name, fn ) {
+	jQuery.fn[ name ] = function( until, selector ) {
+		var ret = jQuery.map( this, fn, until ),
+			// The variable 'args' was introduced in
+			// https://github.com/jquery/jquery/commit/52a0238
+			// to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed.
+			// http://code.google.com/p/v8/issues/detail?id=1050
+			args = slice.call(arguments);
+
+		if ( !runtil.test( name ) ) {
+			selector = until;
+		}
+
+		if ( selector && typeof selector === "string" ) {
+			ret = jQuery.filter( selector, ret );
+		}
+
+		ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
+
+		if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
+			ret = ret.reverse();
+		}
+
+		return this.pushStack( ret, name, args.join(",") );
+	};
+});
+
+jQuery.extend({
+	filter: function( expr, elems, not ) {
+		if ( not ) {
+			expr = ":not(" + expr + ")";
+		}
+
+		return elems.length === 1 ?
+			jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
+			jQuery.find.matches(expr, elems);
+	},
+
+	dir: function( elem, dir, until ) {
+		var matched = [],
+			cur = elem[ dir ];
+
+		while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
+			if ( cur.nodeType === 1 ) {
+				matched.push( cur );
+			}
+			cur = cur[dir];
+		}
+		return matched;
+	},
+
+	nth: function( cur, result, dir, elem ) {
+		result = result || 1;
+		var num = 0;
+
+		for ( ; cur; cur = cur[dir] ) {
+			if ( cur.nodeType === 1 && ++num === result ) {
+				break;
+			}
+		}
+
+		return cur;
+	},
+
+	sibling: function( n, elem ) {
+		var r = [];
+
+		for ( ; n; n = n.nextSibling ) {
+			if ( n.nodeType === 1 && n !== elem ) {
+				r.push( n );
+			}
+		}
+
+		return r;
+	}
+});
+
+// Implement the identical functionality for filter and not
+function winnow( elements, qualifier, keep ) {
+
+	// Can't pass null or undefined to indexOf in Firefox 4
+	// Set to 0 to skip string check
+	qualifier = qualifier || 0;
+
+	if ( jQuery.isFunction( qualifier ) ) {
+		return jQuery.grep(elements, function( elem, i ) {
+			var retVal = !!qualifier.call( elem, i, elem );
+			return retVal === keep;
+		});
+
+	} else if ( qualifier.nodeType ) {
+		return jQuery.grep(elements, function( elem, i ) {
+			return (elem === qualifier) === keep;
+		});
+
+	} else if ( typeof qualifier === "string" ) {
+		var filtered = jQuery.grep(elements, function( elem ) {
+			return elem.nodeType === 1;
+		});
+
+		if ( isSimple.test( qualifier ) ) {
+			return jQuery.filter(qualifier, filtered, !keep);
+		} else {
+			qualifier = jQuery.filter( qualifier, filtered );
+		}
+	}
+
+	return jQuery.grep(elements, function( elem, i ) {
+		return (jQuery.inArray( elem, qualifier ) >= 0) === keep;
+	});
+}
+
+
+
+
+var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
+	rleadingWhitespace = /^\s+/,
+	rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
+	rtagName = /<([\w:]+)/,
+	rtbody = /<tbody/i,
+	rhtml = /<|&#?\w+;/,
+	rnocache = /<(?:script|object|embed|option|style)/i,
+	// checked="checked" or checked
+	rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
+	rscriptType = /\/(java|ecma)script/i,
+	rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/,
+	wrapMap = {
+		option: [ 1, "<select multiple='multiple'>", "</select>" ],
+		legend: [ 1, "<fieldset>", "</fieldset>" ],
+		thead: [ 1, "<table>", "</table>" ],
+		tr: [ 2, "<table><tbody>", "</tbody></table>" ],
+		td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
+		col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
+		area: [ 1, "<map>", "</map>" ],
+		_default: [ 0, "", "" ]
+	};
+
+wrapMap.optgroup = wrapMap.option;
+wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
+wrapMap.th = wrapMap.td;
+
+// IE can't serialize <link> and <script> tags normally
+if ( !jQuery.support.htmlSerialize ) {
+	wrapMap._default = [ 1, "div<div>", "</div>" ];
+}
+
+jQuery.fn.extend({
+	text: function( text ) {
+		if ( jQuery.isFunction(text) ) {
+			return this.each(function(i) {
+				var self = jQuery( this );
+
+				self.text( text.call(this, i, self.text()) );
+			});
+		}
+
+		if ( typeof text !== "object" && text !== undefined ) {
+			return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
+		}
+
+		return jQuery.text( this );
+	},
+
+	wrapAll: function( html ) {
+		if ( jQuery.isFunction( html ) ) {
+			return this.each(function(i) {
+				jQuery(this).wrapAll( html.call(this, i) );
+			});
+		}
+
+		if ( this[0] ) {
+			// The elements to wrap the target around
+			var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
+
+			if ( this[0].parentNode ) {
+				wrap.insertBefore( this[0] );
+			}
+
+			wrap.map(function() {
+				var elem = this;
+
+				while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
+					elem = elem.firstChild;
+				}
+
+				return elem;
+			}).append( this );
+		}
+
+		return this;
+	},
+
+	wrapInner: function( html ) {
+		if ( jQuery.isFunction( html ) ) {
+			return this.each(function(i) {
+				jQuery(this).wrapInner( html.call(this, i) );
+			});
+		}
+
+		return this.each(function() {
+			var self = jQuery( this ),
+				contents = self.contents();
+
+			if ( contents.length ) {
+				contents.wrapAll( html );
+
+			} else {
+				self.append( html );
+			}
+		});
+	},
+
+	wrap: function( html ) {
+		return this.each(function() {
+			jQuery( this ).wrapAll( html );
+		});
+	},
+
+	unwrap: function() {
+		return this.parent().each(function() {
+			if ( !jQuery.nodeName( this, "body" ) ) {
+				jQuery( this ).replaceWith( this.childNodes );
+			}
+		}).end();
+	},
+
+	append: function() {
+		return this.domManip(arguments, true, function( elem ) {
+			if ( this.nodeType === 1 ) {
+				this.appendChild( elem );
+			}
+		});
+	},
+
+	prepend: function() {
+		return this.domManip(arguments, true, function( elem ) {
+			if ( this.nodeType === 1 ) {
+				this.insertBefore( elem, this.firstChild );
+			}
+		});
+	},
+
+	before: function() {
+		if ( this[0] && this[0].parentNode ) {
+			return this.domManip(arguments, false, function( elem ) {
+				this.parentNode.insertBefore( elem, this );
+			});
+		} else if ( arguments.length ) {
+			var set = jQuery(arguments[0]);
+			set.push.apply( set, this.toArray() );
+			return this.pushStack( set, "before", arguments );
+		}
+	},
+
+	after: function() {
+		if ( this[0] && this[0].parentNode ) {
+			return this.domManip(arguments, false, function( elem ) {
+				this.parentNode.insertBefore( elem, this.nextSibling );
+			});
+		} else if ( arguments.length ) {
+			var set = this.pushStack( this, "after", arguments );
+			set.push.apply( set, jQuery(arguments[0]).toArray() );
+			return set;
+		}
+	},
+
+	// keepData is for internal use only--do not document
+	remove: function( selector, keepData ) {
+		for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
+			if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
+				if ( !keepData && elem.nodeType === 1 ) {
+					jQuery.cleanData( elem.getElementsByTagName("*") );
+					jQuery.cleanData( [ elem ] );
+				}
+
+				if ( elem.parentNode ) {
+					elem.parentNode.removeChild( elem );
+				}
+			}
+		}
+
+		return this;
+	},
+
+	empty: function() {
+		for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
+			// Remove element nodes and prevent memory leaks
+			if ( elem.nodeType === 1 ) {
+				jQuery.cleanData( elem.getElementsByTagName("*") );
+			}
+
+			// Remove any remaining nodes
+			while ( elem.firstChild ) {
+				elem.removeChild( elem.firstChild );
+			}
+		}
+
+		return this;
+	},
+
+	clone: function( dataAndEvents, deepDataAndEvents ) {
+		dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
+		deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
+
+		return this.map( function () {
+			return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
+		});
+	},
+
+	html: function( value ) {
+		if ( value === undefined ) {
+			return this[0] && this[0].nodeType === 1 ?
+				this[0].innerHTML.replace(rinlinejQuery, "") :
+				null;
+
+		// See if we can take a shortcut and just use innerHTML
+		} else if ( typeof value === "string" && !rnocache.test( value ) &&
+			(jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
+			!wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
+
+			value = value.replace(rxhtmlTag, "<$1></$2>");
+
+			try {
+				for ( var i = 0, l = this.length; i < l; i++ ) {
+					// Remove element nodes and prevent memory leaks
+					if ( this[i].nodeType === 1 ) {
+						jQuery.cleanData( this[i].getElementsByTagName("*") );
+						this[i].innerHTML = value;
+					}
+				}
+
+			// If using innerHTML throws an exception, use the fallback method
+			} catch(e) {
+				this.empty().append( value );
+			}
+
+		} else if ( jQuery.isFunction( value ) ) {
+			this.each(function(i){
+				var self = jQuery( this );
+
+				self.html( value.call(this, i, self.html()) );
+			});
+
+		} else {
+			this.empty().append( value );
+		}
+
+		return this;
+	},
+
+	replaceWith: function( value ) {
+		if ( this[0] && this[0].parentNode ) {
+			// Make sure that the elements are removed from the DOM before they are inserted
+			// this can help fix replacing a parent with child elements
+			if ( jQuery.isFunction( value ) ) {
+				return this.each(function(i) {
+					var self = jQuery(this), old = self.html();
+					self.replaceWith( value.call( this, i, old ) );
+				});
+			}
+
+			if ( typeof value !== "string" ) {
+				value = jQuery( value ).detach();
+			}
+
+			return this.each(function() {
+				var next = this.nextSibling,
+					parent = this.parentNode;
+
+				jQuery( this ).remove();
+
+				if ( next ) {
+					jQuery(next).before( value );
+				} else {
+					jQuery(parent).append( value );
+				}
+			});
+		} else {
+			return this.length ?
+				this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
+				this;
+		}
+	},
+
+	detach: function( selector ) {
+		return this.remove( selector, true );
+	},
+
+	domManip: function( args, table, callback ) {
+		var results, first, fragment, parent,
+			value = args[0],
+			scripts = [];
+
+		// We can't cloneNode fragments that contain checked, in WebKit
+		if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) {
+			return this.each(function() {
+				jQuery(this).domManip( args, table, callback, true );
+			});
+		}
+
+		if ( jQuery.isFunction(value) ) {
+			return this.each(function(i) {
+				var self = jQuery(this);
+				args[0] = value.call(this, i, table ? self.html() : undefined);
+				self.domManip( args, table, callback );
+			});
+		}
+
+		if ( this[0] ) {
+			parent = value && value.parentNode;
+
+			// If we're in a fragment, just use that instead of building a new one
+			if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) {
+				results = { fragment: parent };
+
+			} else {
+				results = jQuery.buildFragment( args, this, scripts );
+			}
+
+			fragment = results.fragment;
+
+			if ( fragment.childNodes.length === 1 ) {
+				first = fragment = fragment.firstChild;
+			} else {
+				first = fragment.firstChild;
+			}
+
+			if ( first ) {
+				table = table && jQuery.nodeName( first, "tr" );
+
+				for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) {
+					callback.call(
+						table ?
+							root(this[i], first) :
+							this[i],
+						// Make sure that we do not leak memory by inadvertently discarding
+						// the original fragment (which might have attached data) instead of
+						// using it; in addition, use the original fragment object for the last
+						// item instead of first because it can end up being emptied incorrectly
+						// in certain situations (Bug #8070).
+						// Fragments from the fragment cache must always be cloned and never used
+						// in place.
+						results.cacheable || (l > 1 && i < lastIndex) ?
+							jQuery.clone( fragment, true, true ) :
+							fragment
+					);
+				}
+			}
+
+			if ( scripts.length ) {
+				jQuery.each( scripts, evalScript );
+			}
+		}
+
+		return this;
+	}
+});
+
+function root( elem, cur ) {
+	return jQuery.nodeName(elem, "table") ?
+		(elem.getElementsByTagName("tbody")[0] ||
+		elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
+		elem;
+}
+
+function cloneCopyEvent( src, dest ) {
+
+	if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
+		return;
+	}
+
+	var internalKey = jQuery.expando,
+		oldData = jQuery.data( src ),
+		curData = jQuery.data( dest, oldData );
+
+	// Switch to use the internal data object, if it exists, for the next
+	// stage of data copying
+	if ( (oldData = oldData[ internalKey ]) ) {
+		var events = oldData.events;
+				curData = curData[ internalKey ] = jQuery.extend({}, oldData);
+
+		if ( events ) {
+			delete curData.handle;
+			curData.events = {};
+
+			for ( var type in events ) {
+				for ( var i = 0, l = events[ type ].length; i < l; i++ ) {
+					jQuery.event.add( dest, type + ( events[ type ][ i ].namespace ? "." : "" ) + events[ type ][ i ].namespace, events[ type ][ i ], events[ type ][ i ].data );
+				}
+			}
+		}
+	}
+}
+
+function cloneFixAttributes( src, dest ) {
+	var nodeName;
+
+	// We do not need to do anything for non-Elements
+	if ( dest.nodeType !== 1 ) {
+		return;
+	}
+
+	// clearAttributes removes the attributes, which we don't want,
+	// but also removes the attachEvent events, which we *do* want
+	if ( dest.clearAttributes ) {
+		dest.clearAttributes();
+	}
+
+	// mergeAttributes, in contrast, only merges back on the
+	// original attributes, not the events
+	if ( dest.mergeAttributes ) {
+		dest.mergeAttributes( src );
+	}
+
+	nodeName = dest.nodeName.toLowerCase();
+
+	// IE6-8 fail to clone children inside object elements that use
+	// the proprietary classid attribute value (rather than the type
+	// attribute) to identify the type of content to display
+	if ( nodeName === "object" ) {
+		dest.outerHTML = src.outerHTML;
+
+	} else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) {
+		// IE6-8 fails to persist the checked state of a cloned checkbox
+		// or radio button. Worse, IE6-7 fail to give the cloned element
+		// a checked appearance if the defaultChecked value isn't also set
+		if ( src.checked ) {
+			dest.defaultChecked = dest.checked = src.checked;
+		}
+
+		// IE6-7 get confused and end up setting the value of a cloned
+		// checkbox/radio button to an empty string instead of "on"
+		if ( dest.value !== src.value ) {
+			dest.value = src.value;
+		}
+
+	// IE6-8 fails to return the selected option to the default selected
+	// state when cloning options
+	} else if ( nodeName === "option" ) {
+		dest.selected = src.defaultSelected;
+
+	// IE6-8 fails to set the defaultValue to the correct value when
+	// cloning other types of input fields
+	} else if ( nodeName === "input" || nodeName === "textarea" ) {
+		dest.defaultValue = src.defaultValue;
+	}
+
+	// Event data gets referenced instead of copied if the expando
+	// gets copied too
+	dest.removeAttribute( jQuery.expando );
+}
+
+jQuery.buildFragment = function( args, nodes, scripts ) {
+	var fragment, cacheable, cacheresults, doc;
+
+  // nodes may contain either an explicit document object,
+  // a jQuery collection or context object.
+  // If nodes[0] contains a valid object to assign to doc
+  if ( nodes && nodes[0] ) {
+    doc = nodes[0].ownerDocument || nodes[0];
+  }
+
+  // Ensure that an attr object doesn't incorrectly stand in as a document object
+	// Chrome and Firefox seem to allow this to occur and will throw exception
+	// Fixes #8950
+	if ( !doc.createDocumentFragment ) {
+		doc = document;
+	}
+
+	// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
+	// Cloning options loses the selected state, so don't cache them
+	// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
+	// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
+	if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document &&
+		args[0].charAt(0) === "<" && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) {
+
+		cacheable = true;
+
+		cacheresults = jQuery.fragments[ args[0] ];
+		if ( cacheresults && cacheresults !== 1 ) {
+			fragment = cacheresults;
+		}
+	}
+
+	if ( !fragment ) {
+		fragment = doc.createDocumentFragment();
+		jQuery.clean( args, doc, fragment, scripts );
+	}
+
+	if ( cacheable ) {
+		jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1;
+	}
+
+	return { fragment: fragment, cacheable: cacheable };
+};
+
+jQuery.fragments = {};
+
+jQuery.each({
+	appendTo: "append",
+	prependTo: "prepend",
+	insertBefore: "before",
+	insertAfter: "after",
+	replaceAll: "replaceWith"
+}, function( name, original ) {
+	jQuery.fn[ name ] = function( selector ) {
+		var ret = [],
+			insert = jQuery( selector ),
+			parent = this.length === 1 && this[0].parentNode;
+
+		if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
+			insert[ original ]( this[0] );
+			return this;
+
+		} else {
+			for ( var i = 0, l = insert.length; i < l; i++ ) {
+				var elems = (i > 0 ? this.clone(true) : this).get();
+				jQuery( insert[i] )[ original ]( elems );
+				ret = ret.concat( elems );
+			}
+
+			return this.pushStack( ret, name, insert.selector );
+		}
+	};
+});
+
+function getAll( elem ) {
+	if ( "getElementsByTagName" in elem ) {
+		return elem.getElementsByTagName( "*" );
+
+	} else if ( "querySelectorAll" in elem ) {
+		return elem.querySelectorAll( "*" );
+
+	} else {
+		return [];
+	}
+}
+
+// Used in clean, fixes the defaultChecked property
+function fixDefaultChecked( elem ) {
+	if ( elem.type === "checkbox" || elem.type === "radio" ) {
+		elem.defaultChecked = elem.checked;
+	}
+}
+// Finds all inputs and passes them to fixDefaultChecked
+function findInputs( elem ) {
+	if ( jQuery.nodeName( elem, "input" ) ) {
+		fixDefaultChecked( elem );
+	} else if ( "getElementsByTagName" in elem ) {
+		jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
+	}
+}
+
+jQuery.extend({
+	clone: function( elem, dataAndEvents, deepDataAndEvents ) {
+		var clone = elem.cloneNode(true),
+				srcElements,
+				destElements,
+				i;
+
+		if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
+				(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
+			// IE copies events bound via attachEvent when using cloneNode.
+			// Calling detachEvent on the clone will also remove the events
+			// from the original. In order to get around this, we use some
+			// proprietary methods to clear the events. Thanks to MooTools
+			// guys for this hotness.
+
+			cloneFixAttributes( elem, clone );
+
+			// Using Sizzle here is crazy slow, so we use getElementsByTagName
+			// instead
+			srcElements = getAll( elem );
+			destElements = getAll( clone );
+
+			// Weird iteration because IE will replace the length property
+			// with an element if you are cloning the body and one of the
+			// elements on the page has a name or id of "length"
+			for ( i = 0; srcElements[i]; ++i ) {
+				// Ensure that the destination node is not null; Fixes #9587
+				if ( destElements[i] ) {
+					cloneFixAttributes( srcElements[i], destElements[i] );
+				}
+			}
+		}
+
+		// Copy the events from the original to the clone
+		if ( dataAndEvents ) {
+			cloneCopyEvent( elem, clone );
+
+			if ( deepDataAndEvents ) {
+				srcElements = getAll( elem );
+				destElements = getAll( clone );
+
+				for ( i = 0; srcElements[i]; ++i ) {
+					cloneCopyEvent( srcElements[i], destElements[i] );
+				}
+			}
+		}
+
+		srcElements = destElements = null;
+
+		// Return the cloned set
+		return clone;
+	},
+
+	clean: function( elems, context, fragment, scripts ) {
+		var checkScriptType;
+
+		context = context || document;
+
+		// !context.createElement fails in IE with an error but returns typeof 'object'
+		if ( typeof context.createElement === "undefined" ) {
+			context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
+		}
+
+		var ret = [], j;
+
+		for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
+			if ( typeof elem === "number" ) {
+				elem += "";
+			}
+
+			if ( !elem ) {
+				continue;
+			}
+
+			// Convert html string into DOM nodes
+			if ( typeof elem === "string" ) {
+				if ( !rhtml.test( elem ) ) {
+					elem = context.createTextNode( elem );
+				} else {
+					// Fix "XHTML"-style tags in all browsers
+					elem = elem.replace(rxhtmlTag, "<$1></$2>");
+
+					// Trim whitespace, otherwise indexOf won't work as expected
+					var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(),
+						wrap = wrapMap[ tag ] || wrapMap._default,
+						depth = wrap[0],
+						div = context.createElement("div");
+
+					// Go to html and back, then peel off extra wrappers
+					div.innerHTML = wrap[1] + elem + wrap[2];
+
+					// Move to the right depth
+					while ( depth-- ) {
+						div = div.lastChild;
+					}
+
+					// Remove IE's autoinserted <tbody> from table fragments
+					if ( !jQuery.support.tbody ) {
+
+						// String was a <table>, *may* have spurious <tbody>
+						var hasBody = rtbody.test(elem),
+							tbody = tag === "table" && !hasBody ?
+								div.firstChild && div.firstChild.childNodes :
+
+								// String was a bare <thead> or <tfoot>
+								wrap[1] === "<table>" && !hasBody ?
+									div.childNodes :
+									[];
+
+						for ( j = tbody.length - 1; j >= 0 ; --j ) {
+							if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
+								tbody[ j ].parentNode.removeChild( tbody[ j ] );
+							}
+						}
+					}
+
+					// IE completely kills leading whitespace when innerHTML is used
+					if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
+						div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
+					}
+
+					elem = div.childNodes;
+				}
+			}
+
+			// Resets defaultChecked for any radios and checkboxes
+			// about to be appended to the DOM in IE 6/7 (#8060)
+			var len;
+			if ( !jQuery.support.appendChecked ) {
+				if ( elem[0] && typeof (len = elem.length) === "number" ) {
+					for ( j = 0; j < len; j++ ) {
+						findInputs( elem[j] );
+					}
+				} else {
+					findInputs( elem );
+				}
+			}
+
+			if ( elem.nodeType ) {
+				ret.push( elem );
+			} else {
+				ret = jQuery.merge( ret, elem );
+			}
+		}
+
+		if ( fragment ) {
+			checkScriptType = function( elem ) {
+				return !elem.type || rscriptType.test( elem.type );
+			};
+			for ( i = 0; ret[i]; i++ ) {
+				if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
+					scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
+
+				} else {
+					if ( ret[i].nodeType === 1 ) {
+						var jsTags = jQuery.grep( ret[i].getElementsByTagName( "script" ), checkScriptType );
+
+						ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
+					}
+					fragment.appendChild( ret[i] );
+				}
+			}
+		}
+
+		return ret;
+	},
+
+	cleanData: function( elems ) {
+		var data, id, cache = jQuery.cache, internalKey = jQuery.expando, special = jQuery.event.special,
+			deleteExpando = jQuery.support.deleteExpando;
+
+		for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
+			if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
+				continue;
+			}
+
+			id = elem[ jQuery.expando ];
+
+			if ( id ) {
+				data = cache[ id ] && cache[ id ][ internalKey ];
+
+				if ( data && data.events ) {
+					for ( var type in data.events ) {
+						if ( special[ type ] ) {
+							jQuery.event.remove( elem, type );
+
+						// This is a shortcut to avoid jQuery.event.remove's overhead
+						} else {
+							jQuery.removeEvent( elem, type, data.handle );
+						}
+					}
+
+					// Null the DOM reference to avoid IE6/7/8 leak (#7054)
+					if ( data.handle ) {
+						data.handle.elem = null;
+					}
+				}
+
+				if ( deleteExpando ) {
+					delete elem[ jQuery.expando ];
+
+				} else if ( elem.removeAttribute ) {
+					elem.removeAttribute( jQuery.expando );
+				}
+
+				delete cache[ id ];
+			}
+		}
+	}
+});
+
+function evalScript( i, elem ) {
+	if ( elem.src ) {
+		jQuery.ajax({
+			url: elem.src,
+			async: false,
+			dataType: "script"
+		});
+	} else {
+		jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "/*$0*/" ) );
+	}
+
+	if ( elem.parentNode ) {
+		elem.parentNode.removeChild( elem );
+	}
+}
+
+
+
+
+var ralpha = /alpha\([^)]*\)/i,
+	ropacity = /opacity=([^)]*)/,
+	// fixed for IE9, see #8346
+	rupper = /([A-Z]|^ms)/g,
+	rnumpx = /^-?\d+(?:px)?$/i,
+	rnum = /^-?\d/,
+	rrelNum = /^([\-+])=([\-+.\de]+)/,
+
+	cssShow = { position: "absolute", visibility: "hidden", display: "block" },
+	cssWidth = [ "Left", "Right" ],
+	cssHeight = [ "Top", "Bottom" ],
+	curCSS,
+
+	getComputedStyle,
+	currentStyle;
+
+jQuery.fn.css = function( name, value ) {
+	// Setting 'undefined' is a no-op
+	if ( arguments.length === 2 && value === undefined ) {
+		return this;
+	}
+
+	return jQuery.access( this, name, value, true, function( elem, name, value ) {
+		return value !== undefined ?
+			jQuery.style( elem, name, value ) :
+			jQuery.css( elem, name );
+	});
+};
+
+jQuery.extend({
+	// Add in style property hooks for overriding the default
+	// behavior of getting and setting a style property
+	cssHooks: {
+		opacity: {
+			get: function( elem, computed ) {
+				if ( computed ) {
+					// We should always get a number back from opacity
+					var ret = curCSS( elem, "opacity", "opacity" );
+					return ret === "" ? "1" : ret;
+
+				} else {
+					return elem.style.opacity;
+				}
+			}
+		}
+	},
+
+	// Exclude the following css properties to add px
+	cssNumber: {
+		"fillOpacity": true,
+		"fontWeight": true,
+		"lineHeight": true,
+		"opacity": true,
+		"orphans": true,
+		"widows": true,
+		"zIndex": true,
+		"zoom": true
+	},
+
+	// Add in properties whose names you wish to fix before
+	// setting or getting the value
+	cssProps: {
+		// normalize float css property
+		"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
+	},
+
+	// Get and set the style property on a DOM Node
+	style: function( elem, name, value, extra ) {
+		// Don't set styles on text and comment nodes
+		if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
+			return;
+		}
+
+		// Make sure that we're working with the right name
+		var ret, type, origName = jQuery.camelCase( name ),
+			style = elem.style, hooks = jQuery.cssHooks[ origName ];
+
+		name = jQuery.cssProps[ origName ] || origName;
+
+		// Check if we're setting a value
+		if ( value !== undefined ) {
+			type = typeof value;
+
+			// convert relative number strings (+= or -=) to relative numbers. #7345
+			if ( type === "string" && (ret = rrelNum.exec( value )) ) {
+				value = ( +( ret[1] + 1) * +ret[2] ) + parseFloat( jQuery.css( elem, name ) );
+				// Fixes bug #9237
+				type = "number";
+			}
+
+			// Make sure that NaN and null values aren't set. See: #7116
+			if ( value == null || type === "number" && isNaN( value ) ) {
+				return;
+			}
+
+			// If a number was passed in, add 'px' to the (except for certain CSS properties)
+			if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
+				value += "px";
+			}
+
+			// If a hook was provided, use that value, otherwise just set the specified value
+			if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) {
+				// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
+				// Fixes bug #5509
+				try {
+					style[ name ] = value;
+				} catch(e) {}
+			}
+
+		} else {
+			// If a hook was provided get the non-computed value from there
+			if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
+				return ret;
+			}
+
+			// Otherwise just get the value from the style object
+			return style[ name ];
+		}
+	},
+
+	css: function( elem, name, extra ) {
+		var ret, hooks;
+
+		// Make sure that we're working with the right name
+		name = jQuery.camelCase( name );
+		hooks = jQuery.cssHooks[ name ];
+		name = jQuery.cssProps[ name ] || name;
+
+		// cssFloat needs a special treatment
+		if ( name === "cssFloat" ) {
+			name = "float";
+		}
+
+		// If a hook was provided get the computed value from there
+		if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) {
+			return ret;
+
+		// Otherwise, if a way to get the computed value exists, use that
+		} else if ( curCSS ) {
+			return curCSS( elem, name );
+		}
+	},
+
+	// A method for quickly swapping in/out CSS properties to get correct calculations
+	swap: function( elem, options, callback ) {
+		var old = {};
+
+		// Remember the old values, and insert the new ones
+		for ( var name in options ) {
+			old[ name ] = elem.style[ name ];
+			elem.style[ name ] = options[ name ];
+		}
+
+		callback.call( elem );
+
+		// Revert the old values
+		for ( name in options ) {
+			elem.style[ name ] = old[ name ];
+		}
+	}
+});
+
+// DEPRECATED, Use jQuery.css() instead
+jQuery.curCSS = jQuery.css;
+
+jQuery.each(["height", "width"], function( i, name ) {
+	jQuery.cssHooks[ name ] = {
+		get: function( elem, computed, extra ) {
+			var val;
+
+			if ( computed ) {
+				if ( elem.offsetWidth !== 0 ) {
+					return getWH( elem, name, extra );
+				} else {
+					jQuery.swap( elem, cssShow, function() {
+						val = getWH( elem, name, extra );
+					});
+				}
+
+				return val;
+			}
+		},
+
+		set: function( elem, value ) {
+			if ( rnumpx.test( value ) ) {
+				// ignore negative width and height values #1599
+				value = parseFloat( value );
+
+				if ( value >= 0 ) {
+					return value + "px";
+				}
+
+			} else {
+				return value;
+			}
+		}
+	};
+});
+
+if ( !jQuery.support.opacity ) {
+	jQuery.cssHooks.opacity = {
+		get: function( elem, computed ) {
+			// IE uses filters for opacity
+			return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
+				( parseFloat( RegExp.$1 ) / 100 ) + "" :
+				computed ? "1" : "";
+		},
+
+		set: function( elem, value ) {
+			var style = elem.style,
+				currentStyle = elem.currentStyle,
+				opacity = jQuery.isNaN( value ) ? "" : "alpha(opacity=" + value * 100 + ")",
+				filter = currentStyle && currentStyle.filter || style.filter || "";
+
+			// IE has trouble with opacity if it does not have layout
+			// Force it by setting the zoom level
+			style.zoom = 1;
+
+			// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
+			if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" ) {
+
+				// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
+				// if "filter:" is present at all, clearType is disabled, we want to avoid this
+				// style.removeAttribute is IE Only, but so apparently is this code path...
+				style.removeAttribute( "filter" );
+
+				// if there there is no filter style applied in a css rule, we are done
+				if ( currentStyle && !currentStyle.filter ) {
+					return;
+				}
+			}
+
+			// otherwise, set new filter values
+			style.filter = ralpha.test( filter ) ?
+				filter.replace( ralpha, opacity ) :
+				filter + " " + opacity;
+		}
+	};
+}
+
+jQuery(function() {
+	// This hook cannot be added until DOM ready because the support test
+	// for it is not run until after DOM ready
+	if ( !jQuery.support.reliableMarginRight ) {
+		jQuery.cssHooks.marginRight = {
+			get: function( elem, computed ) {
+				// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
+				// Work around by temporarily setting element display to inline-block
+				var ret;
+				jQuery.swap( elem, { "display": "inline-block" }, function() {
+					if ( computed ) {
+						ret = curCSS( elem, "margin-right", "marginRight" );
+					} else {
+						ret = elem.style.marginRight;
+					}
+				});
+				return ret;
+			}
+		};
+	}
+});
+
+if ( document.defaultView && document.defaultView.getComputedStyle ) {
+	getComputedStyle = function( elem, name ) {
+		var ret, defaultView, computedStyle;
+
+		name = name.replace( rupper, "-$1" ).toLowerCase();
+
+		if ( !(defaultView = elem.ownerDocument.defaultView) ) {
+			return undefined;
+		}
+
+		if ( (computedStyle = defaultView.getComputedStyle( elem, null )) ) {
+			ret = computedStyle.getPropertyValue( name );
+			if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
+				ret = jQuery.style( elem, name );
+			}
+		}
+
+		return ret;
+	};
+}
+
+if ( document.documentElement.currentStyle ) {
+	currentStyle = function( elem, name ) {
+		var left,
+			ret = elem.currentStyle && elem.currentStyle[ name ],
+			rsLeft = elem.runtimeStyle && elem.runtimeStyle[ name ],
+			style = elem.style;
+
+		// From the awesome hack by Dean Edwards
+		// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
+
+		// If we're not dealing with a regular pixel number
+		// but a number that has a weird ending, we need to convert it to pixels
+		if ( !rnumpx.test( ret ) && rnum.test( ret ) ) {
+			// Remember the original values
+			left = style.left;
+
+			// Put in the new values to get a computed value out
+			if ( rsLeft ) {
+				elem.runtimeStyle.left = elem.currentStyle.left;
+			}
+			style.left = name === "fontSize" ? "1em" : (ret || 0);
+			ret = style.pixelLeft + "px";
+
+			// Revert the changed values
+			style.left = left;
+			if ( rsLeft ) {
+				elem.runtimeStyle.left = rsLeft;
+			}
+		}
+
+		return ret === "" ? "auto" : ret;
+	};
+}
+
+curCSS = getComputedStyle || currentStyle;
+
+function getWH( elem, name, extra ) {
+
+	// Start with offset property
+	var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
+		which = name === "width" ? cssWidth : cssHeight;
+
+	if ( val > 0 ) {
+		if ( extra !== "border" ) {
+			jQuery.each( which, function() {
+				if ( !extra ) {
+					val -= parseFloat( jQuery.css( elem, "padding" + this ) ) || 0;
+				}
+				if ( extra === "margin" ) {
+					val += parseFloat( jQuery.css( elem, extra + this ) ) || 0;
+				} else {
+					val -= parseFloat( jQuery.css( elem, "border" + this + "Width" ) ) || 0;
+				}
+			});
+		}
+
+		return val + "px";
+	}
+
+	// Fall back to computed then uncomputed css if necessary
+	val = curCSS( elem, name, name );
+	if ( val < 0 || val == null ) {
+		val = elem.style[ name ] || 0;
+	}
+	// Normalize "", auto, and prepare for extra
+	val = parseFloat( val ) || 0;
+
+	// Add padding, border, margin
+	if ( extra ) {
+		jQuery.each( which, function() {
+			val += parseFloat( jQuery.css( elem, "padding" + this ) ) || 0;
+			if ( extra !== "padding" ) {
+				val += parseFloat( jQuery.css( elem, "border" + this + "Width" ) ) || 0;
+			}
+			if ( extra === "margin" ) {
+				val += parseFloat( jQuery.css( elem, extra + this ) ) || 0;
+			}
+		});
+	}
+
+	return val + "px";
+}
+
+if ( jQuery.expr && jQuery.expr.filters ) {
+	jQuery.expr.filters.hidden = function( elem ) {
+		var width = elem.offsetWidth,
+			height = elem.offsetHeight;
+
+		return (width === 0 && height === 0) || (!jQuery.support.reliableHiddenOffsets && (elem.style.display || jQuery.css( elem, "display" )) === "none");
+	};
+
+	jQuery.expr.filters.visible = function( elem ) {
+		return !jQuery.expr.filters.hidden( elem );
+	};
+}
+
+
+
+
+var r20 = /%20/g,
+	rbracket = /\[\]$/,
+	rCRLF = /\r?\n/g,
+	rhash = /#.*$/,
+	rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
+	rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
+	// #7653, #8125, #8152: local protocol detection
+	rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,
+	rnoContent = /^(?:GET|HEAD)$/,
+	rprotocol = /^\/\//,
+	rquery = /\?/,
+	rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
+	rselectTextarea = /^(?:select|textarea)/i,
+	rspacesAjax = /\s+/,
+	rts = /([?&])_=[^&]*/,
+	rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,
+
+	// Keep a copy of the old load method
+	_load = jQuery.fn.load,
+
+	/* Prefilters
+	 * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
+	 * 2) These are called:
+	 *    - BEFORE asking for a transport
+	 *    - AFTER param serialization (s.data is a string if s.processData is true)
+	 * 3) key is the dataType
+	 * 4) the catchall symbol "*" can be used
+	 * 5) execution will start with transport dataType and THEN continue down to "*" if needed
+	 */
+	prefilters = {},
+
+	/* Transports bindings
+	 * 1) key is the dataType
+	 * 2) the catchall symbol "*" can be used
+	 * 3) selection will start with transport dataType and THEN go to "*" if needed
+	 */
+	transports = {},
+
+	// Document location
+	ajaxLocation,
+
+	// Document location segments
+	ajaxLocParts,
+	
+	// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
+	allTypes = ["*/"] + ["*"];
+
+// #8138, IE may throw an exception when accessing
+// a field from window.location if document.domain has been set
+try {
+	ajaxLocation = location.href;
+} catch( e ) {
+	// Use the href attribute of an A element
+	// since IE will modify it given document.location
+	ajaxLocation = document.createElement( "a" );
+	ajaxLocation.href = "";
+	ajaxLocation = ajaxLocation.href;
+}
+
+// Segment location into parts
+ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
+
+// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
+function addToPrefiltersOrTransports( structure ) {
+
+	// dataTypeExpression is optional and defaults to "*"
+	return function( dataTypeExpression, func ) {
+
+		if ( typeof dataTypeExpression !== "string" ) {
+			func = dataTypeExpression;
+			dataTypeExpression = "*";
+		}
+
+		if ( jQuery.isFunction( func ) ) {
+			var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ),
+				i = 0,
+				length = dataTypes.length,
+				dataType,
+				list,
+				placeBefore;
+
+			// For each dataType in the dataTypeExpression
+			for(; i < length; i++ ) {
+				dataType = dataTypes[ i ];
+				// We control if we're asked to add before
+				// any existing element
+				placeBefore = /^\+/.test( dataType );
+				if ( placeBefore ) {
+					dataType = dataType.substr( 1 ) || "*";
+				}
+				list = structure[ dataType ] = structure[ dataType ] || [];
+				// then we add to the structure accordingly
+				list[ placeBefore ? "unshift" : "push" ]( func );
+			}
+		}
+	};
+}
+
+// Base inspection function for prefilters and transports
+function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
+		dataType /* internal */, inspected /* internal */ ) {
+
+	dataType = dataType || options.dataTypes[ 0 ];
+	inspected = inspected || {};
+
+	inspected[ dataType ] = true;
+
+	var list = structure[ dataType ],
+		i = 0,
+		length = list ? list.length : 0,
+		executeOnly = ( structure === prefilters ),
+		selection;
+
+	for(; i < length && ( executeOnly || !selection ); i++ ) {
+		selection = list[ i ]( options, originalOptions, jqXHR );
+		// If we got redirected to another dataType
+		// we try there if executing only and not done already
+		if ( typeof selection === "string" ) {
+			if ( !executeOnly || inspected[ selection ] ) {
+				selection = undefined;
+			} else {
+				options.dataTypes.unshift( selection );
+				selection = inspectPrefiltersOrTransports(
+						structure, options, originalOptions, jqXHR, selection, inspected );
+			}
+		}
+	}
+	// If we're only executing or nothing was selected
+	// we try the catchall dataType if not done already
+	if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
+		selection = inspectPrefiltersOrTransports(
+				structure, options, originalOptions, jqXHR, "*", inspected );
+	}
+	// unnecessary when only executing (prefilters)
+	// but it'll be ignored by the caller in that case
+	return selection;
+}
+
+// A special extend for ajax options
+// that takes "flat" options (not to be deep extended)
+// Fixes #9887
+function ajaxExtend( target, src ) {
+	var key, deep,
+		flatOptions = jQuery.ajaxSettings.flatOptions || {};
+	for( key in src ) {
+		if ( src[ key ] !== undefined ) {
+			( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
+		}
+	}
+	if ( deep ) {
+		jQuery.extend( true, target, deep );
+	}
+}
+
+jQuery.fn.extend({
+	load: function( url, params, callback ) {
+		if ( typeof url !== "string" && _load ) {
+			return _load.apply( this, arguments );
+
+		// Don't do a request if no elements are being requested
+		} else if ( !this.length ) {
+			return this;
+		}
+
+		var off = url.indexOf( " " );
+		if ( off >= 0 ) {
+			var selector = url.slice( off, url.length );
+			url = url.slice( 0, off );
+		}
+
+		// Default to a GET request
+		var type = "GET";
+
+		// If the second parameter was provided
+		if ( params ) {
+			// If it's a function
+			if ( jQuery.isFunction( params ) ) {
+				// We assume that it's the callback
+				callback = params;
+				params = undefined;
+
+			// Otherwise, build a param string
+			} else if ( typeof params === "object" ) {
+				params = jQuery.param( params, jQuery.ajaxSettings.traditional );
+				type = "POST";
+			}
+		}
+
+		var self = this;
+
+		// Request the remote document
+		jQuery.ajax({
+			url: url,
+			type: type,
+			dataType: "html",
+			data: params,
+			// Complete callback (responseText is used internally)
+			complete: function( jqXHR, status, responseText ) {
+				// Store the response as specified by the jqXHR object
+				responseText = jqXHR.responseText;
+				// If successful, inject the HTML into all the matched elements
+				if ( jqXHR.isResolved() ) {
+					// #4825: Get the actual response in case
+					// a dataFilter is present in ajaxSettings
+					jqXHR.done(function( r ) {
+						responseText = r;
+					});
+					// See if a selector was specified
+					self.html( selector ?
+						// Create a dummy div to hold the results
+						jQuery("<div>")
+							// inject the contents of the document in, removing the scripts
+							// to avoid any 'Permission Denied' errors in IE
+							.append(responseText.replace(rscript, ""))
+
+							// Locate the specified elements
+							.find(selector) :
+
+						// If not, just inject the full result
+						responseText );
+				}
+
+				if ( callback ) {
+					self.each( callback, [ responseText, status, jqXHR ] );
+				}
+			}
+		});
+
+		return this;
+	},
+
+	serialize: function() {
+		return jQuery.param( this.serializeArray() );
+	},
+
+	serializeArray: function() {
+		return this.map(function(){
+			return this.elements ? jQuery.makeArray( this.elements ) : this;
+		})
+		.filter(function(){
+			return this.name && !this.disabled &&
+				( this.checked || rselectTextarea.test( this.nodeName ) ||
+					rinput.test( this.type ) );
+		})
+		.map(function( i, elem ){
+			var val = jQuery( this ).val();
+
+			return val == null ?
+				null :
+				jQuery.isArray( val ) ?
+					jQuery.map( val, function( val, i ){
+						return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
+					}) :
+					{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
+		}).get();
+	}
+});
+
+// Attach a bunch of functions for handling common AJAX events
+jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
+	jQuery.fn[ o ] = function( f ){
+		return this.bind( o, f );
+	};
+});
+
+jQuery.each( [ "get", "post" ], function( i, method ) {
+	jQuery[ method ] = function( url, data, callback, type ) {
+		// shift arguments if data argument was omitted
+		if ( jQuery.isFunction( data ) ) {
+			type = type || callback;
+			callback = data;
+			data = undefined;
+		}
+
+		return jQuery.ajax({
+			type: method,
+			url: url,
+			data: data,
+			success: callback,
+			dataType: type
+		});
+	};
+});
+
+jQuery.extend({
+
+	getScript: function( url, callback ) {
+		return jQuery.get( url, undefined, callback, "script" );
+	},
+
+	getJSON: function( url, data, callback ) {
+		return jQuery.get( url, data, callback, "json" );
+	},
+
+	// Creates a full fledged settings object into target
+	// with both ajaxSettings and settings fields.
+	// If target is omitted, writes into ajaxSettings.
+	ajaxSetup: function( target, settings ) {
+		if ( settings ) {
+			// Building a settings object
+			ajaxExtend( target, jQuery.ajaxSettings );
+		} else {
+			// Extending ajaxSettings
+			settings = target;
+			target = jQuery.ajaxSettings;
+		}
+		ajaxExtend( target, settings );
+		return target;
+	},
+
+	ajaxSettings: {
+		url: ajaxLocation,
+		isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
+		global: true,
+		type: "GET",
+		contentType: "application/x-www-form-urlencoded",
+		processData: true,
+		async: true,
+		/*
+		timeout: 0,
+		data: null,
+		dataType: null,
+		username: null,
+		password: null,
+		cache: null,
+		traditional: false,
+		headers: {},
+		*/
+
+		accepts: {
+			xml: "application/xml, text/xml",
+			html: "text/html",
+			text: "text/plain",
+			json: "application/json, text/javascript",
+			"*": allTypes
+		},
+
+		contents: {
+			xml: /xml/,
+			html: /html/,
+			json: /json/
+		},
+
+		responseFields: {
+			xml: "responseXML",
+			text: "responseText"
+		},
+
+		// List of data converters
+		// 1) key format is "source_type destination_type" (a single space in-between)
+		// 2) the catchall symbol "*" can be used for source_type
+		converters: {
+
+			// Convert anything to text
+			"* text": window.String,
+
+			// Text to html (true = no transformation)
+			"text html": true,
+
+			// Evaluate text as a json expression
+			"text json": jQuery.parseJSON,
+
+			// Parse text as xml
+			"text xml": jQuery.parseXML
+		},
+
+		// For options that shouldn't be deep extended:
+		// you can add your own custom options here if
+		// and when you create one that shouldn't be
+		// deep extended (see ajaxExtend)
+		flatOptions: {
+			context: true,
+			url: true
+		}
+	},
+
+	ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
+	ajaxTransport: addToPrefiltersOrTransports( transports ),
+
+	// Main method
+	ajax: function( url, options ) {
+
+		// If url is an object, simulate pre-1.5 signature
+		if ( typeof url === "object" ) {
+			options = url;
+			url = undefined;
+		}
+
+		// Force options to be an object
+		options = options || {};
+
+		var // Create the final options object
+			s = jQuery.ajaxSetup( {}, options ),
+			// Callbacks context
+			callbackContext = s.context || s,
+			// Context for global events
+			// It's the callbackContext if one was provided in the options
+			// and if it's a DOM node or a jQuery collection
+			globalEventContext = callbackContext !== s &&
+				( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
+						jQuery( callbackContext ) : jQuery.event,
+			// Deferreds
+			deferred = jQuery.Deferred(),
+			completeDeferred = jQuery._Deferred(),
+			// Status-dependent callbacks
+			statusCode = s.statusCode || {},
+			// ifModified key
+			ifModifiedKey,
+			// Headers (they are sent all at once)
+			requestHeaders = {},
+			requestHeadersNames = {},
+			// Response headers
+			responseHeadersString,
+			responseHeaders,
+			// transport
+			transport,
+			// timeout handle
+			timeoutTimer,
+			// Cross-domain detection vars
+			parts,
+			// The jqXHR state
+			state = 0,
+			// To know if global events are to be dispatched
+			fireGlobals,
+			// Loop variable
+			i,
+			// Fake xhr
+			jqXHR = {
+
+				readyState: 0,
+
+				// Caches the header
+				setRequestHeader: function( name, value ) {
+					if ( !state ) {
+						var lname = name.toLowerCase();
+						name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
+						requestHeaders[ name ] = value;
+					}
+					return this;
+				},
+
+				// Raw string
+				getAllResponseHeaders: function() {
+					return state === 2 ? responseHeadersString : null;
+				},
+
+				// Builds headers hashtable if needed
+				getResponseHeader: function( key ) {
+					var match;
+					if ( state === 2 ) {
+						if ( !responseHeaders ) {
+							responseHeaders = {};
+							while( ( match = rheaders.exec( responseHeadersString ) ) ) {
+								responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
+							}
+						}
+						match = responseHeaders[ key.toLowerCase() ];
+					}
+					return match === undefined ? null : match;
+				},
+
+				// Overrides response content-type header
+				overrideMimeType: function( type ) {
+					if ( !state ) {
+						s.mimeType = type;
+					}
+					return this;
+				},
+
+				// Cancel the request
+				abort: function( statusText ) {
+					statusText = statusText || "abort";
+					if ( transport ) {
+						transport.abort( statusText );
+					}
+					done( 0, statusText );
+					return this;
+				}
+			};
+
+		// Callback for when everything is done
+		// It is defined here because jslint complains if it is declared
+		// at the end of the function (which would be more logical and readable)
+		function done( status, nativeStatusText, responses, headers ) {
+
+			// Called once
+			if ( state === 2 ) {
+				return;
+			}
+
+			// State is "done" now
+			state = 2;
+
+			// Clear timeout if it exists
+			if ( timeoutTimer ) {
+				clearTimeout( timeoutTimer );
+			}
+
+			// Dereference transport for early garbage collection
+			// (no matter how long the jqXHR object will be used)
+			transport = undefined;
+
+			// Cache response headers
+			responseHeadersString = headers || "";
+
+			// Set readyState
+			jqXHR.readyState = status > 0 ? 4 : 0;
+
+			var isSuccess,
+				success,
+				error,
+				statusText = nativeStatusText,
+				response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined,
+				lastModified,
+				etag;
+
+			// If successful, handle type chaining
+			if ( status >= 200 && status < 300 || status === 304 ) {
+
+				// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
+				if ( s.ifModified ) {
+
+					if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) {
+						jQuery.lastModified[ ifModifiedKey ] = lastModified;
+					}
+					if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) {
+						jQuery.etag[ ifModifiedKey ] = etag;
+					}
+				}
+
+				// If not modified
+				if ( status === 304 ) {
+
+					statusText = "notmodified";
+					isSuccess = true;
+
+				// If we have data
+				} else {
+
+					try {
+						success = ajaxConvert( s, response );
+						statusText = "success";
+						isSuccess = true;
+					} catch(e) {
+						// We have a parsererror
+						statusText = "parsererror";
+						error = e;
+					}
+				}
+			} else {
+				// We extract error from statusText
+				// then normalize statusText and status for non-aborts
+				error = statusText;
+				if( !statusText || status ) {
+					statusText = "error";
+					if ( status < 0 ) {
+						status = 0;
+					}
+				}
+			}
+
+			// Set data for the fake xhr object
+			jqXHR.status = status;
+			jqXHR.statusText = "" + ( nativeStatusText || statusText );
+
+			// Success/Error
+			if ( isSuccess ) {
+				deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
+			} else {
+				deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
+			}
+
+			// Status-dependent callbacks
+			jqXHR.statusCode( statusCode );
+			statusCode = undefined;
+
+			if ( fireGlobals ) {
+				globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
+						[ jqXHR, s, isSuccess ? success : error ] );
+			}
+
+			// Complete
+			completeDeferred.resolveWith( callbackContext, [ jqXHR, statusText ] );
+
+			if ( fireGlobals ) {
+				globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
+				// Handle the global AJAX counter
+				if ( !( --jQuery.active ) ) {
+					jQuery.event.trigger( "ajaxStop" );
+				}
+			}
+		}
+
+		// Attach deferreds
+		deferred.promise( jqXHR );
+		jqXHR.success = jqXHR.done;
+		jqXHR.error = jqXHR.fail;
+		jqXHR.complete = completeDeferred.done;
+
+		// Status-dependent callbacks
+		jqXHR.statusCode = function( map ) {
+			if ( map ) {
+				var tmp;
+				if ( state < 2 ) {
+					for( tmp in map ) {
+						statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
+					}
+				} else {
+					tmp = map[ jqXHR.status ];
+					jqXHR.then( tmp, tmp );
+				}
+			}
+			return this;
+		};
+
+		// Remove hash character (#7531: and string promotion)
+		// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
+		// We also use the url parameter if available
+		s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
+
+		// Extract dataTypes list
+		s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
+
+		// Determine if a cross-domain request is in order
+		if ( s.crossDomain == null ) {
+			parts = rurl.exec( s.url.toLowerCase() );
+			s.crossDomain = !!( parts &&
+				( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] ||
+					( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
+						( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
+			);
+		}
+
+		// Convert data if not already a string
+		if ( s.data && s.processData && typeof s.data !== "string" ) {
+			s.data = jQuery.param( s.data, s.traditional );
+		}
+
+		// Apply prefilters
+		inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
+
+		// If request was aborted inside a prefiler, stop there
+		if ( state === 2 ) {
+			return false;
+		}
+
+		// We can fire global events as of now if asked to
+		fireGlobals = s.global;
+
+		// Uppercase the type
+		s.type = s.type.toUpperCase();
+
+		// Determine if request has content
+		s.hasContent = !rnoContent.test( s.type );
+
+		// Watch for a new set of requests
+		if ( fireGlobals && jQuery.active++ === 0 ) {
+			jQuery.event.trigger( "ajaxStart" );
+		}
+
+		// More options handling for requests with no content
+		if ( !s.hasContent ) {
+
+			// If data is available, append data to url
+			if ( s.data ) {
+				s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
+				// #9682: remove data so that it's not used in an eventual retry
+				delete s.data;
+			}
+
+			// Get ifModifiedKey before adding the anti-cache parameter
+			ifModifiedKey = s.url;
+
+			// Add anti-cache in url if needed
+			if ( s.cache === false ) {
+
+				var ts = jQuery.now(),
+					// try replacing _= if it is there
+					ret = s.url.replace( rts, "$1_=" + ts );
+
+				// if nothing was replaced, add timestamp to the end
+				s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
+			}
+		}
+
+		// Set the correct header, if data is being sent
+		if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
+			jqXHR.setRequestHeader( "Content-Type", s.contentType );
+		}
+
+		// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
+		if ( s.ifModified ) {
+			ifModifiedKey = ifModifiedKey || s.url;
+			if ( jQuery.lastModified[ ifModifiedKey ] ) {
+				jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] );
+			}
+			if ( jQuery.etag[ ifModifiedKey ] ) {
+				jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] );
+			}
+		}
+
+		// Set the Accepts header for the server, depending on the dataType
+		jqXHR.setRequestHeader(
+			"Accept",
+			s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
+				s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
+				s.accepts[ "*" ]
+		);
+
+		// Check for headers option
+		for ( i in s.headers ) {
+			jqXHR.setRequestHeader( i, s.headers[ i ] );
+		}
+
+		// Allow custom headers/mimetypes and early abort
+		if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
+				// Abort if not done already
+				jqXHR.abort();
+				return false;
+
+		}
+
+		// Install callbacks on deferreds
+		for ( i in { success: 1, error: 1, complete: 1 } ) {
+			jqXHR[ i ]( s[ i ] );
+		}
+
+		// Get transport
+		transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
+
+		// If no transport, we auto-abort
+		if ( !transport ) {
+			done( -1, "No Transport" );
+		} else {
+			jqXHR.readyState = 1;
+			// Send global event
+			if ( fireGlobals ) {
+				globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
+			}
+			// Timeout
+			if ( s.async && s.timeout > 0 ) {
+				timeoutTimer = setTimeout( function(){
+					jqXHR.abort( "timeout" );
+				}, s.timeout );
+			}
+
+			try {
+				state = 1;
+				transport.send( requestHeaders, done );
+			} catch (e) {
+				// Propagate exception as error if not done
+				if ( state < 2 ) {
+					done( -1, e );
+				// Simply rethrow otherwise
+				} else {
+					jQuery.error( e );
+				}
+			}
+		}
+
+		return jqXHR;
+	},
+
+	// Serialize an array of form elements or a set of
+	// key/values into a query string
+	param: function( a, traditional ) {
+		var s = [],
+			add = function( key, value ) {
+				// If value is a function, invoke it and return its value
+				value = jQuery.isFunction( value ) ? value() : value;
+				s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
+			};
+
+		// Set traditional to true for jQuery <= 1.3.2 behavior.
+		if ( traditional === undefined ) {
+			traditional = jQuery.ajaxSettings.traditional;
+		}
+
+		// If an array was passed in, assume that it is an array of form elements.
+		if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
+			// Serialize the form elements
+			jQuery.each( a, function() {
+				add( this.name, this.value );
+			});
+
+		} else {
+			// If traditional, encode the "old" way (the way 1.3.2 or older
+			// did it), otherwise encode params recursively.
+			for ( var prefix in a ) {
+				buildParams( prefix, a[ prefix ], traditional, add );
+			}
+		}
+
+		// Return the resulting serialization
+		return s.join( "&" ).replace( r20, "+" );
+	}
+});
+
+function buildParams( prefix, obj, traditional, add ) {
+	if ( jQuery.isArray( obj ) ) {
+		// Serialize array item.
+		jQuery.each( obj, function( i, v ) {
+			if ( traditional || rbracket.test( prefix ) ) {
+				// Treat each array item as a scalar.
+				add( prefix, v );
+
+			} else {
+				// If array item is non-scalar (array or object), encode its
+				// numeric index to resolve deserialization ambiguity issues.
+				// Note that rack (as of 1.0.0) can't currently deserialize
+				// nested arrays properly, and attempting to do so may cause
+				// a server error. Possible fixes are to modify rack's
+				// deserialization algorithm or to provide an option or flag
+				// to force array serialization to be shallow.
+				buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
+			}
+		});
+
+	} else if ( !traditional && obj != null && typeof obj === "object" ) {
+		// Serialize object item.
+		for ( var name in obj ) {
+			buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
+		}
+
+	} else {
+		// Serialize scalar item.
+		add( prefix, obj );
+	}
+}
+
+// This is still on the jQuery object... for now
+// Want to move this to jQuery.ajax some day
+jQuery.extend({
+
+	// Counter for holding the number of active queries
+	active: 0,
+
+	// Last-Modified header cache for next request
+	lastModified: {},
+	etag: {}
+
+});
+
+/* Handles responses to an ajax request:
+ * - sets all responseXXX fields accordingly
+ * - finds the right dataType (mediates between content-type and expected dataType)
+ * - returns the corresponding response
+ */
+function ajaxHandleResponses( s, jqXHR, responses ) {
+
+	var contents = s.contents,
+		dataTypes = s.dataTypes,
+		responseFields = s.responseFields,
+		ct,
+		type,
+		finalDataType,
+		firstDataType;
+
+	// Fill responseXXX fields
+	for( type in responseFields ) {
+		if ( type in responses ) {
+			jqXHR[ responseFields[type] ] = responses[ type ];
+		}
+	}
+
+	// Remove auto dataType and get content-type in the process
+	while( dataTypes[ 0 ] === "*" ) {
+		dataTypes.shift();
+		if ( ct === undefined ) {
+			ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
+		}
+	}
+
+	// Check if we're dealing with a known content-type
+	if ( ct ) {
+		for ( type in contents ) {
+			if ( contents[ type ] && contents[ type ].test( ct ) ) {
+				dataTypes.unshift( type );
+				break;
+			}
+		}
+	}
+
+	// Check to see if we have a response for the expected dataType
+	if ( dataTypes[ 0 ] in responses ) {
+		finalDataType = dataTypes[ 0 ];
+	} else {
+		// Try convertible dataTypes
+		for ( type in responses ) {
+			if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
+				finalDataType = type;
+				break;
+			}
+			if ( !firstDataType ) {
+				firstDataType = type;
+			}
+		}
+		// Or just use first one
+		finalDataType = finalDataType || firstDataType;
+	}
+
+	// If we found a dataType
+	// We add the dataType to the list if needed
+	// and return the corresponding response
+	if ( finalDataType ) {
+		if ( finalDataType !== dataTypes[ 0 ] ) {
+			dataTypes.unshift( finalDataType );
+		}
+		return responses[ finalDataType ];
+	}
+}
+
+// Chain conversions given the request and the original response
+function ajaxConvert( s, response ) {
+
+	// Apply the dataFilter if provided
+	if ( s.dataFilter ) {
+		response = s.dataFilter( response, s.dataType );
+	}
+
+	var dataTypes = s.dataTypes,
+		converters = {},
+		i,
+		key,
+		length = dataTypes.length,
+		tmp,
+		// Current and previous dataTypes
+		current = dataTypes[ 0 ],
+		prev,
+		// Conversion expression
+		conversion,
+		// Conversion function
+		conv,
+		// Conversion functions (transitive conversion)
+		conv1,
+		conv2;
+
+	// For each dataType in the chain
+	for( i = 1; i < length; i++ ) {
+
+		// Create converters map
+		// with lowercased keys
+		if ( i === 1 ) {
+			for( key in s.converters ) {
+				if( typeof key === "string" ) {
+					converters[ key.toLowerCase() ] = s.converters[ key ];
+				}
+			}
+		}
+
+		// Get the dataTypes
+		prev = current;
+		current = dataTypes[ i ];
+
+		// If current is auto dataType, update it to prev
+		if( current === "*" ) {
+			current = prev;
+		// If no auto and dataTypes are actually different
+		} else if ( prev !== "*" && prev !== current ) {
+
+			// Get the converter
+			conversion = prev + " " + current;
+			conv = converters[ conversion ] || converters[ "* " + current ];
+
+			// If there is no direct converter, search transitively
+			if ( !conv ) {
+				conv2 = undefined;
+				for( conv1 in converters ) {
+					tmp = conv1.split( " " );
+					if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
+						conv2 = converters[ tmp[1] + " " + current ];
+						if ( conv2 ) {
+							conv1 = converters[ conv1 ];
+							if ( conv1 === true ) {
+								conv = conv2;
+							} else if ( conv2 === true ) {
+								conv = conv1;
+							}
+							break;
+						}
+					}
+				}
+			}
+			// If we found no converter, dispatch an error
+			if ( !( conv || conv2 ) ) {
+				jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
+			}
+			// If found converter is not an equivalence
+			if ( conv !== true ) {
+				// Convert with 1 or 2 converters accordingly
+				response = conv ? conv( response ) : conv2( conv1(response) );
+			}
+		}
+	}
+	return response;
+}
+
+
+
+
+var jsc = jQuery.now(),
+	jsre = /(\=)\?(&|$)|\?\?/i;
+
+// Default jsonp settings
+jQuery.ajaxSetup({
+	jsonp: "callback",
+	jsonpCallback: function() {
+		return jQuery.expando + "_" + ( jsc++ );
+	}
+});
+
+// Detect, normalize options and install callbacks for jsonp requests
+jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
+
+	var inspectData = s.contentType === "application/x-www-form-urlencoded" &&
+		( typeof s.data === "string" );
+
+	if ( s.dataTypes[ 0 ] === "jsonp" ||
+		s.jsonp !== false && ( jsre.test( s.url ) ||
+				inspectData && jsre.test( s.data ) ) ) {
+
+		var responseContainer,
+			jsonpCallback = s.jsonpCallback =
+				jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback,
+			previous = window[ jsonpCallback ],
+			url = s.url,
+			data = s.data,
+			replace = "$1" + jsonpCallback + "$2";
+
+		if ( s.jsonp !== false ) {
+			url = url.replace( jsre, replace );
+			if ( s.url === url ) {
+				if ( inspectData ) {
+					data = data.replace( jsre, replace );
+				}
+				if ( s.data === data ) {
+					// Add callback manually
+					url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback;
+				}
+			}
+		}
+
+		s.url = url;
+		s.data = data;
+
+		// Install callback
+		window[ jsonpCallback ] = function( response ) {
+			responseContainer = [ response ];
+		};
+
+		// Clean-up function
+		jqXHR.always(function() {
+			// Set callback back to previous value
+			window[ jsonpCallback ] = previous;
+			// Call if it was a function and we have a response
+			if ( responseContainer && jQuery.isFunction( previous ) ) {
+				window[ jsonpCallback ]( responseContainer[ 0 ] );
+			}
+		});
+
+		// Use data converter to retrieve json after script execution
+		s.converters["script json"] = function() {
+			if ( !responseContainer ) {
+				jQuery.error( jsonpCallback + " was not called" );
+			}
+			return responseContainer[ 0 ];
+		};
+
+		// force json dataType
+		s.dataTypes[ 0 ] = "json";
+
+		// Delegate to script
+		return "script";
+	}
+});
+
+
+
+
+// Install script dataType
+jQuery.ajaxSetup({
+	accepts: {
+		script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
+	},
+	contents: {
+		script: /javascript|ecmascript/
+	},
+	converters: {
+		"text script": function( text ) {
+			jQuery.globalEval( text );
+			return text;
+		}
+	}
+});
+
+// Handle cache's special case and global
+jQuery.ajaxPrefilter( "script", function( s ) {
+	if ( s.cache === undefined ) {
+		s.cache = false;
+	}
+	if ( s.crossDomain ) {
+		s.type = "GET";
+		s.global = false;
+	}
+});
+
+// Bind script tag hack transport
+jQuery.ajaxTransport( "script", function(s) {
+
+	// This transport only deals with cross domain requests
+	if ( s.crossDomain ) {
+
+		var script,
+			head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;
+
+		return {
+
+			send: function( _, callback ) {
+
+				script = document.createElement( "script" );
+
+				script.async = "async";
+
+				if ( s.scriptCharset ) {
+					script.charset = s.scriptCharset;
+				}
+
+				script.src = s.url;
+
+				// Attach handlers for all browsers
+				script.onload = script.onreadystatechange = function( _, isAbort ) {
+
+					if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
+
+						// Handle memory leak in IE
+						script.onload = script.onreadystatechange = null;
+
+						// Remove the script
+						if ( head && script.parentNode ) {
+							head.removeChild( script );
+						}
+
+						// Dereference the script
+						script = undefined;
+
+						// Callback if not abort
+						if ( !isAbort ) {
+							callback( 200, "success" );
+						}
+					}
+				};
+				// Use insertBefore instead of appendChild  to circumvent an IE6 bug.
+				// This arises when a base node is used (#2709 and #4378).
+				head.insertBefore( script, head.firstChild );
+			},
+
+			abort: function() {
+				if ( script ) {
+					script.onload( 0, 1 );
+				}
+			}
+		};
+	}
+});
+
+
+
+
+var // #5280: Internet Explorer will keep connections alive if we don't abort on unload
+	xhrOnUnloadAbort = window.ActiveXObject ? function() {
+		// Abort all pending requests
+		for ( var key in xhrCallbacks ) {
+			xhrCallbacks[ key ]( 0, 1 );
+		}
+	} : false,
+	xhrId = 0,
+	xhrCallbacks;
+
+// Functions to create xhrs
+function createStandardXHR() {
+	try {
+		return new window.XMLHttpRequest();
+	} catch( e ) {}
+}
+
+function createActiveXHR() {
+	try {
+		return new window.ActiveXObject( "Microsoft.XMLHTTP" );
+	} catch( e ) {}
+}
+
+// Create the request object
+// (This is still attached to ajaxSettings for backward compatibility)
+jQuery.ajaxSettings.xhr = window.ActiveXObject ?
+	/* Microsoft failed to properly
+	 * implement the XMLHttpRequest in IE7 (can't request local files),
+	 * so we use the ActiveXObject when it is available
+	 * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
+	 * we need a fallback.
+	 */
+	function() {
+		return !this.isLocal && createStandardXHR() || createActiveXHR();
+	} :
+	// For all other browsers, use the standard XMLHttpRequest object
+	createStandardXHR;
+
+// Determine support properties
+(function( xhr ) {
+	jQuery.extend( jQuery.support, {
+		ajax: !!xhr,
+		cors: !!xhr && ( "withCredentials" in xhr )
+	});
+})( jQuery.ajaxSettings.xhr() );
+
+// Create transport if the browser can provide an xhr
+if ( jQuery.support.ajax ) {
+
+	jQuery.ajaxTransport(function( s ) {
+		// Cross domain only allowed if supported through XMLHttpRequest
+		if ( !s.crossDomain || jQuery.support.cors ) {
+
+			var callback;
+
+			return {
+				send: function( headers, complete ) {
+
+					// Get a new xhr
+					var xhr = s.xhr(),
+						handle,
+						i;
+
+					// Open the socket
+					// Passing null username, generates a login popup on Opera (#2865)
+					if ( s.username ) {
+						xhr.open( s.type, s.url, s.async, s.username, s.password );
+					} else {
+						xhr.open( s.type, s.url, s.async );
+					}
+
+					// Apply custom fields if provided
+					if ( s.xhrFields ) {
+						for ( i in s.xhrFields ) {
+							xhr[ i ] = s.xhrFields[ i ];
+						}
+					}
+
+					// Override mime type if needed
+					if ( s.mimeType && xhr.overrideMimeType ) {
+						xhr.overrideMimeType( s.mimeType );
+					}
+
+					// X-Requested-With header
+					// For cross-domain requests, seeing as conditions for a preflight are
+					// akin to a jigsaw puzzle, we simply never set it to be sure.
+					// (it can always be set on a per-request basis or even using ajaxSetup)
+					// For same-domain requests, won't change header if already provided.
+					if ( !s.crossDomain && !headers["X-Requested-With"] ) {
+						headers[ "X-Requested-With" ] = "XMLHttpRequest";
+					}
+
+					// Need an extra try/catch for cross domain requests in Firefox 3
+					try {
+						for ( i in headers ) {
+							xhr.setRequestHeader( i, headers[ i ] );
+						}
+					} catch( _ ) {}
+
+					// Do send the request
+					// This may raise an exception which is actually
+					// handled in jQuery.ajax (so no try/catch here)
+					xhr.send( ( s.hasContent && s.data ) || null );
+
+					// Listener
+					callback = function( _, isAbort ) {
+
+						var status,
+							statusText,
+							responseHeaders,
+							responses,
+							xml;
+
+						// Firefox throws exceptions when accessing properties
+						// of an xhr when a network error occured
+						// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
+						try {
+
+							// Was never called and is aborted or complete
+							if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
+
+								// Only called once
+								callback = undefined;
+
+								// Do not keep as active anymore
+								if ( handle ) {
+									xhr.onreadystatechange = jQuery.noop;
+									if ( xhrOnUnloadAbort ) {
+										delete xhrCallbacks[ handle ];
+									}
+								}
+
+								// If it's an abort
+								if ( isAbort ) {
+									// Abort it manually if needed
+									if ( xhr.readyState !== 4 ) {
+										xhr.abort();
+									}
+								} else {
+									status = xhr.status;
+									responseHeaders = xhr.getAllResponseHeaders();
+									responses = {};
+									xml = xhr.responseXML;
+
+									// Construct response list
+									if ( xml && xml.documentElement /* #4958 */ ) {
+										responses.xml = xml;
+									}
+									responses.text = xhr.responseText;
+
+									// Firefox throws an exception when accessing
+									// statusText for faulty cross-domain requests
+									try {
+										statusText = xhr.statusText;
+									} catch( e ) {
+										// We normalize with Webkit giving an empty statusText
+										statusText = "";
+									}
+
+									// Filter status for non standard behaviors
+
+									// If the request is local and we have data: assume a success
+									// (success with no data won't get notified, that's the best we
+									// can do given current implementations)
+									if ( !status && s.isLocal && !s.crossDomain ) {
+										status = responses.text ? 200 : 404;
+									// IE - #1450: sometimes returns 1223 when it should be 204
+									} else if ( status === 1223 ) {
+										status = 204;
+									}
+								}
+							}
+						} catch( firefoxAccessException ) {
+							if ( !isAbort ) {
+								complete( -1, firefoxAccessException );
+							}
+						}
+
+						// Call complete if needed
+						if ( responses ) {
+							complete( status, statusText, responses, responseHeaders );
+						}
+					};
+
+					// if we're in sync mode or it's in cache
+					// and has been retrieved directly (IE6 & IE7)
+					// we need to manually fire the callback
+					if ( !s.async || xhr.readyState === 4 ) {
+						callback();
+					} else {
+						handle = ++xhrId;
+						if ( xhrOnUnloadAbort ) {
+							// Create the active xhrs callbacks list if needed
+							// and attach the unload handler
+							if ( !xhrCallbacks ) {
+								xhrCallbacks = {};
+								jQuery( window ).unload( xhrOnUnloadAbort );
+							}
+							// Add to list of active xhrs callbacks
+							xhrCallbacks[ handle ] = callback;
+						}
+						xhr.onreadystatechange = callback;
+					}
+				},
+
+				abort: function() {
+					if ( callback ) {
+						callback(0,1);
+					}
+				}
+			};
+		}
+	});
+}
+
+
+
+
+var elemdisplay = {},
+	iframe, iframeDoc,
+	rfxtypes = /^(?:toggle|show|hide)$/,
+	rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,
+	timerId,
+	fxAttrs = [
+		// height animations
+		[ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
+		// width animations
+		[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
+		// opacity animations
+		[ "opacity" ]
+	],
+	fxNow;
+
+jQuery.fn.extend({
+	show: function( speed, easing, callback ) {
+		var elem, display;
+
+		if ( speed || speed === 0 ) {
+			return this.animate( genFx("show", 3), speed, easing, callback);
+
+		} else {
+			for ( var i = 0, j = this.length; i < j; i++ ) {
+				elem = this[i];
+
+				if ( elem.style ) {
+					display = elem.style.display;
+
+					// Reset the inline display of this element to learn if it is
+					// being hidden by cascaded rules or not
+					if ( !jQuery._data(elem, "olddisplay") && display === "none" ) {
+						display = elem.style.display = "";
+					}
+
+					// Set elements which have been overridden with display: none
+					// in a stylesheet to whatever the default browser style is
+					// for such an element
+					if ( display === "" && jQuery.css( elem, "display" ) === "none" ) {
+						jQuery._data(elem, "olddisplay", defaultDisplay(elem.nodeName));
+					}
+				}
+			}
+
+			// Set the display of most of the elements in a second loop
+			// to avoid the constant reflow
+			for ( i = 0; i < j; i++ ) {
+				elem = this[i];
+
+				if ( elem.style ) {
+					display = elem.style.display;
+
+					if ( display === "" || display === "none" ) {
+						elem.style.display = jQuery._data(elem, "olddisplay") || "";
+					}
+				}
+			}
+
+			return this;
+		}
+	},
+
+	hide: function( speed, easing, callback ) {
+		if ( speed || speed === 0 ) {
+			return this.animate( genFx("hide", 3), speed, easing, callback);
+
+		} else {
+			for ( var i = 0, j = this.length; i < j; i++ ) {
+				if ( this[i].style ) {
+					var display = jQuery.css( this[i], "display" );
+
+					if ( display !== "none" && !jQuery._data( this[i], "olddisplay" ) ) {
+						jQuery._data( this[i], "olddisplay", display );
+					}
+				}
+			}
+
+			// Set the display of the elements in a second loop
+			// to avoid the constant reflow
+			for ( i = 0; i < j; i++ ) {
+				if ( this[i].style ) {
+					this[i].style.display = "none";
+				}
+			}
+
+			return this;
+		}
+	},
+
+	// Save the old toggle function
+	_toggle: jQuery.fn.toggle,
+
+	toggle: function( fn, fn2, callback ) {
+		var bool = typeof fn === "boolean";
+
+		if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) {
+			this._toggle.apply( this, arguments );
+
+		} else if ( fn == null || bool ) {
+			this.each(function() {
+				var state = bool ? fn : jQuery(this).is(":hidden");
+				jQuery(this)[ state ? "show" : "hide" ]();
+			});
+
+		} else {
+			this.animate(genFx("toggle", 3), fn, fn2, callback);
+		}
+
+		return this;
+	},
+
+	fadeTo: function( speed, to, easing, callback ) {
+		return this.filter(":hidden").css("opacity", 0).show().end()
+					.animate({opacity: to}, speed, easing, callback);
+	},
+
+	animate: function( prop, speed, easing, callback ) {
+		var optall = jQuery.speed(speed, easing, callback);
+
+		if ( jQuery.isEmptyObject( prop ) ) {
+			return this.each( optall.complete, [ false ] );
+		}
+
+		// Do not change referenced properties as per-property easing will be lost
+		prop = jQuery.extend( {}, prop );
+
+		return this[ optall.queue === false ? "each" : "queue" ](function() {
+			// XXX 'this' does not always have a nodeName when running the
+			// test suite
+
+			if ( optall.queue === false ) {
+				jQuery._mark( this );
+			}
+
+			var opt = jQuery.extend( {}, optall ),
+				isElement = this.nodeType === 1,
+				hidden = isElement && jQuery(this).is(":hidden"),
+				name, val, p,
+				display, e,
+				parts, start, end, unit;
+
+			// will store per property easing and be used to determine when an animation is complete
+			opt.animatedProperties = {};
+
+			for ( p in prop ) {
+
+				// property name normalization
+				name = jQuery.camelCase( p );
+				if ( p !== name ) {
+					prop[ name ] = prop[ p ];
+					delete prop[ p ];
+				}
+
+				val = prop[ name ];
+
+				// easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default)
+				if ( jQuery.isArray( val ) ) {
+					opt.animatedProperties[ name ] = val[ 1 ];
+					val = prop[ name ] = val[ 0 ];
+				} else {
+					opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing';
+				}
+
+				if ( val === "hide" && hidden || val === "show" && !hidden ) {
+					return opt.complete.call( this );
+				}
+
+				if ( isElement && ( name === "height" || name === "width" ) ) {
+					// Make sure that nothing sneaks out
+					// Record all 3 overflow attributes because IE does not
+					// change the overflow attribute when overflowX and
+					// overflowY are set to the same value
+					opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ];
+
+					// Set display property to inline-block for height/width
+					// animations on inline elements that are having width/height
+					// animated
+					if ( jQuery.css( this, "display" ) === "inline" &&
+							jQuery.css( this, "float" ) === "none" ) {
+						if ( !jQuery.support.inlineBlockNeedsLayout ) {
+							this.style.display = "inline-block";
+
+						} else {
+							display = defaultDisplay( this.nodeName );
+
+							// inline-level elements accept inline-block;
+							// block-level elements need to be inline with layout
+							if ( display === "inline" ) {
+								this.style.display = "inline-block";
+
+							} else {
+								this.style.display = "inline";
+								this.style.zoom = 1;
+							}
+						}
+					}
+				}
+			}
+
+			if ( opt.overflow != null ) {
+				this.style.overflow = "hidden";
+			}
+
+			for ( p in prop ) {
+				e = new jQuery.fx( this, opt, p );
+				val = prop[ p ];
+
+				if ( rfxtypes.test(val) ) {
+					e[ val === "toggle" ? hidden ? "show" : "hide" : val ]();
+
+				} else {
+					parts = rfxnum.exec( val );
+					start = e.cur();
+
+					if ( parts ) {
+						end = parseFloat( parts[2] );
+						unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" );
+
+						// We need to compute starting value
+						if ( unit !== "px" ) {
+							jQuery.style( this, p, (end || 1) + unit);
+							start = ((end || 1) / e.cur()) * start;
+							jQuery.style( this, p, start + unit);
+						}
+
+						// If a +=/-= token was provided, we're doing a relative animation
+						if ( parts[1] ) {
+							end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start;
+						}
+
+						e.custom( start, end, unit );
+
+					} else {
+						e.custom( start, val, "" );
+					}
+				}
+			}
+
+			// For JS strict compliance
+			return true;
+		});
+	},
+
+	stop: function( clearQueue, gotoEnd ) {
+		if ( clearQueue ) {
+			this.queue([]);
+		}
+
+		this.each(function() {
+			var timers = jQuery.timers,
+				i = timers.length;
+			// clear marker counters if we know they won't be
+			if ( !gotoEnd ) {
+				jQuery._unmark( true, this );
+			}
+			while ( i-- ) {
+				if ( timers[i].elem === this ) {
+					if (gotoEnd) {
+						// force the next step to be the last
+						timers[i](true);
+					}
+
+					timers.splice(i, 1);
+				}
+			}
+		});
+
+		// start the next in the queue if the last step wasn't forced
+		if ( !gotoEnd ) {
+			this.dequeue();
+		}
+
+		return this;
+	}
+
+});
+
+// Animations created synchronously will run synchronously
+function createFxNow() {
+	setTimeout( clearFxNow, 0 );
+	return ( fxNow = jQuery.now() );
+}
+
+function clearFxNow() {
+	fxNow = undefined;
+}
+
+// Generate parameters to create a standard animation
+function genFx( type, num ) {
+	var obj = {};
+
+	jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function() {
+		obj[ this ] = type;
+	});
+
+	return obj;
+}
+
+// Generate shortcuts for custom animations
+jQuery.each({
+	slideDown: genFx("show", 1),
+	slideUp: genFx("hide", 1),
+	slideToggle: genFx("toggle", 1),
+	fadeIn: { opacity: "show" },
+	fadeOut: { opacity: "hide" },
+	fadeToggle: { opacity: "toggle" }
+}, function( name, props ) {
+	jQuery.fn[ name ] = function( speed, easing, callback ) {
+		return this.animate( props, speed, easing, callback );
+	};
+});
+
+jQuery.extend({
+	speed: function( speed, easing, fn ) {
+		var opt = speed && typeof speed === "object" ? jQuery.extend({}, speed) : {
+			complete: fn || !fn && easing ||
+				jQuery.isFunction( speed ) && speed,
+			duration: speed,
+			easing: fn && easing || easing && !jQuery.isFunction(easing) && easing
+		};
+
+		opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
+			opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[opt.duration] : jQuery.fx.speeds._default;
+
+		// Queueing
+		opt.old = opt.complete;
+		opt.complete = function( noUnmark ) {
+			if ( jQuery.isFunction( opt.old ) ) {
+				opt.old.call( this );
+			}
+
+			if ( opt.queue !== false ) {
+				jQuery.dequeue( this );
+			} else if ( noUnmark !== false ) {
+				jQuery._unmark( this );
+			}
+		};
+
+		return opt;
+	},
+
+	easing: {
+		linear: function( p, n, firstNum, diff ) {
+			return firstNum + diff * p;
+		},
+		swing: function( p, n, firstNum, diff ) {
+			return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum;
+		}
+	},
+
+	timers: [],
+
+	fx: function( elem, options, prop ) {
+		this.options = options;
+		this.elem = elem;
+		this.prop = prop;
+
+		options.orig = options.orig || {};
+	}
+
+});
+
+jQuery.fx.prototype = {
+	// Simple function for setting a style value
+	update: function() {
+		if ( this.options.step ) {
+			this.options.step.call( this.elem, this.now, this );
+		}
+
+		(jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this );
+	},
+
+	// Get the current size
+	cur: function() {
+		if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) {
+			return this.elem[ this.prop ];
+		}
+
+		var parsed,
+			r = jQuery.css( this.elem, this.prop );
+		// Empty strings, null, undefined and "auto" are converted to 0,
+		// complex values such as "rotate(1rad)" are returned as is,
+		// simple values such as "10px" are parsed to Float.
+		return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed;
+	},
+
+	// Start an animation from one number to another
+	custom: function( from, to, unit ) {
+		var self = this,
+			fx = jQuery.fx;
+
+		this.startTime = fxNow || createFxNow();
+		this.start = from;
+		this.end = to;
+		this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" );
+		this.now = this.start;
+		this.pos = this.state = 0;
+
+		function t( gotoEnd ) {
+			return self.step(gotoEnd);
+		}
+
+		t.elem = this.elem;
+
+		if ( t() && jQuery.timers.push(t) && !timerId ) {
+			timerId = setInterval( fx.tick, fx.interval );
+		}
+	},
+
+	// Simple 'show' function
+	show: function() {
+		// Remember where we started, so that we can go back to it later
+		this.options.orig[this.prop] = jQuery.style( this.elem, this.prop );
+		this.options.show = true;
+
+		// Begin the animation
+		// Make sure that we start at a small width/height to avoid any
+		// flash of content
+		this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur());
+
+		// Start by showing the element
+		jQuery( this.elem ).show();
+	},
+
+	// Simple 'hide' function
+	hide: function() {
+		// Remember where we started, so that we can go back to it later
+		this.options.orig[this.prop] = jQuery.style( this.elem, this.prop );
+		this.options.hide = true;
+
+		// Begin the animation
+		this.custom(this.cur(), 0);
+	},
+
+	// Each step of an animation
+	step: function( gotoEnd ) {
+		var t = fxNow || createFxNow(),
+			done = true,
+			elem = this.elem,
+			options = this.options,
+			i, n;
+
+		if ( gotoEnd || t >= options.duration + this.startTime ) {
+			this.now = this.end;
+			this.pos = this.state = 1;
+			this.update();
+
+			options.animatedProperties[ this.prop ] = true;
+
+			for ( i in options.animatedProperties ) {
+				if ( options.animatedProperties[i] !== true ) {
+					done = false;
+				}
+			}
+
+			if ( done ) {
+				// Reset the overflow
+				if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) {
+
+					jQuery.each( [ "", "X", "Y" ], function (index, value) {
+						elem.style[ "overflow" + value ] = options.overflow[index];
+					});
+				}
+
+				// Hide the element if the "hide" operation was done
+				if ( options.hide ) {
+					jQuery(elem).hide();
+				}
+
+				// Reset the properties, if the item has been hidden or shown
+				if ( options.hide || options.show ) {
+					for ( var p in options.animatedProperties ) {
+						jQuery.style( elem, p, options.orig[p] );
+					}
+				}
+
+				// Execute the complete function
+				options.complete.call( elem );
+			}
+
+			return false;
+
+		} else {
+			// classical easing cannot be used with an Infinity duration
+			if ( options.duration == Infinity ) {
+				this.now = t;
+			} else {
+				n = t - this.startTime;
+				this.state = n / options.duration;
+
+				// Perform the easing function, defaults to swing
+				this.pos = jQuery.easing[ options.animatedProperties[ this.prop ] ]( this.state, n, 0, 1, options.duration );
+				this.now = this.start + ((this.end - this.start) * this.pos);
+			}
+			// Perform the next step of the animation
+			this.update();
+		}
+
+		return true;
+	}
+};
+
+jQuery.extend( jQuery.fx, {
+	tick: function() {
+		for ( var timers = jQuery.timers, i = 0 ; i < timers.length ; ++i ) {
+			if ( !timers[i]() ) {
+				timers.splice(i--, 1);
+			}
+		}
+
+		if ( !timers.length ) {
+			jQuery.fx.stop();
+		}
+	},
+
+	interval: 13,
+
+	stop: function() {
+		clearInterval( timerId );
+		timerId = null;
+	},
+
+	speeds: {
+		slow: 600,
+		fast: 200,
+		// Default speed
+		_default: 400
+	},
+
+	step: {
+		opacity: function( fx ) {
+			jQuery.style( fx.elem, "opacity", fx.now );
+		},
+
+		_default: function( fx ) {
+			if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) {
+				fx.elem.style[ fx.prop ] = (fx.prop === "width" || fx.prop === "height" ? Math.max(0, fx.now) : fx.now) + fx.unit;
+			} else {
+				fx.elem[ fx.prop ] = fx.now;
+			}
+		}
+	}
+});
+
+if ( jQuery.expr && jQuery.expr.filters ) {
+	jQuery.expr.filters.animated = function( elem ) {
+		return jQuery.grep(jQuery.timers, function( fn ) {
+			return elem === fn.elem;
+		}).length;
+	};
+}
+
+// Try to restore the default display value of an element
+function defaultDisplay( nodeName ) {
+
+	if ( !elemdisplay[ nodeName ] ) {
+
+		var body = document.body,
+			elem = jQuery( "<" + nodeName + ">" ).appendTo( body ),
+			display = elem.css( "display" );
+
+		elem.remove();
+
+		// If the simple way fails,
+		// get element's real default display by attaching it to a temp iframe
+		if ( display === "none" || display === "" ) {
+			// No iframe to use yet, so create it
+			if ( !iframe ) {
+				iframe = document.createElement( "iframe" );
+				iframe.frameBorder = iframe.width = iframe.height = 0;
+			}
+
+			body.appendChild( iframe );
+
+			// Create a cacheable copy of the iframe document on first call.
+			// IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML
+			// document to it; WebKit & Firefox won't allow reusing the iframe document.
+			if ( !iframeDoc || !iframe.createElement ) {
+				iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;
+				iframeDoc.write( ( document.compatMode === "CSS1Compat" ? "<!doctype html>" : "" ) + "<html><body>" );
+				iframeDoc.close();
+			}
+
+			elem = iframeDoc.createElement( nodeName );
+
+			iframeDoc.body.appendChild( elem );
+
+			display = jQuery.css( elem, "display" );
+
+			body.removeChild( iframe );
+		}
+
+		// Store the correct default display
+		elemdisplay[ nodeName ] = display;
+	}
+
+	return elemdisplay[ nodeName ];
+}
+
+
+
+
+var rtable = /^t(?:able|d|h)$/i,
+	rroot = /^(?:body|html)$/i;
+
+if ( "getBoundingClientRect" in document.documentElement ) {
+	jQuery.fn.offset = function( options ) {
+		var elem = this[0], box;
+
+		if ( options ) {
+			return this.each(function( i ) {
+				jQuery.offset.setOffset( this, options, i );
+			});
+		}
+
+		if ( !elem || !elem.ownerDocument ) {
+			return null;
+		}
+
+		if ( elem === elem.ownerDocument.body ) {
+			return jQuery.offset.bodyOffset( elem );
+		}
+
+		try {
+			box = elem.getBoundingClientRect();
+		} catch(e) {}
+
+		var doc = elem.ownerDocument,
+			docElem = doc.documentElement;
+
+		// Make sure we're not dealing with a disconnected DOM node
+		if ( !box || !jQuery.contains( docElem, elem ) ) {
+			return box ? { top: box.top, left: box.left } : { top: 0, left: 0 };
+		}
+
+		var body = doc.body,
+			win = getWindow(doc),
+			clientTop  = docElem.clientTop  || body.clientTop  || 0,
+			clientLeft = docElem.clientLeft || body.clientLeft || 0,
+			scrollTop  = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop  || body.scrollTop,
+			scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft,
+			top  = box.top  + scrollTop  - clientTop,
+			left = box.left + scrollLeft - clientLeft;
+
+		return { top: top, left: left };
+	};
+
+} else {
+	jQuery.fn.offset = function( options ) {
+		var elem = this[0];
+
+		if ( options ) {
+			return this.each(function( i ) {
+				jQuery.offset.setOffset( this, options, i );
+			});
+		}
+
+		if ( !elem || !elem.ownerDocument ) {
+			return null;
+		}
+
+		if ( elem === elem.ownerDocument.body ) {
+			return jQuery.offset.bodyOffset( elem );
+		}
+
+		jQuery.offset.initialize();
+
+		var computedStyle,
+			offsetParent = elem.offsetParent,
+			prevOffsetParent = elem,
+			doc = elem.ownerDocument,
+			docElem = doc.documentElement,
+			body = doc.body,
+			defaultView = doc.defaultView,
+			prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle,
+			top = elem.offsetTop,
+			left = elem.offsetLeft;
+
+		while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
+			if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) {
+				break;
+			}
+
+			computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle;
+			top  -= elem.scrollTop;
+			left -= elem.scrollLeft;
+
+			if ( elem === offsetParent ) {
+				top  += elem.offsetTop;
+				left += elem.offsetLeft;
+
+				if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) {
+					top  += parseFloat( computedStyle.borderTopWidth  ) || 0;
+					left += parseFloat( computedStyle.borderLeftWidth ) || 0;
+				}
+
+				prevOffsetParent = offsetParent;
+				offsetParent = elem.offsetParent;
+			}
+
+			if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) {
+				top  += parseFloat( computedStyle.borderTopWidth  ) || 0;
+				left += parseFloat( computedStyle.borderLeftWidth ) || 0;
+			}
+
+			prevComputedStyle = computedStyle;
+		}
+
+		if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) {
+			top  += body.offsetTop;
+			left += body.offsetLeft;
+		}
+
+		if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) {
+			top  += Math.max( docElem.scrollTop, body.scrollTop );
+			left += Math.max( docElem.scrollLeft, body.scrollLeft );
+		}
+
+		return { top: top, left: left };
+	};
+}
+
+jQuery.offset = {
+	initialize: function() {
+		var body = document.body, container = document.createElement("div"), innerDiv, checkDiv, table, td, bodyMarginTop = parseFloat( jQuery.css(body, "marginTop") ) || 0,
+			html = "<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";
+
+		jQuery.extend( container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" } );
+
+		container.innerHTML = html;
+		body.insertBefore( container, body.firstChild );
+		innerDiv = container.firstChild;
+		checkDiv = innerDiv.firstChild;
+		td = innerDiv.nextSibling.firstChild.firstChild;
+
+		this.doesNotAddBorder = (checkDiv.offsetTop !== 5);
+		this.doesAddBorderForTableAndCells = (td.offsetTop === 5);
+
+		checkDiv.style.position = "fixed";
+		checkDiv.style.top = "20px";
+
+		// safari subtracts parent border width here which is 5px
+		this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15);
+		checkDiv.style.position = checkDiv.style.top = "";
+
+		innerDiv.style.overflow = "hidden";
+		innerDiv.style.position = "relative";
+
+		this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5);
+
+		this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop);
+
+		body.removeChild( container );
+		jQuery.offset.initialize = jQuery.noop;
+	},
+
+	bodyOffset: function( body ) {
+		var top = body.offsetTop,
+			left = body.offsetLeft;
+
+		jQuery.offset.initialize();
+
+		if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) {
+			top  += parseFloat( jQuery.css(body, "marginTop") ) || 0;
+			left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
+		}
+
+		return { top: top, left: left };
+	},
+
+	setOffset: function( elem, options, i ) {
+		var position = jQuery.css( elem, "position" );
+
+		// set position first, in-case top/left are set even on static elem
+		if ( position === "static" ) {
+			elem.style.position = "relative";
+		}
+
+		var curElem = jQuery( elem ),
+			curOffset = curElem.offset(),
+			curCSSTop = jQuery.css( elem, "top" ),
+			curCSSLeft = jQuery.css( elem, "left" ),
+			calculatePosition = (position === "absolute" || position === "fixed") && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
+			props = {}, curPosition = {}, curTop, curLeft;
+
+		// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
+		if ( calculatePosition ) {
+			curPosition = curElem.position();
+			curTop = curPosition.top;
+			curLeft = curPosition.left;
+		} else {
+			curTop = parseFloat( curCSSTop ) || 0;
+			curLeft = parseFloat( curCSSLeft ) || 0;
+		}
+
+		if ( jQuery.isFunction( options ) ) {
+			options = options.call( elem, i, curOffset );
+		}
+
+		if (options.top != null) {
+			props.top = (options.top - curOffset.top) + curTop;
+		}
+		if (options.left != null) {
+			props.left = (options.left - curOffset.left) + curLeft;
+		}
+
+		if ( "using" in options ) {
+			options.using.call( elem, props );
+		} else {
+			curElem.css( props );
+		}
+	}
+};
+
+
+jQuery.fn.extend({
+	position: function() {
+		if ( !this[0] ) {
+			return null;
+		}
+
+		var elem = this[0],
+
+		// Get *real* offsetParent
+		offsetParent = this.offsetParent(),
+
+		// Get correct offsets
+		offset       = this.offset(),
+		parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
+
+		// Subtract element margins
+		// note: when an element has margin: auto the offsetLeft and marginLeft
+		// are the same in Safari causing offset.left to incorrectly be 0
+		offset.top  -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
+		offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;
+
+		// Add offsetParent borders
+		parentOffset.top  += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
+		parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;
+
+		// Subtract the two offsets
+		return {
+			top:  offset.top  - parentOffset.top,
+			left: offset.left - parentOffset.left
+		};
+	},
+
+	offsetParent: function() {
+		return this.map(function() {
+			var offsetParent = this.offsetParent || document.body;
+			while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
+				offsetParent = offsetParent.offsetParent;
+			}
+			return offsetParent;
+		});
+	}
+});
+
+
+// Create scrollLeft and scrollTop methods
+jQuery.each( ["Left", "Top"], function( i, name ) {
+	var method = "scroll" + name;
+
+	jQuery.fn[ method ] = function( val ) {
+		var elem, win;
+
+		if ( val === undefined ) {
+			elem = this[ 0 ];
+
+			if ( !elem ) {
+				return null;
+			}
+
+			win = getWindow( elem );
+
+			// Return the scroll offset
+			return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] :
+				jQuery.support.boxModel && win.document.documentElement[ method ] ||
+					win.document.body[ method ] :
+				elem[ method ];
+		}
+
+		// Set the scroll offset
+		return this.each(function() {
+			win = getWindow( this );
+
+			if ( win ) {
+				win.scrollTo(
+					!i ? val : jQuery( win ).scrollLeft(),
+					 i ? val : jQuery( win ).scrollTop()
+				);
+
+			} else {
+				this[ method ] = val;
+			}
+		});
+	};
+});
+
+function getWindow( elem ) {
+	return jQuery.isWindow( elem ) ?
+		elem :
+		elem.nodeType === 9 ?
+			elem.defaultView || elem.parentWindow :
+			false;
+}
+
+
+
+
+// Create width, height, innerHeight, innerWidth, outerHeight and outerWidth methods
+jQuery.each([ "Height", "Width" ], function( i, name ) {
+
+	var type = name.toLowerCase();
+
+	// innerHeight and innerWidth
+	jQuery.fn[ "inner" + name ] = function() {
+		var elem = this[0];
+		return elem && elem.style ?
+			parseFloat( jQuery.css( elem, type, "padding" ) ) :
+			null;
+	};
+
+	// outerHeight and outerWidth
+	jQuery.fn[ "outer" + name ] = function( margin ) {
+		var elem = this[0];
+		return elem && elem.style ?
+			parseFloat( jQuery.css( elem, type, margin ? "margin" : "border" ) ) :
+			null;
+	};
+
+	jQuery.fn[ type ] = function( size ) {
+		// Get window width or height
+		var elem = this[0];
+		if ( !elem ) {
+			return size == null ? null : this;
+		}
+
+		if ( jQuery.isFunction( size ) ) {
+			return this.each(function( i ) {
+				var self = jQuery( this );
+				self[ type ]( size.call( this, i, self[ type ]() ) );
+			});
+		}
+
+		if ( jQuery.isWindow( elem ) ) {
+			// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
+			// 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
+			var docElemProp = elem.document.documentElement[ "client" + name ],
+				body = elem.document.body;
+			return elem.document.compatMode === "CSS1Compat" && docElemProp ||
+				body && body[ "client" + name ] || docElemProp;
+
+		// Get document width or height
+		} else if ( elem.nodeType === 9 ) {
+			// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
+			return Math.max(
+				elem.documentElement["client" + name],
+				elem.body["scroll" + name], elem.documentElement["scroll" + name],
+				elem.body["offset" + name], elem.documentElement["offset" + name]
+			);
+
+		// Get or set width or height on the element
+		} else if ( size === undefined ) {
+			var orig = jQuery.css( elem, type ),
+				ret = parseFloat( orig );
+
+			return jQuery.isNaN( ret ) ? orig : ret;
+
+		// Set the width or height on the element (default to pixels if value is unitless)
+		} else {
+			return this.css( type, typeof size === "string" ? size : size + "px" );
+		}
+	};
+
+});
+
+
+// Expose jQuery to the global object
+window.jQuery = window.$ = jQuery;
+})(window);
--- a/web/data/jquery.tablesorter.js	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/data/jquery.tablesorter.js	Fri Oct 14 09:21:45 2011 +0200
@@ -1,876 +1,1031 @@
-/*
- *
- * TableSorter 2.0 - Client-side table sorting with ease!
- * Version 2.0.3
- * @requires jQuery v1.2.3
- *
- * Copyright (c) 2007 Christian Bach
- * Examples and docs at: http://tablesorter.com
- * Dual licensed under the MIT and GPL licenses:
- * http://www.opensource.org/licenses/mit-license.php
- * http://www.gnu.org/licenses/gpl.html
- *
- */
-/**
- *
- * @description Create a sortable table with multi-column sorting capabilitys
- *
- * @example $('table').tablesorter();
- * @desc Create a simple tablesorter interface.
- *
- * @example $('table').tablesorter({ sortList:[[0,0],[1,0]] });
- * @desc Create a tablesorter interface and sort on the first and secound column in ascending order.
- *
- * @example $('table').tablesorter({ headers: { 0: { sorter: false}, 1: {sorter: false} } });
- * @desc Create a tablesorter interface and disableing the first and secound column headers.
- *
- * @example $('table').tablesorter({ 0: {sorter:"integer"}, 1: {sorter:"currency"} });
- * @desc Create a tablesorter interface and set a column parser for the first and secound column.
- *
- *
- * @param Object settings An object literal containing key/value pairs to provide optional settings.
- *
- * @option String cssHeader (optional) 			A string of the class name to be appended to sortable tr elements in the thead of the table.
- * 												Default value: "header"
- *
- * @option String cssAsc (optional) 			A string of the class name to be appended to sortable tr elements in the thead on a ascending sort.
- * 												Default value: "headerSortUp"
- *
- * @option String cssDesc (optional) 			A string of the class name to be appended to sortable tr elements in the thead on a descending sort.
- * 												Default value: "headerSortDown"
- *
- * @option String sortInitialOrder (optional) 	A string of the inital sorting order can be asc or desc.
- * 												Default value: "asc"
- *
- * @option String sortMultisortKey (optional) 	A string of the multi-column sort key.
- * 												Default value: "shiftKey"
- *
- * @option String textExtraction (optional) 	A string of the text-extraction method to use.
- * 												For complex html structures inside td cell set this option to "complex",
- * 												on large tables the complex option can be slow.
- * 												Default value: "simple"
- *
- * @option Object headers (optional) 			An array containing the forces sorting rules.
- * 												This option let's you specify a default sorting rule.
- * 												Default value: null
- *
- * @option Array sortList (optional) 			An array containing the forces sorting rules.
- * 												This option let's you specify a default sorting rule.
- * 												Default value: null
- *
- * @option Array sortForce (optional) 			An array containing forced sorting rules.
- * 												This option let's you specify a default sorting rule, which is prepended to user-selected rules.
- * 												Default value: null
- *
-  * @option Array sortAppend (optional) 			An array containing forced sorting rules.
- * 												This option let's you specify a default sorting rule, which is appended to user-selected rules.
- * 												Default value: null
- *
- * @option Boolean widthFixed (optional) 		Boolean flag indicating if tablesorter should apply fixed widths to the table columns.
- * 												This is usefull when using the pager companion plugin.
- * 												This options requires the dimension jquery plugin.
- * 												Default value: false
- *
- * @option Boolean cancelSelection (optional) 	Boolean flag indicating if tablesorter should cancel selection of the table headers text.
- * 												Default value: true
- *
- * @option Boolean debug (optional) 			Boolean flag indicating if tablesorter should display debuging information usefull for development.
- *
- * @type jQuery
- *
- * @name tablesorter
- *
- * @cat Plugins/Tablesorter
- *
- * @author Christian Bach/christian.bach@polyester.se
- */
-
-var Sortable = {};
-
-(function($) {
-	$.extend({
-		tablesorter: new function() {
-			var parsers = [], widgets = [];
-
-			this.defaults = {
-				cssHeader: "header",
-				cssAsc: "headerSortUp",
-				cssDesc: "headerSortDown",
-				sortInitialOrder: "asc",
-				sortMultiSortKey: "shiftKey",
-				sortForce: null,
-				sortAppend: null,
-				textExtraction: "simple",
-				parsers: {},
-				widgets: [],
-				widgetZebra: {css: ["even","odd"]},
-				headers: {},
-				widthFixed: false,
-				cancelSelection: true,
-				sortList: [],
-				headerList: [],
-				dateFormat: "us",
-				decimal: '.',
-				debug: false
-			};
-
-			/* debuging utils */
-			function benchmark(s,d) {
-				log(s + "," + (new Date().getTime() - d.getTime()) + "ms");
-			}
-
-			this.benchmark = benchmark;
-
-			function log(s) {
-				if (typeof console != "undefined" && typeof console.debug != "undefined") {
-					console.log(s);
-				} else {
-					alert(s);
-				}
-			}
-
-			/* parsers utils */
-			function buildParserCache(table,$headers) {
-
-				if(table.config.debug) { var parsersDebug = ""; }
-
-				var rows = table.tBodies[0].rows;
-
-				if(table.tBodies[0].rows[0]) {
-
-					var list = [], cells = rows[0].cells, l = cells.length;
-
-					for (var i=0;i < l; i++) {
-						var p = false;
-
-						if($.metadata && ($($headers[i]).metadata() && $($headers[i]).metadata().sorter)  ) {
-
-							p = getParserById($($headers[i]).metadata().sorter);
-
-						} else if((table.config.headers[i] && table.config.headers[i].sorter)) {
-
-							p = getParserById(table.config.headers[i].sorter);
-						}
-						if(!p) {
-							p = detectParserForColumn(table,cells[i]);
-						}
-
-						if(table.config.debug) { parsersDebug += "column:" + i + " parser:" +p.id + "\n"; }
-
-						list.push(p);
-					}
-				}
-
-				if(table.config.debug) { log(parsersDebug); }
-
-				return list;
-			};
-
-			function detectParserForColumn(table,node) {
-				var l = parsers.length;
-				for(var i=1; i < l; i++) {
-					if(parsers[i].is($.trim(getElementText(table.config,node)),table,node)) {
-						return parsers[i];
-					}
-				}
-				// 0 is always the generic parser (text)
-				return parsers[0];
-			}
-
-			function getParserById(name) {
-				var l = parsers.length;
-				for(var i=0; i < l; i++) {
-					if(parsers[i].id.toLowerCase() == name.toLowerCase()) {
-						return parsers[i];
-					}
-				}
-				return false;
-			}
-
-			/* utils */
-			function buildCache(table) {
-
-				if(table.config.debug) { var cacheTime = new Date(); }
-
-
-				var totalRows = (table.tBodies[0] && table.tBodies[0].rows.length) || 0,
-					totalCells = (table.tBodies[0].rows[0] && table.tBodies[0].rows[0].cells.length) || 0,
-					parsers = table.config.parsers,
-					cache = {row: [], normalized: []};
-
-					for (var i=0;i < totalRows; ++i) {
-
-						/** Add the table data to main data array */
-						var c = table.tBodies[0].rows[i], cols = [];
-
-						cache.row.push($(c));
-
-						for(var j=0; j < totalCells; ++j) {
-							cols.push(parsers[j].format(getElementText(table.config,c.cells[j]),table,c.cells[j]));
-						}
-
-						cols.push(i); // add position for rowCache
-						cache.normalized.push(cols);
-						cols = null;
-					};
-
-				if(table.config.debug) { benchmark("Building cache for " + totalRows + " rows:", cacheTime); }
-
-				return cache;
-			};
-
-			function getElementText(config,node) {
-
-				if(!node) return "";
-
-				var t = "";
-
-				if(config.textExtraction == "simple") {
-					if(node.childNodes[0] && node.childNodes[0].hasChildNodes()) {
-						t = node.childNodes[0].innerHTML;
-					} else {
-						t = node.innerHTML;
-					}
-				} else {
-					if(typeof(config.textExtraction) == "function") {
-						t = config.textExtraction(node);
-					} else {
-						t = $(node).text();
-					}
-				}
-				return t;
-			}
-
-			function appendToTable(table,cache) {
-
-				if(table.config.debug) {var appendTime = new Date()}
-
-				var c = cache,
-					r = c.row,
-					n= c.normalized,
-					totalRows = n.length,
-					checkCell = (n[0].length-1),
-					tableBody = $(table.tBodies[0]),
-					rows = [];
-
-				for (var i=0;i < totalRows; i++) {
-					rows.push(r[n[i][checkCell]]);
-					if(!table.config.appender) {
-
-						var o = r[n[i][checkCell]];
-						var l = o.length;
-						for(var j=0; j < l; j++) {
-
-							tableBody[0].appendChild(o[j]);
-
-						}
-
-						//tableBody.append(r[n[i][checkCell]]);
-					}
-				}
-
-				if(table.config.appender) {
-
-					table.config.appender(table,rows);
-				}
-
-				rows = null;
-
-				if(table.config.debug) { benchmark("Rebuilt table:", appendTime); }
-
-				//apply table widgets
-				applyWidget(table);
-
-				// trigger sortend
-				setTimeout(function() {
-					$(table).trigger("sortEnd");
-				},0);
-
-			};
-
-			function buildHeaders(table) {
-
-				if(table.config.debug) { var time = new Date(); }
-
-				var meta = ($.metadata) ? true : false, tableHeadersRows = [];
-
-				for(var i = 0; i < table.tHead.rows.length; i++) { tableHeadersRows[i]=0; };
-
-				$tableHeaders = $("thead th",table);
-
-				$tableHeaders.each(function(index) {
-
-					this.count = 0;
-					this.column = index;
-					this.order = formatSortingOrder(table.config.sortInitialOrder);
-
-					if(checkHeaderMetadata(this) || checkHeaderOptions(table,index)) this.sortDisabled = true;
-
-					if(!this.sortDisabled) {
-						$(this).addClass(table.config.cssHeader);
-					}
-
-					// add cell to headerList
-					table.config.headerList[index]= this;
-				});
-
-				if(table.config.debug) { benchmark("Built headers:", time); log($tableHeaders); }
-
-				return $tableHeaders;
-
-			};
-
-		   	function checkCellColSpan(table, rows, row) {
-                var arr = [], r = table.tHead.rows, c = r[row].cells;
-
-				for(var i=0; i < c.length; i++) {
-					var cell = c[i];
-
-					if ( cell.colSpan > 1) {
-						arr = arr.concat(checkCellColSpan(table, headerArr,row++));
-					} else  {
-						if(table.tHead.length == 1 || (cell.rowSpan > 1 || !r[row+1])) {
-							arr.push(cell);
-						}
-						//headerArr[row] = (i+row);
-					}
-				}
-				return arr;
-			};
-
-			function checkHeaderMetadata(cell) {
-				if(($.metadata) && ($(cell).metadata().sorter === false)) { return true; };
-				return false;
-			}
-
-			function checkHeaderOptions(table,i) {
-				if((table.config.headers[i]) && (table.config.headers[i].sorter === false)) { return true; };
-				return false;
-			}
-
-			function applyWidget(table) {
-				var c = table.config.widgets;
-				var l = c.length;
-				for(var i=0; i < l; i++) {
-
-					getWidgetById(c[i]).format(table);
-				}
-
-			}
-
-			function getWidgetById(name) {
-				var l = widgets.length;
-				for(var i=0; i < l; i++) {
-					if(widgets[i].id.toLowerCase() == name.toLowerCase() ) {
-						return widgets[i];
-					}
-				}
-			};
-
-			function formatSortingOrder(v) {
-
-				if(typeof(v) != "Number") {
-					i = (v.toLowerCase() == "desc") ? 1 : 0;
-				} else {
-					i = (v == (0 || 1)) ? v : 0;
-				}
-				return i;
-			}
-
-			function isValueInArray(v, a) {
-				var l = a.length;
-				for(var i=0; i < l; i++) {
-					if(a[i][0] == v) {
-						return true;
-					}
-				}
-				return false;
-			}
-
-			function setHeadersCss(table,$headers, list, css) {
-				// remove all header information
-				$headers.removeClass(css[0]).removeClass(css[1]);
-
-				var h = [];
-				$headers.each(function(offset) {
-						if(!this.sortDisabled) {
-							h[this.column] = $(this);
-						}
-				});
-
-				var l = list.length;
-				for(var i=0; i < l; i++) {
-					h[list[i][0]].addClass(css[list[i][1]]);
-				}
-			}
-
-			function fixColumnWidth(table,$headers) {
-				var c = table.config;
-				if(c.widthFixed) {
-					var colgroup = $('<colgroup>');
-					$("tr:first td",table.tBodies[0]).each(function() {
-						colgroup.append($('<col>').css('width',$(this).width()));
-					});
-					$(table).prepend(colgroup);
-				};
-			}
-
-			function updateHeaderSortCount(table,sortList) {
-				var c = table.config, l = sortList.length;
-				for(var i=0; i < l; i++) {
-					var s = sortList[i], o = c.headerList[s[0]];
-					o.count = s[1];
-					o.count++;
-				}
-			}
-
-			/* sorting methods */
-			function multisort(table,sortList,cache) {
-
-				if(table.config.debug) { var sortTime = new Date(); }
-
-				var dynamicExp = "var sortWrapper = function(a,b) {", l = sortList.length;
-
-				for(var i=0; i < l; i++) {
-
-					var c = sortList[i][0];
-					var order = sortList[i][1];
-					var s = (getCachedSortType(table.config.parsers,c) == "text") ? ((order == 0) ? "sortText" : "sortTextDesc") : ((order == 0) ? "sortNumeric" : "sortNumericDesc");
-					var e = "e" + i;
-					dynamicExp += "var " + e + " = " + s + "(a[" + c + "],b[" + c + "]); ";
-					dynamicExp += "if(" + e + ") { return " + e + "; } ";
-					dynamicExp += "else { ";
-				}
-
-				// if value is the same keep orignal order
-				var orgOrderCol = cache.normalized[0].length - 1;
-				dynamicExp += "return a[" + orgOrderCol + "]-b[" + orgOrderCol + "];";
-
-				for(var i=0; i < l; i++) {
-					dynamicExp += "}; ";
-				}
-
-				dynamicExp += "return 0; ";
-				dynamicExp += "}; ";
-
-				eval(dynamicExp);
-
-				cache.normalized.sort(sortWrapper);
-
-				if(table.config.debug) { benchmark("Sorting on " + sortList.toString() + " and dir " + order+ " time:", sortTime); }
-
-				return cache;
-			};
-
-			function sortText(a,b) {
-				return ((a < b) ? -1 : ((a > b) ? 1 : 0));
-			};
-
-			function sortTextDesc(a,b) {
-				return ((b < a) ? -1 : ((b > a) ? 1 : 0));
-			};
-
-	 		function sortNumeric(a,b) {
-				return a-b;
-			};
-
-			function sortNumericDesc(a,b) {
-				return b-a;
-			};
-
-			function getCachedSortType(parsers,i) {
-				return parsers[i].type;
-			};
-
-			/* public methods */
-			this.construct = function(settings) {
-
-				return this.each(function() {
-
-					if(!this.tHead || !this.tBodies) return;
-
-					var $this, $document,$headers, cache, config, shiftDown = 0, sortOrder;
-
-					this.config = {};
-
-					config = $.extend(this.config, $.tablesorter.defaults, settings);
-
-					// store common expression for speed
-					$this = $(this);
-
-					// build headers
-					$headers = buildHeaders(this);
-
-					// try to auto detect column type, and store in tables config
-					this.config.parsers = buildParserCache(this,$headers);
-
-					// build the cache for the tbody cells
-					cache = buildCache(this);
-
-					// get the css class names, could be done else where.
-					var sortCSS = [config.cssDesc,config.cssAsc];
-
-					// fixate columns if the users supplies the fixedWidth option
-					fixColumnWidth(this);
-
-					// apply event handling to headers
-					// this is to big, perhaps break it out?
-					$headers.click(function(e) {
-
-						$this.trigger("sortStart");
-
-						var totalRows = ($this[0].tBodies[0] && $this[0].tBodies[0].rows.length) || 0;
-
-						if(!this.sortDisabled && totalRows > 0) {
-
-
-							// store exp, for speed
-							var $cell = $(this);
-
-							// get current column index
-							var i = this.column;
-
-							// get current column sort order
-							this.order = this.count++ % 2;
-
-							// user only whants to sort on one column
-							if(!e[config.sortMultiSortKey]) {
-
-								// flush the sort list
-								config.sortList = [];
-
-								if(config.sortForce != null) {
-									var a = config.sortForce;
-									for(var j=0; j < a.length; j++) {
-										if(a[j][0] != i) {
-											config.sortList.push(a[j]);
-										}
-									}
-								}
-
-								// add column to sort list
-								config.sortList.push([i,this.order]);
-
-							// multi column sorting
-							} else {
-								// the user has clicked on an all ready sortet column.
-								if(isValueInArray(i,config.sortList)) {
-
-									// revers the sorting direction for all tables.
-									for(var j=0; j < config.sortList.length; j++) {
-										var s = config.sortList[j], o = config.headerList[s[0]];
-										if(s[0] == i) {
-											o.count = s[1];
-											o.count++;
-											s[1] = o.count % 2;
-										}
-									}
-								} else {
-									// add column to sort list array
-									config.sortList.push([i,this.order]);
-								}
-							};
-							setTimeout(function() {
-								//set css for headers
-								setHeadersCss($this[0],$headers,config.sortList,sortCSS);
-								appendToTable($this[0],multisort($this[0],config.sortList,cache));
-							},1);
-							// stop normal event by returning false
-							return false;
-						}
-					// cancel selection
-					}).mousedown(function() {
-						if(config.cancelSelection) {
-							this.onselectstart = function() {return false};
-							return false;
-						}
-					});
-
-					// apply easy methods that trigger binded events
-					$this.bind("update",function() {
-
-						// rebuild parsers.
-						this.config.parsers = buildParserCache(this,$headers);
-
-						// rebuild the cache map
-						cache = buildCache(this);
-
-					}).bind("sorton",function(e,list) {
-
-						$(this).trigger("sortStart");
-
-						config.sortList = list;
-
-						// update and store the sortlist
-						var sortList = config.sortList;
-
-						// update header count index
-						updateHeaderSortCount(this,sortList);
-
-						//set css for headers
-						setHeadersCss(this,$headers,sortList,sortCSS);
-
-
-						// sort the table and append it to the dom
-						appendToTable(this,multisort(this,sortList,cache));
-
-					}).bind("appendCache",function() {
-
-						appendToTable(this,cache);
-
-					}).bind("applyWidgetId",function(e,id) {
-
-						getWidgetById(id).format(this);
-
-					}).bind("applyWidgets",function() {
-						// apply widgets
-						applyWidget(this);
-					});
-
-					if($.metadata && ($(this).metadata() && $(this).metadata().sortlist)) {
-						config.sortList = $(this).metadata().sortlist;
-					}
-					// if user has supplied a sort list to constructor.
-					if(config.sortList.length > 0) {
-						$this.trigger("sorton",[config.sortList]);
-					}
-
-					// apply widgets
-					applyWidget(this);
-				});
-			};
-
-			this.addParser = function(parser) {
-				var l = parsers.length, a = true;
-				for(var i=0; i < l; i++) {
-					if(parsers[i].id.toLowerCase() == parser.id.toLowerCase()) {
-						a = false;
-					}
-				}
-				if(a) { parsers.push(parser); };
-			};
-
-			this.addWidget = function(widget) {
-				widgets.push(widget);
-			};
-
-			this.formatFloat = function(s) {
-				var i = parseFloat(s);
-				return (isNaN(i)) ? 0 : i;
-			};
-			this.formatInt = function(s) {
-				var i = parseInt(s);
-				return (isNaN(i)) ? 0 : i;
-			};
-
-			this.isDigit = function(s,config) {
-				var DECIMAL = '\\' + config.decimal;
-				var exp = '/(^[+]?0(' + DECIMAL +'0+)?$)|(^([-+]?[1-9][0-9]*)$)|(^([-+]?((0?|[1-9][0-9]*)' + DECIMAL +'(0*[1-9][0-9]*)))$)|(^[-+]?[1-9]+[0-9]*' + DECIMAL +'0+$)/';
-				return RegExp(exp).test($.trim(s));
-			};
-
-			this.clearTableBody = function(table) {
-				if($.browser.msie) {
-					function empty() {
-						while ( this.firstChild ) this.removeChild( this.firstChild );
-					}
-					empty.apply(table.tBodies[0]);
-				} else {
-					table.tBodies[0].innerHTML = "";
-				}
-			};
-		}
-	});
-
-	// extend plugin scope
-	$.fn.extend({
-        tablesorter: $.tablesorter.construct
-	});
-
-	var ts = $.tablesorter;
-
-	// add default parsers
-	ts.addParser({
-		id: "text",
-		is: function(s) {
-			return true;
-		},
-		format: function(s) {
-			return $.trim(s.toLowerCase());
-		},
-		type: "text"
-	});
-
-
-	ts.addParser({
-	    id: "json",
-	    is: function(s) {
-	        return s.startswith('json:');
-	    },
-	    format: function(s,table,cell) {
-		return cw.evalJSON(s.slice(5));
-	    },
-	  type: "text"
-	});
-
-     ts.addParser({
-		id: "digit",
-		is: function(s,table) {
-			var c = table.config;
-			return $.tablesorter.isDigit(s,c);
-		},
-		format: function(s) {
-			return $.tablesorter.formatFloat(s);
-		},
-		type: "numeric"
-	});
-
-	ts.addParser({
-		id: "currency",
-		is: function(s) {
-			return /^[£$€?.]/.test(s);
-		},
-		format: function(s) {
-			return $.tablesorter.formatFloat(s.replace(new RegExp(/[^0-9.]/g),""));
-		},
-		type: "numeric"
-	});
-
-	ts.addParser({
-		id: "ipAddress",
-		is: function(s) {
-			return /^\d{2,3}[\.]\d{2,3}[\.]\d{2,3}[\.]\d{2,3}$/.test(s);
-		},
-		format: function(s) {
-			var a = s.split("."), r = "", l = a.length;
-			for(var i = 0; i < l; i++) {
-				var item = a[i];
-			   	if(item.length == 2) {
-					r += "0" + item;
-			   	} else {
-					r += item;
-			   	}
-			}
-			return $.tablesorter.formatFloat(r);
-		},
-		type: "numeric"
-	});
-
-	ts.addParser({
-		id: "url",
-		is: function(s) {
-			return /^(https?|ftp|file):\/\/$/.test(s);
-		},
-		format: function(s) {
-			return jQuery.trim(s.replace(new RegExp(/(https?|ftp|file):\/\//),''));
-		},
-		type: "text"
-	});
-
-	ts.addParser({
-		id: "isoDate",
-		is: function(s) {
-			return /^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(s);
-		},
-		format: function(s) {
-			return $.tablesorter.formatFloat((s != "") ? new Date(s.replace(new RegExp(/-/g),"/")).getTime() : "0");
-		},
-		type: "numeric"
-	});
-
-	ts.addParser({
-		id: "percent",
-		is: function(s) {
-			return /\%$/.test($.trim(s));
-		},
-		format: function(s) {
-			return $.tablesorter.formatFloat(s.replace(new RegExp(/%/g),""));
-		},
-		type: "numeric"
-	});
-
-	ts.addParser({
-		id: "usLongDate",
-		is: function(s) {
-			return s.match(new RegExp(/^[A-Za-z]{3,10}\.? [0-9]{1,2}, ([0-9]{4}|'?[0-9]{2}) (([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(AM|PM)))$/)); //'
-		},
-		format: function(s) {
-			return $.tablesorter.formatFloat(new Date(s).getTime());
-		},
-		type: "numeric"
-	});
-
-	ts.addParser({
-		id: "shortDate",
-		is: function(s) {
-			return /\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}/.test(s);
-		},
-		format: function(s,table) {
-			var c = table.config;
-			s = s.replace(/\-/g,"/");
-			if(c.dateFormat == "us") {
-				// reformat the string in ISO format
-				s = s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/, "$3/$1/$2");
-			} else if(c.dateFormat == "uk") {
-				//reformat the string in ISO format
-				s = s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/, "$3/$2/$1");
-			} else if(c.dateFormat == "dd/mm/yy" || c.dateFormat == "dd-mm-yy") {
-				s = s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2})/, "$1/$2/$3");
-			}
-			return $.tablesorter.formatFloat(new Date(s).getTime());
-		},
-		type: "numeric"
-	});
-
-	ts.addParser({
-	    id: "time",
-	    is: function(s) {
-	        return /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/.test(s);
-	    },
-	    format: function(s) {
-	        return $.tablesorter.formatFloat(new Date("2000/01/01 " + s).getTime());
-	    },
-	  type: "numeric"
-	});
-
-
-	ts.addParser({
-	    id: "metadata",
-	    is: function(s) {
-	        return false;
-	    },
-	    format: function(s,table,cell) {
-			var c = table.config, p = (!c.parserMetadataName) ? 'sortValue' : c.parserMetadataName;
-	        return $(cell).metadata()[p];
-	    },
-	  type: "numeric"
-	});
-
-
-	// add default widgets
-	ts.addWidget({
-		id: "zebra",
-		format: function(table) {
-			if(table.config.debug) { var time = new Date(); }
-			$("tr:visible",table.tBodies[0])
-	        .filter(':even')
-	        .removeClass(table.config.widgetZebra.css[1]).addClass(table.config.widgetZebra.css[0])
-	        .end().filter(':odd')
-	        .removeClass(table.config.widgetZebra.css[0]).addClass(table.config.widgetZebra.css[1]);
-			if(table.config.debug) { $.tablesorter.benchmark("Applying Zebra widget", time); }
-		}
-	});
-})(jQuery);
-
-
-function cubicwebSortValueExtraction(node){
-    var sortvalue = jQuery(node).attr('cubicweb:sortvalue');
-    if (sortvalue === undefined) {
-	return '';
-    }
-    return sortvalue;
-}
-
-Sortable.sortTables = function() {
-   jQuery("table.listing").tablesorter({textExtraction: cubicwebSortValueExtraction});
-};
+/*
+ *
+ * TableSorter 2.0 - Client-side table sorting with ease!
+ * Version 2.0.5b
+ * @requires jQuery v1.2.3
+ *
+ * Copyright (c) 2007 Christian Bach
+ * Examples and docs at: http://tablesorter.com
+ * Dual licensed under the MIT and GPL licenses:
+ * http://www.opensource.org/licenses/mit-license.php
+ * http://www.gnu.org/licenses/gpl.html
+ *
+ */
+/**
+ *
+ * @description Create a sortable table with multi-column sorting capabilitys
+ *
+ * @example $('table').tablesorter();
+ * @desc Create a simple tablesorter interface.
+ *
+ * @example $('table').tablesorter({ sortList:[[0,0],[1,0]] });
+ * @desc Create a tablesorter interface and sort on the first and secound column column headers.
+ *
+ * @example $('table').tablesorter({ headers: { 0: { sorter: false}, 1: {sorter: false} } });
+ *
+ * @desc Create a tablesorter interface and disableing the first and second  column headers.
+ *
+ *
+ * @example $('table').tablesorter({ headers: { 0: {sorter:"integer"}, 1: {sorter:"currency"} } });
+ *
+ * @desc Create a tablesorter interface and set a column parser for the first
+ *       and second column.
+ *
+ *
+ * @param Object
+ *            settings An object literal containing key/value pairs to provide
+ *            optional settings.
+ *
+ *
+ * @option String cssHeader (optional) A string of the class name to be appended
+ *         to sortable tr elements in the thead of the table. Default value:
+ *         "header"
+ *
+ * @option String cssAsc (optional) A string of the class name to be appended to
+ *         sortable tr elements in the thead on a ascending sort. Default value:
+ *         "headerSortUp"
+ *
+ * @option String cssDesc (optional) A string of the class name to be appended
+ *         to sortable tr elements in the thead on a descending sort. Default
+ *         value: "headerSortDown"
+ *
+ * @option String sortInitialOrder (optional) A string of the inital sorting
+ *         order can be asc or desc. Default value: "asc"
+ *
+ * @option String sortMultisortKey (optional) A string of the multi-column sort
+ *         key. Default value: "shiftKey"
+ *
+ * @option String textExtraction (optional) A string of the text-extraction
+ *         method to use. For complex html structures inside td cell set this
+ *         option to "complex", on large tables the complex option can be slow.
+ *         Default value: "simple"
+ *
+ * @option Object headers (optional) An array containing the forces sorting
+ *         rules. This option let's you specify a default sorting rule. Default
+ *         value: null
+ *
+ * @option Array sortList (optional) An array containing the forces sorting
+ *         rules. This option let's you specify a default sorting rule. Default
+ *         value: null
+ *
+ * @option Array sortForce (optional) An array containing forced sorting rules.
+ *         This option let's you specify a default sorting rule, which is
+ *         prepended to user-selected rules. Default value: null
+ *
+ * @option Boolean sortLocaleCompare (optional) Boolean flag indicating whatever
+ *         to use String.localeCampare method or not. Default set to true.
+ *
+ *
+ * @option Array sortAppend (optional) An array containing forced sorting rules.
+ *         This option let's you specify a default sorting rule, which is
+ *         appended to user-selected rules. Default value: null
+ *
+ * @option Boolean widthFixed (optional) Boolean flag indicating if tablesorter
+ *         should apply fixed widths to the table columns. This is usefull when
+ *         using the pager companion plugin. This options requires the dimension
+ *         jquery plugin. Default value: false
+ *
+ * @option Boolean cancelSelection (optional) Boolean flag indicating if
+ *         tablesorter should cancel selection of the table headers text.
+ *         Default value: true
+ *
+ * @option Boolean debug (optional) Boolean flag indicating if tablesorter
+ *         should display debuging information usefull for development.
+ *
+ * @type jQuery
+ *
+ * @name tablesorter
+ *
+ * @cat Plugins/Tablesorter
+ *
+ * @author Christian Bach/christian.bach@polyester.se
+ */
+
+(function ($) {
+    $.extend({
+        tablesorter: new
+        function () {
+
+            var parsers = [],
+                widgets = [];
+
+            this.defaults = {
+                cssHeader: "header",
+                cssAsc: "headerSortUp",
+                cssDesc: "headerSortDown",
+                cssChildRow: "expand-child",
+                sortInitialOrder: "asc",
+                sortMultiSortKey: "shiftKey",
+                sortForce: null,
+                sortAppend: null,
+                sortLocaleCompare: true,
+                textExtraction: "simple",
+                parsers: {}, widgets: [],
+                widgetZebra: {
+                    css: ["even", "odd"]
+                }, headers: {}, widthFixed: false,
+                cancelSelection: true,
+                sortList: [],
+                headerList: [],
+                dateFormat: "us",
+                decimal: '/\.|\,/g',
+                onRenderHeader: null,
+                selectorHeaders: 'thead th',
+                debug: false
+            };
+
+            /* debuging utils */
+
+            function benchmark(s, d) {
+                log(s + "," + (new Date().getTime() - d.getTime()) + "ms");
+            }
+
+            this.benchmark = benchmark;
+
+            function log(s) {
+                if (typeof console != "undefined" && typeof console.debug != "undefined") {
+                    console.log(s);
+                } else {
+                    alert(s);
+                }
+            }
+
+            /* parsers utils */
+
+            function buildParserCache(table, $headers) {
+
+                if (table.config.debug) {
+                    var parsersDebug = "";
+                }
+
+                if (table.tBodies.length == 0) return; // In the case of empty tables
+                var rows = table.tBodies[0].rows;
+
+                if (rows[0]) {
+
+                    var list = [],
+                        cells = rows[0].cells,
+                        l = cells.length;
+
+                    for (var i = 0; i < l; i++) {
+
+                        var p = false;
+
+                        if ($.metadata && ($($headers[i]).metadata() && $($headers[i]).metadata().sorter)) {
+
+                            p = getParserById($($headers[i]).metadata().sorter);
+
+                        } else if ((table.config.headers[i] && table.config.headers[i].sorter)) {
+
+                            p = getParserById(table.config.headers[i].sorter);
+                        }
+                        if (!p) {
+
+                            p = detectParserForColumn(table, rows, -1, i);
+                        }
+
+                        if (table.config.debug) {
+                            parsersDebug += "column:" + i + " parser:" + p.id + "\n";
+                        }
+
+                        list.push(p);
+                    }
+                }
+
+                if (table.config.debug) {
+                    log(parsersDebug);
+                }
+
+                return list;
+            };
+
+            function detectParserForColumn(table, rows, rowIndex, cellIndex) {
+                var l = parsers.length,
+                    node = false,
+                    nodeValue = false,
+                    keepLooking = true;
+                while (nodeValue == '' && keepLooking) {
+                    rowIndex++;
+                    if (rows[rowIndex]) {
+                        node = getNodeFromRowAndCellIndex(rows, rowIndex, cellIndex);
+                        nodeValue = trimAndGetNodeText(table.config, node);
+                        if (table.config.debug) {
+                            log('Checking if value was empty on row:' + rowIndex);
+                        }
+                    } else {
+                        keepLooking = false;
+                    }
+                }
+                for (var i = 1; i < l; i++) {
+                    if (parsers[i].is(nodeValue, table, node)) {
+                        return parsers[i];
+                    }
+                }
+                // 0 is always the generic parser (text)
+                return parsers[0];
+            }
+
+            function getNodeFromRowAndCellIndex(rows, rowIndex, cellIndex) {
+                return rows[rowIndex].cells[cellIndex];
+            }
+
+            function trimAndGetNodeText(config, node) {
+                return $.trim(getElementText(config, node));
+            }
+
+            function getParserById(name) {
+                var l = parsers.length;
+                for (var i = 0; i < l; i++) {
+                    if (parsers[i].id.toLowerCase() == name.toLowerCase()) {
+                        return parsers[i];
+                    }
+                }
+                return false;
+            }
+
+            /* utils */
+
+            function buildCache(table) {
+
+                if (table.config.debug) {
+                    var cacheTime = new Date();
+                }
+
+                var totalRows = (table.tBodies[0] && table.tBodies[0].rows.length) || 0,
+                    totalCells = (table.tBodies[0].rows[0] && table.tBodies[0].rows[0].cells.length) || 0,
+                    parsers = table.config.parsers,
+                    cache = {
+                        row: [],
+                        normalized: []
+                    };
+
+                for (var i = 0; i < totalRows; ++i) {
+
+                    /** Add the table data to main data array */
+                    var c = $(table.tBodies[0].rows[i]),
+                        cols = [];
+
+                    // if this is a child row, add it to the last row's children and
+                    // continue to the next row
+                    if (c.hasClass(table.config.cssChildRow)) {
+                        cache.row[cache.row.length - 1] = cache.row[cache.row.length - 1].add(c);
+                        // go to the next for loop
+                        continue;
+                    }
+
+                    cache.row.push(c);
+
+                    for (var j = 0; j < totalCells; ++j) {
+                        cols.push(parsers[j].format(getElementText(table.config, c[0].cells[j]), table, c[0].cells[j]));
+                    }
+
+                    cols.push(cache.normalized.length); // add position for rowCache
+                    cache.normalized.push(cols);
+                    cols = null;
+                };
+
+                if (table.config.debug) {
+                    benchmark("Building cache for " + totalRows + " rows:", cacheTime);
+                }
+
+                return cache;
+            };
+
+            function getElementText(config, node) {
+
+                var text = "";
+
+                if (!node) return "";
+
+                if (!config.supportsTextContent) config.supportsTextContent = node.textContent || false;
+
+                if (config.textExtraction == "simple") {
+                    if (config.supportsTextContent) {
+                        text = node.textContent;
+                    } else {
+                        if (node.childNodes[0] && node.childNodes[0].hasChildNodes()) {
+                            text = node.childNodes[0].innerHTML;
+                        } else {
+                            text = node.innerHTML;
+                        }
+                    }
+                } else {
+                    if (typeof(config.textExtraction) == "function") {
+                        text = config.textExtraction(node);
+                    } else {
+                        text = $(node).text();
+                    }
+                }
+                return text;
+            }
+
+            function appendToTable(table, cache) {
+
+                if (table.config.debug) {
+                    var appendTime = new Date()
+                }
+
+                var c = cache,
+                    r = c.row,
+                    n = c.normalized,
+                    totalRows = n.length,
+                    checkCell = (n[0].length - 1),
+                    tableBody = $(table.tBodies[0]),
+                    rows = [];
+
+
+                for (var i = 0; i < totalRows; i++) {
+                    var pos = n[i][checkCell];
+
+                    rows.push(r[pos]);
+
+                    if (!table.config.appender) {
+
+                        //var o = ;
+                        var l = r[pos].length;
+                        for (var j = 0; j < l; j++) {
+                            tableBody[0].appendChild(r[pos][j]);
+                        }
+
+                        //
+                    }
+                }
+
+
+
+                if (table.config.appender) {
+
+                    table.config.appender(table, rows);
+                }
+
+                rows = null;
+
+                if (table.config.debug) {
+                    benchmark("Rebuilt table:", appendTime);
+                }
+
+                // apply table widgets
+                applyWidget(table);
+
+                // trigger sortend
+                setTimeout(function () {
+                    $(table).trigger("sortEnd");
+                }, 0);
+
+            };
+
+            function buildHeaders(table) {
+
+                if (table.config.debug) {
+                    var time = new Date();
+                }
+
+                var meta = ($.metadata) ? true : false;
+
+                var header_index = computeTableHeaderCellIndexes(table);
+
+                $tableHeaders = $(table.config.selectorHeaders, table).each(function (index) {
+
+                    this.column = header_index[this.parentNode.rowIndex + "-" + this.cellIndex];
+                    // this.column = index;
+                    this.order = formatSortingOrder(table.config.sortInitialOrder);
+
+
+                    this.count = this.order;
+
+                    if (checkHeaderMetadata(this) || checkHeaderOptions(table, index)) this.sortDisabled = true;
+                    if (checkHeaderOptionsSortingLocked(table, index)) this.order = this.lockedOrder = checkHeaderOptionsSortingLocked(table, index);
+
+                    if (!this.sortDisabled) {
+                        var $th = $(this).addClass(table.config.cssHeader);
+                        if (table.config.onRenderHeader) table.config.onRenderHeader.apply($th);
+                    }
+
+                    // add cell to headerList
+                    table.config.headerList[index] = this;
+                });
+
+                if (table.config.debug) {
+                    benchmark("Built headers:", time);
+                    log($tableHeaders);
+                }
+
+                return $tableHeaders;
+
+            };
+
+            // from:
+            // http://www.javascripttoolbox.com/lib/table/examples.php
+            // http://www.javascripttoolbox.com/temp/table_cellindex.html
+
+
+            function computeTableHeaderCellIndexes(t) {
+                var matrix = [];
+                var lookup = {};
+                var thead = t.getElementsByTagName('THEAD')[0];
+                var trs = thead.getElementsByTagName('TR');
+
+                for (var i = 0; i < trs.length; i++) {
+                    var cells = trs[i].cells;
+                    for (var j = 0; j < cells.length; j++) {
+                        var c = cells[j];
+
+                        var rowIndex = c.parentNode.rowIndex;
+                        var cellId = rowIndex + "-" + c.cellIndex;
+                        var rowSpan = c.rowSpan || 1;
+                        var colSpan = c.colSpan || 1
+                        var firstAvailCol;
+                        if (typeof(matrix[rowIndex]) == "undefined") {
+                            matrix[rowIndex] = [];
+                        }
+                        // Find first available column in the first row
+                        for (var k = 0; k < matrix[rowIndex].length + 1; k++) {
+                            if (typeof(matrix[rowIndex][k]) == "undefined") {
+                                firstAvailCol = k;
+                                break;
+                            }
+                        }
+                        lookup[cellId] = firstAvailCol;
+                        for (var k = rowIndex; k < rowIndex + rowSpan; k++) {
+                            if (typeof(matrix[k]) == "undefined") {
+                                matrix[k] = [];
+                            }
+                            var matrixrow = matrix[k];
+                            for (var l = firstAvailCol; l < firstAvailCol + colSpan; l++) {
+                                matrixrow[l] = "x";
+                            }
+                        }
+                    }
+                }
+                return lookup;
+            }
+
+            function checkCellColSpan(table, rows, row) {
+                var arr = [],
+                    r = table.tHead.rows,
+                    c = r[row].cells;
+
+                for (var i = 0; i < c.length; i++) {
+                    var cell = c[i];
+
+                    if (cell.colSpan > 1) {
+                        arr = arr.concat(checkCellColSpan(table, headerArr, row++));
+                    } else {
+                        if (table.tHead.length == 1 || (cell.rowSpan > 1 || !r[row + 1])) {
+                            arr.push(cell);
+                        }
+                        // headerArr[row] = (i+row);
+                    }
+                }
+                return arr;
+            };
+
+            function checkHeaderMetadata(cell) {
+                if (($.metadata) && ($(cell).metadata().sorter === false)) {
+                    return true;
+                };
+                return false;
+            }
+
+            function checkHeaderOptions(table, i) {
+                if ((table.config.headers[i]) && (table.config.headers[i].sorter === false)) {
+                    return true;
+                };
+                return false;
+            }
+
+            function checkHeaderOptionsSortingLocked(table, i) {
+                if ((table.config.headers[i]) && (table.config.headers[i].lockedOrder)) return table.config.headers[i].lockedOrder;
+                return false;
+            }
+
+            function applyWidget(table) {
+                var c = table.config.widgets;
+                var l = c.length;
+                for (var i = 0; i < l; i++) {
+
+                    getWidgetById(c[i]).format(table);
+                }
+
+            }
+
+            function getWidgetById(name) {
+                var l = widgets.length;
+                for (var i = 0; i < l; i++) {
+                    if (widgets[i].id.toLowerCase() == name.toLowerCase()) {
+                        return widgets[i];
+                    }
+                }
+            };
+
+            function formatSortingOrder(v) {
+                if (typeof(v) != "Number") {
+                    return (v.toLowerCase() == "desc") ? 1 : 0;
+                } else {
+                    return (v == 1) ? 1 : 0;
+                }
+            }
+
+            function isValueInArray(v, a) {
+                var l = a.length;
+                for (var i = 0; i < l; i++) {
+                    if (a[i][0] == v) {
+                        return true;
+                    }
+                }
+                return false;
+            }
+
+            function setHeadersCss(table, $headers, list, css) {
+                // remove all header information
+                $headers.removeClass(css[0]).removeClass(css[1]);
+
+                var h = [];
+                $headers.each(function (offset) {
+                    if (!this.sortDisabled) {
+                        h[this.column] = $(this);
+                    }
+                });
+
+                var l = list.length;
+                for (var i = 0; i < l; i++) {
+                    h[list[i][0]].addClass(css[list[i][1]]);
+                }
+            }
+
+            function fixColumnWidth(table, $headers) {
+                var c = table.config;
+                if (c.widthFixed) {
+                    var colgroup = $('<colgroup>');
+                    $("tr:first td", table.tBodies[0]).each(function () {
+                        colgroup.append($('<col>').css('width', $(this).width()));
+                    });
+                    $(table).prepend(colgroup);
+                };
+            }
+
+            function updateHeaderSortCount(table, sortList) {
+                var c = table.config,
+                    l = sortList.length;
+                for (var i = 0; i < l; i++) {
+                    var s = sortList[i],
+                        o = c.headerList[s[0]];
+                    o.count = s[1];
+                    o.count++;
+                }
+            }
+
+            /* sorting methods */
+
+            function multisort(table, sortList, cache) {
+
+                if (table.config.debug) {
+                    var sortTime = new Date();
+                }
+
+                var dynamicExp = "var sortWrapper = function(a,b) {",
+                    l = sortList.length;
+
+                // TODO: inline functions.
+                for (var i = 0; i < l; i++) {
+
+                    var c = sortList[i][0];
+                    var order = sortList[i][1];
+                    // var s = (getCachedSortType(table.config.parsers,c) == "text") ?
+                    // ((order == 0) ? "sortText" : "sortTextDesc") : ((order == 0) ?
+                    // "sortNumeric" : "sortNumericDesc");
+                    // var s = (table.config.parsers[c].type == "text") ? ((order == 0)
+                    // ? makeSortText(c) : makeSortTextDesc(c)) : ((order == 0) ?
+                    // makeSortNumeric(c) : makeSortNumericDesc(c));
+                    var s = (table.config.parsers[c].type == "text") ? ((order == 0) ? makeSortFunction("text", "asc", c) : makeSortFunction("text", "desc", c)) : ((order == 0) ? makeSortFunction("numeric", "asc", c) : makeSortFunction("numeric", "desc", c));
+                    var e = "e" + i;
+
+                    dynamicExp += "var " + e + " = " + s; // + "(a[" + c + "],b[" + c
+                    // + "]); ";
+                    dynamicExp += "if(" + e + ") { return " + e + "; } ";
+                    dynamicExp += "else { ";
+
+                }
+
+                // if value is the same keep orignal order
+                var orgOrderCol = cache.normalized[0].length - 1;
+                dynamicExp += "return a[" + orgOrderCol + "]-b[" + orgOrderCol + "];";
+
+                for (var i = 0; i < l; i++) {
+                    dynamicExp += "}; ";
+                }
+
+                dynamicExp += "return 0; ";
+                dynamicExp += "}; ";
+
+                if (table.config.debug) {
+                    benchmark("Evaling expression:" + dynamicExp, new Date());
+                }
+
+                eval(dynamicExp);
+
+                cache.normalized.sort(sortWrapper);
+
+                if (table.config.debug) {
+                    benchmark("Sorting on " + sortList.toString() + " and dir " + order + " time:", sortTime);
+                }
+
+                return cache;
+            };
+
+            function makeSortFunction(type, direction, index) {
+                var a = "a[" + index + "]",
+                    b = "b[" + index + "]";
+                if (type == 'text' && direction == 'asc') {
+                    return "(" + a + " == " + b + " ? 0 : (" + a + " === null ? Number.POSITIVE_INFINITY : (" + b + " === null ? Number.NEGATIVE_INFINITY : (" + a + " < " + b + ") ? -1 : 1 )));";
+                } else if (type == 'text' && direction == 'desc') {
+                    return "(" + a + " == " + b + " ? 0 : (" + a + " === null ? Number.POSITIVE_INFINITY : (" + b + " === null ? Number.NEGATIVE_INFINITY : (" + b + " < " + a + ") ? -1 : 1 )));";
+                } else if (type == 'numeric' && direction == 'asc') {
+                    return "(" + a + " === null && " + b + " === null) ? 0 :(" + a + " === null ? Number.POSITIVE_INFINITY : (" + b + " === null ? Number.NEGATIVE_INFINITY : " + a + " - " + b + "));";
+                } else if (type == 'numeric' && direction == 'desc') {
+                    return "(" + a + " === null && " + b + " === null) ? 0 :(" + a + " === null ? Number.POSITIVE_INFINITY : (" + b + " === null ? Number.NEGATIVE_INFINITY : " + b + " - " + a + "));";
+                }
+            };
+
+            function makeSortText(i) {
+                return "((a[" + i + "] < b[" + i + "]) ? -1 : ((a[" + i + "] > b[" + i + "]) ? 1 : 0));";
+            };
+
+            function makeSortTextDesc(i) {
+                return "((b[" + i + "] < a[" + i + "]) ? -1 : ((b[" + i + "] > a[" + i + "]) ? 1 : 0));";
+            };
+
+            function makeSortNumeric(i) {
+                return "a[" + i + "]-b[" + i + "];";
+            };
+
+            function makeSortNumericDesc(i) {
+                return "b[" + i + "]-a[" + i + "];";
+            };
+
+            function sortText(a, b) {
+                if (table.config.sortLocaleCompare) return a.localeCompare(b);
+                return ((a < b) ? -1 : ((a > b) ? 1 : 0));
+            };
+
+            function sortTextDesc(a, b) {
+                if (table.config.sortLocaleCompare) return b.localeCompare(a);
+                return ((b < a) ? -1 : ((b > a) ? 1 : 0));
+            };
+
+            function sortNumeric(a, b) {
+                return a - b;
+            };
+
+            function sortNumericDesc(a, b) {
+                return b - a;
+            };
+
+            function getCachedSortType(parsers, i) {
+                return parsers[i].type;
+            }; /* public methods */
+            this.construct = function (settings) {
+                return this.each(function () {
+                    // if no thead or tbody quit.
+                    if (!this.tHead || !this.tBodies) return;
+                    // declare
+                    var $this, $document, $headers, cache, config, shiftDown = 0,
+                        sortOrder;
+                    // new blank config object
+                    this.config = {};
+                    // merge and extend.
+                    config = $.extend(this.config, $.tablesorter.defaults, settings);
+                    // store common expression for speed
+                    $this = $(this);
+                    // save the settings where they read
+                    $.data(this, "tablesorter", config);
+                    // build headers
+                    $headers = buildHeaders(this);
+                    // try to auto detect column type, and store in tables config
+                    this.config.parsers = buildParserCache(this, $headers);
+                    // build the cache for the tbody cells
+                    cache = buildCache(this);
+                    // get the css class names, could be done else where.
+                    var sortCSS = [config.cssDesc, config.cssAsc];
+                    // fixate columns if the users supplies the fixedWidth option
+                    fixColumnWidth(this);
+                    // apply event handling to headers
+                    // this is to big, perhaps break it out?
+                    $headers.click(
+
+                    function (e) {
+                        var totalRows = ($this[0].tBodies[0] && $this[0].tBodies[0].rows.length) || 0;
+                        if (!this.sortDisabled && totalRows > 0) {
+                            // Only call sortStart if sorting is
+                            // enabled.
+                            $this.trigger("sortStart");
+                            // store exp, for speed
+                            var $cell = $(this);
+                            // get current column index
+                            var i = this.column;
+                            // get current column sort order
+                            this.order = this.count++ % 2;
+                            // always sort on the locked order.
+                            if(this.lockedOrder) this.order = this.lockedOrder;
+
+                            // user only whants to sort on one
+                            // column
+                            if (!e[config.sortMultiSortKey]) {
+                                // flush the sort list
+                                config.sortList = [];
+                                if (config.sortForce != null) {
+                                    var a = config.sortForce;
+                                    for (var j = 0; j < a.length; j++) {
+                                        if (a[j][0] != i) {
+                                            config.sortList.push(a[j]);
+                                        }
+                                    }
+                                }
+                                // add column to sort list
+                                config.sortList.push([i, this.order]);
+                                // multi column sorting
+                            } else {
+                                // the user has clicked on an all
+                                // ready sortet column.
+                                if (isValueInArray(i, config.sortList)) {
+                                    // revers the sorting direction
+                                    // for all tables.
+                                    for (var j = 0; j < config.sortList.length; j++) {
+                                        var s = config.sortList[j],
+                                            o = config.headerList[s[0]];
+                                        if (s[0] == i) {
+                                            o.count = s[1];
+                                            o.count++;
+                                            s[1] = o.count % 2;
+                                        }
+                                    }
+                                } else {
+                                    // add column to sort list array
+                                    config.sortList.push([i, this.order]);
+                                }
+                            };
+                            setTimeout(function () {
+                                // set css for headers
+                                setHeadersCss($this[0], $headers, config.sortList, sortCSS);
+                                appendToTable(
+	                                $this[0], multisort(
+	                                $this[0], config.sortList, cache)
+								);
+                            }, 1);
+                            // stop normal event by returning false
+                            return false;
+                        }
+                        // cancel selection
+                    }).mousedown(function () {
+                        if (config.cancelSelection) {
+                            this.onselectstart = function () {
+                                return false
+                            };
+                            return false;
+                        }
+                    });
+                    // apply easy methods that trigger binded events
+                    $this.bind("update", function () {
+                        var me = this;
+                        setTimeout(function () {
+                            // rebuild parsers.
+                            me.config.parsers = buildParserCache(
+                            me, $headers);
+                            // rebuild the cache map
+                            cache = buildCache(me);
+                        }, 1);
+                    }).bind("updateCell", function (e, cell) {
+                        var config = this.config;
+                        // get position from the dom.
+                        var pos = [(cell.parentNode.rowIndex - 1), cell.cellIndex];
+                        // update cache
+                        cache.normalized[pos[0]][pos[1]] = config.parsers[pos[1]].format(
+                        getElementText(config, cell), cell);
+                    }).bind("sorton", function (e, list) {
+                        $(this).trigger("sortStart");
+                        config.sortList = list;
+                        // update and store the sortlist
+                        var sortList = config.sortList;
+                        // update header count index
+                        updateHeaderSortCount(this, sortList);
+                        // set css for headers
+                        setHeadersCss(this, $headers, sortList, sortCSS);
+                        // sort the table and append it to the dom
+                        appendToTable(this, multisort(this, sortList, cache));
+                    }).bind("appendCache", function () {
+                        appendToTable(this, cache);
+                    }).bind("applyWidgetId", function (e, id) {
+                        getWidgetById(id).format(this);
+                    }).bind("applyWidgets", function () {
+                        // apply widgets
+                        applyWidget(this);
+                    });
+                    if ($.metadata && ($(this).metadata() && $(this).metadata().sortlist)) {
+                        config.sortList = $(this).metadata().sortlist;
+                    }
+                    // if user has supplied a sort list to constructor.
+                    if (config.sortList.length > 0) {
+                        $this.trigger("sorton", [config.sortList]);
+                    }
+                    // apply widgets
+                    applyWidget(this);
+                });
+            };
+            this.addParser = function (parser) {
+                var l = parsers.length,
+                    a = true;
+                for (var i = 0; i < l; i++) {
+                    if (parsers[i].id.toLowerCase() == parser.id.toLowerCase()) {
+                        a = false;
+                    }
+                }
+                if (a) {
+                    parsers.push(parser);
+                };
+            };
+            this.addWidget = function (widget) {
+                widgets.push(widget);
+            };
+            this.formatFloat = function (s) {
+                var i = parseFloat(s);
+                return (isNaN(i)) ? 0 : i;
+            };
+            this.formatInt = function (s) {
+                var i = parseInt(s);
+                return (isNaN(i)) ? 0 : i;
+            };
+            this.isDigit = function (s, config) {
+                // replace all an wanted chars and match.
+                return /^[-+]?\d*$/.test($.trim(s.replace(/[,.']/g, '')));
+            };
+            this.clearTableBody = function (table) {
+                if ($.browser.msie) {
+                    function empty() {
+                        while (this.firstChild)
+                        this.removeChild(this.firstChild);
+                    }
+                    empty.apply(table.tBodies[0]);
+                } else {
+                    table.tBodies[0].innerHTML = "";
+                }
+            };
+        }
+    });
+
+    // extend plugin scope
+    $.fn.extend({
+        tablesorter: $.tablesorter.construct
+    });
+
+    // make shortcut
+    var ts = $.tablesorter;
+
+    // add default parsers
+    ts.addParser({
+        id: "text",
+        is: function (s) {
+            return true;
+        }, format: function (s) {
+            return $.trim(s.toLocaleLowerCase());
+        }, type: "text"
+    });
+
+    ts.addParser({
+        id: "digit",
+        is: function (s, table) {
+            var c = table.config;
+            return $.tablesorter.isDigit(s, c);
+        }, format: function (s) {
+            return $.tablesorter.formatFloat(s);
+        }, type: "numeric"
+    });
+
+    ts.addParser({
+        id: "currency",
+        is: function (s) {
+            return /^[£$€?.]/.test(s);
+        }, format: function (s) {
+            return $.tablesorter.formatFloat(s.replace(new RegExp(/[£$€]/g), ""));
+        }, type: "numeric"
+    });
+
+    ts.addParser({
+        id: "ipAddress",
+        is: function (s) {
+            return /^\d{2,3}[\.]\d{2,3}[\.]\d{2,3}[\.]\d{2,3}$/.test(s);
+        }, format: function (s) {
+            var a = s.split("."),
+                r = "",
+                l = a.length;
+            for (var i = 0; i < l; i++) {
+                var item = a[i];
+                if (item.length == 2) {
+                    r += "0" + item;
+                } else {
+                    r += item;
+                }
+            }
+            return $.tablesorter.formatFloat(r);
+        }, type: "numeric"
+    });
+
+    ts.addParser({
+        id: "url",
+        is: function (s) {
+            return /^(https?|ftp|file):\/\/$/.test(s);
+        }, format: function (s) {
+            return jQuery.trim(s.replace(new RegExp(/(https?|ftp|file):\/\//), ''));
+        }, type: "text"
+    });
+
+    ts.addParser({
+        id: "isoDate",
+        is: function (s) {
+            return /^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(s);
+        }, format: function (s) {
+            return $.tablesorter.formatFloat((s != "") ? new Date(s.replace(
+            new RegExp(/-/g), "/")).getTime() : "0");
+        }, type: "numeric"
+    });
+
+    ts.addParser({
+        id: "percent",
+        is: function (s) {
+            return /\%$/.test($.trim(s));
+        }, format: function (s) {
+            return $.tablesorter.formatFloat(s.replace(new RegExp(/%/g), ""));
+        }, type: "numeric"
+    });
+
+    ts.addParser({
+        id: "usLongDate",
+        is: function (s) {
+            return s.match(new RegExp(/^[A-Za-z]{3,10}\.? [0-9]{1,2}, ([0-9]{4}|'?[0-9]{2}) (([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(AM|PM)))$/));
+        }, format: function (s) {
+            return $.tablesorter.formatFloat(new Date(s).getTime());
+        }, type: "numeric"
+    });
+
+    ts.addParser({
+        id: "shortDate",
+        is: function (s) {
+            return /\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}/.test(s);
+        }, format: function (s, table) {
+            var c = table.config;
+            s = s.replace(/\-/g, "/");
+            if (c.dateFormat == "us") {
+                // reformat the string in ISO format
+                s = s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/, "$3/$1/$2");
+            } else if (c.dateFormat == "uk") {
+                // reformat the string in ISO format
+                s = s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/, "$3/$2/$1");
+            } else if (c.dateFormat == "dd/mm/yy" || c.dateFormat == "dd-mm-yy") {
+                s = s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2})/, "$1/$2/$3");
+            }
+            return $.tablesorter.formatFloat(new Date(s).getTime());
+        }, type: "numeric"
+    });
+    ts.addParser({
+        id: "time",
+        is: function (s) {
+            return /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/.test(s);
+        }, format: function (s) {
+            return $.tablesorter.formatFloat(new Date("2000/01/01 " + s).getTime());
+        }, type: "numeric"
+    });
+    ts.addParser({
+        id: "metadata",
+        is: function (s) {
+            return false;
+        }, format: function (s, table, cell) {
+            var c = table.config,
+                p = (!c.parserMetadataName) ? 'sortValue' : c.parserMetadataName;
+            return $(cell).metadata()[p];
+        }, type: "numeric"
+    });
+    // add default widgets
+    ts.addWidget({
+        id: "zebra",
+        format: function (table) {
+            if (table.config.debug) {
+                var time = new Date();
+            }
+            var $tr, row = -1,
+                odd;
+            // loop through the visible rows
+            $("tr:visible", table.tBodies[0]).each(function (i) {
+                $tr = $(this);
+                // style children rows the same way the parent
+                // row was styled
+                if (!$tr.hasClass(table.config.cssChildRow)) row++;
+                odd = (row % 2 == 0);
+                $tr.removeClass(
+                table.config.widgetZebra.css[odd ? 0 : 1]).addClass(
+                table.config.widgetZebra.css[odd ? 1 : 0])
+            });
+            if (table.config.debug) {
+                $.tablesorter.benchmark("Applying Zebra widget", time);
+            }
+        }
+    });
+})(jQuery);
--- a/web/data/uiprops.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/data/uiprops.py	Fri Oct 14 09:21:45 2011 +0200
@@ -167,7 +167,7 @@
 errorMsgColor = '#ed0d0d'
 
 # facets
-facet_titleFont = 'bold 100% Georgia'
+facet_titleFont = 'bold SansSerif'
 facet_overflowedHeight = '12em'
-
-
+# the above minus 1
+facet_overflowedHeightWithLogicalSelector = '11em'
--- a/web/facet.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/facet.py	Fri Oct 14 09:21:45 2011 +0200
@@ -50,7 +50,7 @@
 
 from warnings import warn
 from copy import deepcopy
-from datetime import date, datetime, timedelta
+from datetime import datetime, timedelta
 
 from logilab.mtconverter import xml_escape
 from logilab.common.graph import has_path
@@ -59,7 +59,7 @@
 from logilab.common.compat import all
 from logilab.common.deprecation import deprecated
 
-from rql import parse, nodes, utils
+from rql import nodes, utils
 
 from cubicweb import Unauthorized, typed_eid
 from cubicweb.schema import display_name
@@ -494,6 +494,10 @@
     def wdgclass(self):
         return FacetVocabularyWidget
 
+    def get_selected(self):
+        return frozenset(typed_eid(eid)
+                         for eid in self._cw.list_form_param(self.__regid__))
+
     def get_widget(self):
         """Return the widget instance to use to display this facet.
 
@@ -504,12 +508,9 @@
         if len(vocab) <= 1:
             return None
         wdg = self.wdgclass(self)
-        selected = frozenset(typed_eid(eid) for eid in self._cw.list_form_param(self.__regid__))
+        selected = self.get_selected()
         for label, value in vocab:
-            if value is None:
-                wdg.append(FacetSeparator(label))
-            else:
-                wdg.append(FacetItem(self._cw, label, value, value in selected))
+            wdg.items.append((value, label, value in selected))
         return wdg
 
     def vocabulary(self):
@@ -524,7 +525,6 @@
         raise NotImplementedError
 
 
-
 class RelationFacet(VocabularyFacet):
     """Base facet to filter some entities according to other entities to which
     they are related. Create concrete facet by inheriting from this class an then
@@ -736,6 +736,7 @@
 
     # internal utilities #######################################################
 
+    @cached
     def _support_and_compat(self):
         support = self.support_and
         if callable(support):
@@ -1364,24 +1365,7 @@
 
 
 ## html widets ################################################################
-_DEFAULT_CONSTANT_VOCAB_WIDGET_HEIGHT = 9
-
-@cached
-def _css_height_to_line_count(vreg):
-    cssprop = vreg.config.uiprops['facet_overflowedHeight'].lower().strip()
-    # let's talk a bit ...
-    # we try to deduce a number of displayed lines from a css property
-    # there is a linear (rough empiric coefficient == 0.73) relation between
-    # css _em_ value and line qty
-    # if we get another unit we're out of luck and resort to one constant
-    # hence, it is strongly advised not to specify but ems for this css prop
-    if cssprop.endswith('em'):
-        try:
-            return int(cssprop[:-2]) * .73
-        except Exception:
-            vreg.warning('css property facet_overflowedHeight looks malformed (%r)',
-                         cssprop)
-    return _DEFAULT_CONSTANT_VOCAB_WIDGET_HEIGHT
+_DEFAULT_CONSTANT_VOCAB_WIDGET_HEIGHT = 12
 
 class FacetVocabularyWidget(htmlwidgets.HTMLWidget):
 
@@ -1389,13 +1373,35 @@
         self.facet = facet
         self.items = []
 
+    @property
+    @cached
+    def css_overflow_limit(self):
+        """ we try to deduce a number of displayed lines from a css property
+        if we get another unit we're out of luck and resort to one constant
+        hence, it is strongly advised not to specify but ems for this css prop
+        """
+        vreg = self.facet._cw.vreg
+        cssprop = vreg.config.uiprops['facet_overflowedHeight'].lower().strip()
+        if cssprop.endswith('em'):
+            try:
+                return int(cssprop[:-2])
+            except Exception:
+                vreg.warning('css property facet_overflowedHeight looks malformed (%r)',
+                             cssprop)
+        return _DEFAULT_CONSTANT_VOCAB_WIDGET_HEIGHT
+
+    @property
     @cached
     def height(self):
-        maxheight = _css_height_to_line_count(self.facet._cw.vreg)
-        return 1 + min(len(self.items), maxheight) + int(self.facet._support_and_compat())
+        return 1 + min(len(self.items),
+                       self.css_overflow_limit + int(self.facet._support_and_compat()))
 
-    def append(self, item):
-        self.items.append(item)
+    @property
+    @cached
+    def overflows(self):
+        return len(self.items) >= self.css_overflow_limit
+
+    scrollbar_padding_factor = 4
 
     def _render(self):
         w = self.w
@@ -1405,29 +1411,52 @@
         w(u'<div class="facetTitle" cubicweb:facetName="%s">%s</div>\n' %
           (xml_escape(self.facet.__regid__), title))
         if self.facet._support_and_compat():
-            _ = self.facet._cw._
-            w(u'''<select name="%s" class="radio facetOperator" title="%s">
-  <option value="OR">%s</option>
-  <option value="AND">%s</option>
-</select>''' % (xml_escape(self.facet.__regid__) + '_andor', _('and/or between different values'),
-                _('OR'), _('AND')))
-        cssclass = 'facetBody'
+            self._render_and_or(w)
+        cssclass = 'vocabularyFacet'
         if not self.facet.start_unfolded:
             cssclass += ' hidden'
-        if len(self.items) > 6:
-            cssclass += ' overflowed'
+        overflow = self.overflows
+        if overflow:
+            if self.facet._support_and_compat():
+                cssclass += ' vocabularyFacetBodyWithLogicalSelector'
+            else:
+                cssclass += ' vocabularyFacetBody'
         w(u'<div class="%s">\n' % cssclass)
-        for item in self.items:
-            item.render(w=w)
+        for value, label, selected in self.items:
+            if value is None:
+                continue
+            self._render_value(w, value, label, selected, overflow)
         w(u'</div>\n')
         w(u'</div>\n')
 
+    def _render_and_or(self, w):
+        _ = self.facet._cw._
+        w(u"""<select name='%s' class='radio facetOperator' title='%s'>
+  <option value='OR'>%s</option>
+  <option value='AND'>%s</option>
+</select>""" % (xml_escape(self.facet.__regid__) + '_andor',
+                _('and/or between different values'),
+                _('OR'), _('AND')))
+
+    def _render_value(self, w, value, label, selected, overflow):
+        cssclass = 'facetValue facetCheckBox'
+        if selected:
+            cssclass += ' facetValueSelected'
+        w(u'<div class="%s" cubicweb:value="%s">\n'
+          % (cssclass, xml_escape(unicode(value))))
+        # If it is overflowed one must add padding to compensate for the vertical
+        # scrollbar; given current css values, 4 blanks work perfectly ...
+        padding = u'&#160;' * self.scrollbar_padding_factor if overflow else u''
+        w('<span>%s</span>' % xml_escape(label))
+        w(padding)
+        w(u'</div>')
 
 class FacetStringWidget(htmlwidgets.HTMLWidget):
     def __init__(self, facet):
         self.facet = facet
         self.value = None
 
+    @property
     def height(self):
         return 3
 
@@ -1472,6 +1501,7 @@
         self.minvalue = minvalue
         self.maxvalue = maxvalue
 
+    @property
     def height(self):
         return 3
 
@@ -1532,34 +1562,6 @@
         facet._cw.html_headers.define_var('DATE_FMT', fmt)
 
 
-class FacetItem(htmlwidgets.HTMLWidget):
-
-    selected_img = "black-check.png"
-    unselected_img = "no-check-no-border.png"
-
-    def __init__(self, req, label, value, selected=False):
-        self._cw = req
-        self.label = label
-        self.value = value
-        self.selected = selected
-
-    def _render(self):
-        w = self.w
-        cssclass = 'facetValue facetCheckBox'
-        if self.selected:
-            cssclass += ' facetValueSelected'
-            imgsrc = self._cw.data_url(self.selected_img)
-            imgalt = self._cw._('selected')
-        else:
-            imgsrc = self._cw.data_url(self.unselected_img)
-            imgalt = self._cw._('not selected')
-        w(u'<div class="%s" cubicweb:value="%s">\n'
-          % (cssclass, xml_escape(unicode(self.value))))
-        w(u'<img src="%s" alt="%s"/>&#160;' % (imgsrc, imgalt))
-        w(u'<a href="javascript: {}">%s</a>' % xml_escape(self.label))
-        w(u'</div>')
-
-
 class CheckBoxFacetWidget(htmlwidgets.HTMLWidget):
     selected_img = "black-check.png"
     unselected_img = "black-uncheck.png"
@@ -1570,6 +1572,7 @@
         self.value = value
         self.selected = selected
 
+    @property
     def height(self):
         return 2
 
@@ -1588,9 +1591,9 @@
             imgalt = self._cw._('not selected')
         w(u'<div class="%s" cubicweb:value="%s">\n'
           % (cssclass, xml_escape(unicode(self.value))))
-        w(u'<div class="facetCheckBoxWidget">')
+        w(u'<div>')
         w(u'<img src="%s" alt="%s" cubicweb:unselimg="true" />&#160;' % (imgsrc, imgalt))
-        w(u'<label class="facetTitle" cubicweb:facetName="%s"><a href="javascript: {}">%s</a></label>'
+        w(u'<label class="facetTitle" cubicweb:facetName="%s">%s</label>'
           % (xml_escape(self.facet.__regid__), title))
         w(u'</div>\n')
         w(u'</div>\n')
--- a/web/formfields.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/formfields.py	Fri Oct 14 09:21:45 2011 +0200
@@ -1020,59 +1020,6 @@
         return list(self.fields)
 
 
-# relation vocabulary helper functions #########################################
-
-def relvoc_linkedto(entity, rtype, role):
-    # first see if its specified by __linkto form parameters
-    linkedto = entity.linked_to(rtype, role)
-    if linkedto:
-        buildent = entity._cw.entity_from_eid
-        return [(buildent(eid).view('combobox'), unicode(eid)) for eid in linkedto]
-    return []
-
-def relvoc_init(entity, rtype, role, required=False):
-    # it isn't, check if the entity provides a method to get correct values
-    vocab = []
-    if not required:
-        vocab.append(('', INTERNAL_FIELD_VALUE))
-    # vocabulary doesn't include current values, add them
-    if entity.has_eid():
-        rset = entity.related(rtype, role)
-        vocab += [(e.view('combobox'), unicode(e.eid)) for e in rset.entities()]
-    return vocab
-
-def relvoc_unrelated(entity, rtype, role, limit=None):
-    if isinstance(rtype, basestring):
-        rtype = entity._cw.vreg.schema.rschema(rtype)
-    if entity.has_eid():
-        done = set(row[0] for row in entity.related(rtype, role))
-    else:
-        done = None
-    result = []
-    rsetsize = None
-    for objtype in rtype.targets(entity.e_schema, role):
-        if limit is not None:
-            rsetsize = limit - len(result)
-        result += _relvoc_unrelated(entity, rtype, objtype, role, rsetsize, done)
-        if limit is not None and len(result) >= limit:
-            break
-    return result
-
-def _relvoc_unrelated(entity, rtype, targettype, role, limit, done):
-    """return unrelated entities for a given relation and target entity type
-    for use in vocabulary
-    """
-    if done is None:
-        done = set()
-    res = []
-    for entity in entity.unrelated(rtype, targettype, role, limit).entities():
-        if entity.eid in done:
-            continue
-        done.add(entity.eid)
-        res.append((entity.view('combobox'), unicode(entity.eid)))
-    return res
-
-
 class RelationField(Field):
     """Use this field to edit a relation of an entity.
 
@@ -1097,10 +1044,10 @@
         entity = form.edited_entity
         # first see if its specified by __linkto form parameters
         if limit is None:
-            linkedto = relvoc_linkedto(entity, self.name, self.role)
+            linkedto = self.relvoc_linkedto(form)
             if linkedto:
                 return linkedto
-            vocab = relvoc_init(entity, self.name, self.role, self.required)
+            vocab = self.relvoc_init(form)
         else:
             vocab = []
         # it isn't, check if the entity provides a method to get correct values
@@ -1110,22 +1057,63 @@
             warn('[3.6] found %s on %s, should override field.choices instead (need tweaks)'
                  % (method, form), DeprecationWarning)
         except AttributeError:
-            vocab += relvoc_unrelated(entity, self.name, self.role, limit)
+            vocab += self.relvoc_unrelated(form, limit)
         if self.sort:
             vocab = vocab_sort(vocab)
         return vocab
 
-    def form_init(self, form):
-        #if not self.display_value(form):
-        value = form.edited_entity.linked_to(self.name, self.role)
-        if value:
-            searchedvalues = ['%s:%s:%s' % (self.name, eid, self.role)
-                              for eid in value]
-            # remove associated __linkto hidden fields
-            for field in form.root_form.fields_by_name('__linkto'):
-                if field.value in searchedvalues:
-                    form.root_form.remove_field(field)
-            form.formvalues[(self, form)] = value
+    def relvoc_linkedto(self, form):
+        linkedto = form.linked_to.get((self.name, self.role))
+        if linkedto:
+            buildent = form._cw.entity_from_eid
+            return [(buildent(eid).view('combobox'), unicode(eid))
+                    for eid in linkedto]
+        return []
+
+    def relvoc_init(self, form):
+        entity, rtype, role = form.edited_entity, self.name, self.role
+        vocab = []
+        if not self.required:
+            vocab.append(('', INTERNAL_FIELD_VALUE))
+        # vocabulary doesn't include current values, add them
+        if form.edited_entity.has_eid():
+            rset = form.edited_entity.related(self.name, self.role)
+            vocab += [(e.view('combobox'), unicode(e.eid))
+                      for e in rset.entities()]
+        return vocab
+
+    def relvoc_unrelated(self, form, limit=None):
+        entity = form.edited_entity
+        rtype = entity._cw.vreg.schema.rschema(self.name)
+        if entity.has_eid():
+            done = set(row[0] for row in entity.related(rtype, self.role))
+        else:
+            done = None
+        result = []
+        rsetsize = None
+        for objtype in rtype.targets(entity.e_schema, self.role):
+            if limit is not None:
+                rsetsize = limit - len(result)
+            result += self._relvoc_unrelated(form, objtype, rsetsize, done)
+            if limit is not None and len(result) >= limit:
+                break
+        return result
+
+    def _relvoc_unrelated(self, form, targettype, limit, done):
+        """return unrelated entities for a given relation and target entity type
+        for use in vocabulary
+        """
+        if done is None:
+            done = set()
+        res = []
+        entity = form.edited_entity
+        for entity in entity.unrelated(self.name, targettype,
+                                       self.role, limit).entities():
+            if entity.eid in done:
+                continue
+            done.add(entity.eid)
+            res.append((entity.view('combobox'), unicode(entity.eid)))
+        return res
 
     def format_single_value(self, req, value):
         return unicode(value)
--- a/web/request.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/request.py	Fri Oct 14 09:21:45 2011 +0200
@@ -94,7 +94,7 @@
             self.uiprops = vreg.config.uiprops
             self.datadir_url = vreg.config.datadir_url
         # raw html headers that can be added from any view
-        self.html_headers = HTMLHead(self.datadir_url)
+        self.html_headers = HTMLHead(self)
         # form parameters
         self.setup_params(form)
         # dictionnary that may be used to store request data that has to be
@@ -264,7 +264,7 @@
         """used by AutomaticWebTest to clear html headers between tests on
         the same resultset
         """
-        self.html_headers = HTMLHead(self.datadir_url)
+        self.html_headers = HTMLHead(self)
         return self
 
     # web state helpers #######################################################
--- a/web/test/test_views.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/test/test_views.py	Fri Oct 14 09:21:45 2011 +0200
@@ -52,10 +52,10 @@
     def test_sortable_js_added(self):
         rset = self.execute('CWUser X')
         # sortable.js should not be included by default
-        self.failIf('jquery.tablesorter.js' in self.view('oneline', rset))
+        self.assertFalse('jquery.tablesorter.js' in self.view('oneline', rset))
         # but should be included by the tableview
         rset = self.execute('Any P,F,S LIMIT 1 WHERE P is CWUser, P firstname F, P surname S')
-        self.failUnless('jquery.tablesorter.js' in self.view('table', rset))
+        self.assertTrue('jquery.tablesorter.js' in self.view('table', rset))
 
     def test_js_added_only_once(self):
         self.vreg._loadedmods[__name__] = {}
--- a/web/test/unittest_application.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/test/unittest_application.py	Fri Oct 14 09:21:45 2011 +0200
@@ -31,6 +31,7 @@
 from cubicweb.devtools.fake import FakeRequest
 from cubicweb.web import LogOut, Redirect, INTERNAL_FIELD_VALUE
 from cubicweb.web.views.basecontrollers import ViewController
+from cubicweb.web.application import anonymized_request
 
 class FakeMapping:
     """emulates a mapping module"""
@@ -274,8 +275,8 @@
     def _test_cleaned(self, kwargs, injected, cleaned):
         req = self.request(**kwargs)
         page = self.app.publish('view', req)
-        self.failIf(injected in page, (kwargs, injected))
-        self.failUnless(cleaned in page, (kwargs, cleaned))
+        self.assertFalse(injected in page, (kwargs, injected))
+        self.assertTrue(cleaned in page, (kwargs, cleaned))
 
     def test_nonregr_script_kiddies(self):
         """test against current script injection"""
@@ -321,9 +322,9 @@
         origcnx = req.cnx
         req.form['__fblogin'] = u'turlututu'
         page = self.app_publish(req)
-        self.failIf(req.cnx is origcnx)
+        self.assertFalse(req.cnx is origcnx)
         self.assertEqual(req.user.login, 'turlututu')
-        self.failUnless('turlututu' in page, page)
+        self.assertTrue('turlututu' in page, page)
         req.cnx.close() # avoid warning
 
     # authentication tests ####################################################
@@ -343,8 +344,8 @@
         req, origsession = self.init_authentication('cookie')
         self.assertAuthFailure(req)
         form = self.app_publish(req, 'login')
-        self.failUnless('__login' in form)
-        self.failUnless('__password' in form)
+        self.assertTrue('__login' in form)
+        self.assertTrue('__password' in form)
         self.assertEqual(req.cnx, None)
         req.form['__login'] = self.admlogin
         req.form['__password'] = self.admpassword
@@ -389,7 +390,7 @@
         asession = req.session
         self.assertEqual(len(self.open_sessions), 1)
         self.assertEqual(asession.login, 'anon')
-        self.failUnless(asession.anonymous_session)
+        self.assertTrue(asession.anonymous_session)
         self._reset_cookie(req)
 
     def _test_anon_auth_fail(self, req):
@@ -424,6 +425,18 @@
         self.assertRaises(LogOut, self.app_publish, req, 'logout')
         self.assertEqual(len(self.open_sessions), 0)
 
+    def test_anonymized_request(self):
+        req = self.request()
+        self.assertEqual(req.session.login, self.admlogin)
+        # admin should see anon + admin
+        self.assertEqual(len(list(req.find_entities('CWUser'))), 2)
+        with anonymized_request(req):
+            self.assertEqual(req.session.login, 'anon')
+            # anon should only see anon user
+            self.assertEqual(len(list(req.find_entities('CWUser'))), 1)
+        self.assertEqual(req.session.login, self.admlogin)
+        self.assertEqual(len(list(req.find_entities('CWUser'))), 2)
+
     def test_non_regr_optional_first_var(self):
         req = self.request()
         # expect a rset with None in [0][0]
--- a/web/test/unittest_form.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/test/unittest_form.py	Fri Oct 14 09:21:45 2011 +0200
@@ -64,15 +64,15 @@
         t = self.req.create_entity('Tag', name=u'x')
         form1 = self.vreg['forms'].select('edition', self.req, entity=t)
         unrelated = [reid for rview, reid in form1.field_by_name('tags', 'subject', t.e_schema).choices(form1)]
-        self.failUnless(unicode(b.eid) in unrelated, unrelated)
+        self.assertTrue(unicode(b.eid) in unrelated, unrelated)
         form2 = self.vreg['forms'].select('edition', self.req, entity=b)
         unrelated = [reid for rview, reid in form2.field_by_name('tags', 'object', t.e_schema).choices(form2)]
-        self.failUnless(unicode(t.eid) in unrelated, unrelated)
+        self.assertTrue(unicode(t.eid) in unrelated, unrelated)
         self.execute('SET X tags Y WHERE X is Tag, Y is BlogEntry')
         unrelated = [reid for rview, reid in form1.field_by_name('tags', 'subject', t.e_schema).choices(form1)]
-        self.failIf(unicode(b.eid) in unrelated, unrelated)
+        self.assertFalse(unicode(b.eid) in unrelated, unrelated)
         unrelated = [reid for rview, reid in form2.field_by_name('tags', 'object', t.e_schema).choices(form2)]
-        self.failIf(unicode(t.eid) in unrelated, unrelated)
+        self.assertFalse(unicode(t.eid) in unrelated, unrelated)
 
 
     def test_form_field_vocabulary_new_entity(self):
@@ -110,14 +110,14 @@
                 ok = True
         self.assertEqual(ok, True, 'expected option not found')
         inputs = pageinfo.find_tag('input', False)
-        self.failIf(list(pageinfo.matching_nodes('input', name='__linkto')))
+        self.assertFalse(list(pageinfo.matching_nodes('input', name='__linkto')))
 
     def test_reledit_composite_field(self):
         rset = self.execute('INSERT BlogEntry X: X title "cubicweb.org", X content "hop"')
         form = self.vreg['views'].select('reledit', self.request(),
                                          rset=rset, row=0, rtype='content')
         data = form.render(row=0, rtype='content', formid='base', action='edit_rtype')
-        self.failUnless('content_format' in data)
+        self.assertTrue('content_format' in data)
 
     # form view tests #########################################################
 
--- a/web/test/unittest_propertysheet.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/test/unittest_propertysheet.py	Fri Oct 14 09:21:45 2011 +0200
@@ -35,19 +35,19 @@
                           'a {bgcolor: #FFFFFF; size: 1%;}')
         self.assertEqual(ps.process_resource(DATADIR, 'pouet.css'),
                           CACHEDIR)
-        self.failUnless('pouet.css' in ps._cache)
-        self.failIf(ps.need_reload())
+        self.assertTrue('pouet.css' in ps._cache)
+        self.assertFalse(ps.need_reload())
         os.utime(join(DATADIR, 'sheet1.py'), None)
-        self.failUnless('pouet.css' in ps._cache)
-        self.failUnless(ps.need_reload())
-        self.failUnless('pouet.css' in ps._cache)
+        self.assertTrue('pouet.css' in ps._cache)
+        self.assertTrue(ps.need_reload())
+        self.assertTrue('pouet.css' in ps._cache)
         ps.reload()
-        self.failIf('pouet.css' in ps._cache)
-        self.failIf(ps.need_reload())
+        self.assertFalse('pouet.css' in ps._cache)
+        self.assertFalse(ps.need_reload())
         ps.process_resource(DATADIR, 'pouet.css') # put in cache
         os.utime(join(DATADIR, 'pouet.css'), None)
-        self.failIf(ps.need_reload())
-        self.failIf('pouet.css' in ps._cache)
+        self.assertFalse(ps.need_reload())
+        self.assertFalse('pouet.css' in ps._cache)
 
 if __name__ == '__main__':
     unittest_main()
--- a/web/test/unittest_uicfg.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/test/unittest_uicfg.py	Fri Oct 14 09:21:45 2011 +0200
@@ -24,7 +24,7 @@
 class UICFGTC(CubicWebTC):
 
     def test_default_actionbox_appearsin_addmenu_config(self):
-        self.failIf(abaa.etype_get('TrInfo', 'wf_info_for', 'object', 'CWUser'))
+        self.assertFalse(abaa.etype_get('TrInfo', 'wf_info_for', 'object', 'CWUser'))
 
 
 
--- a/web/test/unittest_urlpublisher.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/test/unittest_urlpublisher.py	Fri Oct 14 09:21:45 2011 +0200
@@ -69,35 +69,35 @@
         self.assertEqual(ctrl, 'view')
         self.assertEqual(len(rset), 1)
         self.assertEqual(rset.description[0][0], 'CWUser')
-        self.assertEqual(rset.printable_rql(), 'Any X,AA,AB,AC,AD WHERE X login "admin", X is CWUser, X login AA, X firstname AB, X surname AC, X modification_date AD')
+        self.assertEqual(rset.printable_rql(), 'Any X,AA,AB,AC,AD WHERE X is CWUser, X login AA, X firstname AB, X surname AC, X modification_date AD, X login "admin"')
 
     def test_rest_path_unique_attr(self):
         ctrl, rset = self.process('cwuser/admin')
         self.assertEqual(ctrl, 'view')
         self.assertEqual(len(rset), 1)
         self.assertEqual(rset.description[0][0], 'CWUser')
-        self.assertEqual(rset.printable_rql(), 'Any X,AA,AB,AC,AD WHERE X login "admin", X is CWUser, X login AA, X firstname AB, X surname AC, X modification_date AD')
+        self.assertEqual(rset.printable_rql(), 'Any X,AA,AB,AC,AD WHERE X is CWUser, X login AA, X firstname AB, X surname AC, X modification_date AD, X login "admin"')
 
     def test_rest_path_eid(self):
         ctrl, rset = self.process('cwuser/eid/%s' % self.user().eid)
         self.assertEqual(ctrl, 'view')
         self.assertEqual(len(rset), 1)
         self.assertEqual(rset.description[0][0], 'CWUser')
-        self.assertEqual(rset.printable_rql(), 'Any X,AA,AB,AC,AD WHERE X eid %s, X is CWUser, X login AA, X firstname AB, X surname AC, X modification_date AD' % rset[0][0])
+        self.assertEqual(rset.printable_rql(), 'Any X,AA,AB,AC,AD WHERE X is CWUser, X login AA, X firstname AB, X surname AC, X modification_date AD, X eid %s' % rset[0][0])
 
     def test_rest_path_non_ascii_paths(self):
         ctrl, rset = self.process('CWUser/login/%C3%BFsa%C3%BFe')
         self.assertEqual(ctrl, 'view')
         self.assertEqual(len(rset), 1)
         self.assertEqual(rset.description[0][0], 'CWUser')
-        self.assertEqual(rset.printable_rql(), u'Any X,AA,AB,AC,AD WHERE X login "\xffsa\xffe", X is CWUser, X login AA, X firstname AB, X surname AC, X modification_date AD')
+        self.assertEqual(rset.printable_rql(), u'Any X,AA,AB,AC,AD WHERE X is CWUser, X login AA, X firstname AB, X surname AC, X modification_date AD, X login "\xffsa\xffe"')
 
     def test_rest_path_quoted_paths(self):
         ctrl, rset = self.process('BlogEntry/title/hell%27o')
         self.assertEqual(ctrl, 'view')
         self.assertEqual(len(rset), 1)
         self.assertEqual(rset.description[0][0], 'BlogEntry')
-        self.assertEqual(rset.printable_rql(), u'Any X,AA,AB,AC WHERE X title "hell\'o", X is BlogEntry, X creation_date AA, X title AB, X modification_date AC')
+        self.assertEqual(rset.printable_rql(), u'Any X,AA,AB,AC WHERE X is BlogEntry, X creation_date AA, X title AB, X modification_date AC, X title "hell\'o"')
 
     def test_rest_path_errors(self):
         self.assertRaises(NotFound, self.process, 'CWUser/eid/30000')
--- a/web/test/unittest_urlrewrite.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/test/unittest_urlrewrite.py	Fri Oct 14 09:21:45 2011 +0200
@@ -1,4 +1,4 @@
-# copyright 2003-2010 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
+# copyright 2003-2011 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
 # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
 #
 # This file is part of CubicWeb.
@@ -15,9 +15,6 @@
 #
 # You should have received a copy of the GNU Lesser General Public License along
 # with CubicWeb.  If not, see <http://www.gnu.org/licenses/>.
-"""
-
-"""
 from logilab.common.testlib import TestCase, unittest_main
 
 from cubicweb.devtools.testlib import CubicWebTC
@@ -53,7 +50,10 @@
             ('/error', dict(vid='error')),
             ('/sparql', dict(vid='sparql')),
             ('/processinfo', dict(vid='processinfo')),
-            ('/cwuser$', {'vid': 'cw.user-management'}),
+            ('/cwuser$', {'vid': 'cw.users-and-groups-management',
+                          'tab': 'cw_users_management'}),
+            ('/cwgroup$', {'vid': 'cw.users-and-groups-management',
+                           'tab': 'cw_groups_management'}),
             ('/cwsource$', {'vid': 'cw.source-management'}),
             ('/schema/([^/]+?)/?$', {'rql': r'Any X WHERE X is CWEType, X name "\1"', 'vid': 'primary'}),
             ('/add/([^/]+?)/?$' , dict(vid='creation', etype=r'\1')),
--- a/web/test/unittest_views_actions.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/test/unittest_views_actions.py	Fri Oct 14 09:21:45 2011 +0200
@@ -34,12 +34,12 @@
         req = self.request()
         rset = self.execute('Any X WHERE X login "admin"', req=req)
         actions = self.vreg['actions'].poss_visible_objects(req, rset=rset)
-        self.failUnless([action for action in actions if action.__regid__ == 'sendemail'])
+        self.assertTrue([action for action in actions if action.__regid__ == 'sendemail'])
         self.login('anon')
         req = self.request()
         rset = self.execute('Any X WHERE X login "anon"', req=req)
         actions = self.vreg['actions'].poss_visible_objects(req, rset=rset)
-        self.failIf([action for action in actions if action.__regid__ == 'sendemail'])
+        self.assertFalse([action for action in actions if action.__regid__ == 'sendemail'])
 
 if __name__ == '__main__':
     unittest_main()
--- a/web/test/unittest_views_basecontrollers.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/test/unittest_views_basecontrollers.py	Fri Oct 14 09:21:45 2011 +0200
@@ -40,11 +40,11 @@
 class EditControllerTC(CubicWebTC):
     def setUp(self):
         CubicWebTC.setUp(self)
-        self.failUnless('users' in self.schema.eschema('CWGroup').get_groups('read'))
+        self.assertTrue('users' in self.schema.eschema('CWGroup').get_groups('read'))
 
     def tearDown(self):
         CubicWebTC.tearDown(self)
-        self.failUnless('users' in self.schema.eschema('CWGroup').get_groups('read'))
+        self.assertTrue('users' in self.schema.eschema('CWGroup').get_groups('read'))
 
     def test_noparam_edit(self):
         """check behaviour of this controller without any form parameter
@@ -107,7 +107,7 @@
         path, params = self.expect_redirect_publish(req, 'edit')
         cnx.commit() # commit to check we don't get late validation error for instance
         self.assertEqual(path, 'cwuser/user')
-        self.failIf('vid' in params)
+        self.assertFalse('vid' in params)
 
     def test_user_editing_itself_no_relation(self):
         """checking we can edit an entity without specifying some required
@@ -308,7 +308,7 @@
             '__action_apply': '',
             }
         path, params = self.expect_redirect_publish(req, 'edit')
-        self.failUnless(path.startswith('blogentry/'))
+        self.assertTrue(path.startswith('blogentry/'))
         eid = path.split('/')[1]
         self.assertEqual(params['vid'], 'edition')
         self.assertNotEqual(int(eid), 4012)
@@ -365,6 +365,43 @@
         self.assertEqual(path, 'view')
         self.assertIn('_cwmsgid', params)
 
+    def test_simple_copy(self):
+        req = self.request()
+        blog = req.create_entity('Blog', title=u'my-blog')
+        blogentry = req.create_entity('BlogEntry', title=u'entry1',
+                                      content=u'content1', entry_of=blog)
+        req = self.request()
+        req.form = {'__maineid' : 'X', 'eid': 'X',
+                    '__cloned_eid:X': blogentry.eid, '__type:X': 'BlogEntry',
+                    '_cw_entity_fields:X': 'title-subject,content-subject',
+                    'title-subject:X': u'entry1-copy',
+                    'content-subject:X': u'content1',
+                    }
+        self.expect_redirect_publish(req, 'edit')
+        blogentry2 = req.find_one_entity('BlogEntry', title=u'entry1-copy')
+        self.assertEqual(blogentry2.entry_of[0].eid, blog.eid)
+
+    def test_skip_copy_for(self):
+        req = self.request()
+        blog = req.create_entity('Blog', title=u'my-blog')
+        blogentry = req.create_entity('BlogEntry', title=u'entry1',
+                                      content=u'content1', entry_of=blog)
+        blogentry.__class__.cw_skip_copy_for = [('entry_of', 'subject')]
+        try:
+            req = self.request()
+            req.form = {'__maineid' : 'X', 'eid': 'X',
+                        '__cloned_eid:X': blogentry.eid, '__type:X': 'BlogEntry',
+                        '_cw_entity_fields:X': 'title-subject,content-subject',
+                        'title-subject:X': u'entry1-copy',
+                        'content-subject:X': u'content1',
+                        }
+            self.expect_redirect_publish(req, 'edit')
+            blogentry2 = req.find_one_entity('BlogEntry', title=u'entry1-copy')
+            # entry_of should not be copied
+            self.assertEqual(len(blogentry2.entry_of), 0)
+        finally:
+            blogentry.__class__.cw_skip_copy_for = []
+
     def test_nonregr_eetype_etype_editing(self):
         """non-regression test checking that a manager user can edit a CWEType entity
         """
@@ -405,7 +442,7 @@
             'title-subject:A': u'"13:03:40"',
             'content-subject:A': u'"13:03:43"',}
         path, params = self.expect_redirect_publish(req, 'edit')
-        self.failUnless(path.startswith('blogentry/'))
+        self.assertTrue(path.startswith('blogentry/'))
         eid = path.split('/')[1]
         e = self.execute('Any C, T WHERE C eid %(x)s, C content T', {'x': eid}).get_entity(0, 0)
         self.assertEqual(e.title, '"13:03:40"')
@@ -541,12 +578,12 @@
         rset = self.john.as_rset()
         rset.req = req
         source = ctrl.publish()
-        self.failUnless(source.startswith('<?xml version="1.0"?>\n' + STRICT_DOCTYPE +
+        self.assertTrue(source.startswith('<?xml version="1.0"?>\n' + STRICT_DOCTYPE +
                                           u'<div xmlns="http://www.w3.org/1999/xhtml" xmlns:cubicweb="http://www.logilab.org/2008/cubicweb">')
                         )
         req.xhtml_browser = lambda: False
         source = ctrl.publish()
-        self.failUnless(source.startswith('<div>'))
+        self.assertTrue(source.startswith('<div>'))
 
 #     def test_json_exec(self):
 #         rql = 'Any T,N WHERE T is Tag, T name N'
--- a/web/test/unittest_views_editforms.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/test/unittest_views_editforms.py	Fri Oct 14 09:21:45 2011 +0200
@@ -95,9 +95,9 @@
                                       ]))
 
     def test_inlined_view(self):
-        self.failUnless('main_inlined' in AFS.etype_get('CWUser', 'use_email', 'subject', 'EmailAddress'))
-        self.failIf('main_inlined' in AFS.etype_get('CWUser', 'primary_email', 'subject', 'EmailAddress'))
-        self.failUnless('main_relations' in AFS.etype_get('CWUser', 'primary_email', 'subject', 'EmailAddress'))
+        self.assertTrue('main_inlined' in AFS.etype_get('CWUser', 'use_email', 'subject', 'EmailAddress'))
+        self.assertFalse('main_inlined' in AFS.etype_get('CWUser', 'primary_email', 'subject', 'EmailAddress'))
+        self.assertTrue('main_relations' in AFS.etype_get('CWUser', 'primary_email', 'subject', 'EmailAddress'))
 
     def test_personne_relations_by_category(self):
         e = self.vreg['etypes'].etype_class('Personne')(self.request())
@@ -142,7 +142,7 @@
         # should be also selectable by specifying entity
         self.vreg['forms'].select('edition', rset.req,
                          entity=rset.get_entity(0, 0))
-        self.failIf(any(f for f in form.fields if f is None))
+        self.assertFalse(any(f for f in form.fields if f is None))
 
 
 class FormViewsTC(CubicWebTC):
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/web/test/unittest_views_json.py	Fri Oct 14 09:21:45 2011 +0200
@@ -0,0 +1,46 @@
+from cubicweb.devtools.testlib import CubicWebTC
+
+from json import loads
+
+class JsonViewsTC(CubicWebTC):
+
+    def test_json_rsetexport(self):
+        req = self.request()
+        rset = req.execute('Any GN,COUNT(X) GROUPBY GN ORDERBY GN WHERE X in_group G, G name GN')
+        data = self.view('jsonexport', rset)
+        self.assertEqual(req.headers_out.getRawHeaders('content-type'), ['application/json'])
+        self.assertEqual(data, '[["guests", 1], ["managers", 1]]')
+
+    def test_json_rsetexport_with_jsonp(self):
+        req = self.request()
+        req.form.update({'callback': 'foo',
+                         'rql': 'Any GN,COUNT(X) GROUPBY GN ORDERBY GN WHERE X in_group G, G name GN',
+                         })
+        data = self.ctrl_publish(req, ctrl='jsonp')
+        self.assertEqual(req.headers_out.getRawHeaders('content-type'), ['application/javascript'])
+        # because jsonp anonymizes data, only 'guests' group should be found
+        self.assertEqual(data, 'foo([["guests", 1]])')
+
+    def test_json_rsetexport_with_jsonp_and_bad_vid(self):
+        req = self.request()
+        req.form.update({'callback': 'foo',
+                         'vid': 'table', # <-- this parameter should be ignored by jsonp controller
+                         'rql': 'Any GN,COUNT(X) GROUPBY GN ORDERBY GN WHERE X in_group G, G name GN',
+                         })
+        data = self.ctrl_publish(req, ctrl='jsonp')
+        self.assertEqual(req.headers_out.getRawHeaders('content-type'), ['application/javascript'])
+        # result should be plain json, not the table view
+        self.assertEqual(data, 'foo([["guests", 1]])')
+
+    def test_json_ersetexport(self):
+        req = self.request()
+        rset = req.execute('Any G ORDERBY GN WHERE G is CWGroup, G name GN')
+        data = loads(self.view('ejsonexport', rset))
+        self.assertEqual(req.headers_out.getRawHeaders('content-type'), ['application/json'])
+        self.assertEqual(data[0]['name'], 'guests')
+        self.assertEqual(data[1]['name'], 'managers')
+
+
+if __name__ == '__main__':
+    from logilab.common.testlib import unittest_main
+    unittest_main()
--- a/web/test/unittest_views_navigation.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/test/unittest_views_navigation.py	Fri Oct 14 09:21:45 2011 +0200
@@ -126,12 +126,12 @@
     #         req, rset=rset, view=view, context='navtop')
     #     # breadcrumbs should be in headers by default
     #     clsids = set(obj.id for obj in objs)
-    #     self.failUnless('breadcrumbs' in clsids)
+    #     self.assertTrue('breadcrumbs' in clsids)
     #     objs = self.vreg['ctxcomponents'].poss_visible_objects(
     #         req, rset=rset, view=view, context='navbottom')
     #     # breadcrumbs should _NOT_ be in footers by default
     #     clsids = set(obj.id for obj in objs)
-    #     self.failIf('breadcrumbs' in clsids)
+    #     self.assertFalse('breadcrumbs' in clsids)
     #     self.execute('INSERT CWProperty P: P pkey "ctxcomponents.breadcrumbs.context", '
     #                  'P value "navbottom"')
     #     # breadcrumbs should now be in footers
@@ -140,12 +140,12 @@
     #         req, rset=rset, view=view, context='navbottom')
 
     #     clsids = [obj.id for obj in objs]
-    #     self.failUnless('breadcrumbs' in clsids)
+    #     self.assertTrue('breadcrumbs' in clsids)
     #     objs = self.vreg['ctxcomponents'].poss_visible_objects(
     #         req, rset=rset, view=view, context='navtop')
 
     #     clsids = [obj.id for obj in objs]
-    #     self.failIf('breadcrumbs' in clsids)
+    #     self.assertFalse('breadcrumbs' in clsids)
 
 
 if __name__ == '__main__':
--- a/web/test/unittest_viewselector.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/test/unittest_viewselector.py	Fri Oct 14 09:21:45 2011 +0200
@@ -91,7 +91,7 @@
         self.assertListEqual(self.pviews(req, None),
                              [('changelog', wdoc.ChangeLogView),
                               ('cw.source-management', cwsources.CWSourceManagementView),
-                              ('cw.user-management', cwuser.CWUserManagementView),
+                              ('cw.users-and-groups-management', cwuser.UsersAndGroupsManagementView),
                               ('gc', debug.GCView),
                               ('index', startup.IndexView),
                               ('info', debug.ProcessInformationView),
@@ -163,9 +163,9 @@
         req2 = self.request()
         rset1 = req1.execute('CWUser X WHERE X login "admin"')
         rset2 = req2.execute('CWUser X WHERE X login "anon"')
-        self.failUnless(self.vreg['views'].select('propertiesform', req1, rset=None))
-        self.failUnless(self.vreg['views'].select('propertiesform', req1, rset=rset1))
-        self.failUnless(self.vreg['views'].select('propertiesform', req2, rset=rset2))
+        self.assertTrue(self.vreg['views'].select('propertiesform', req1, rset=None))
+        self.assertTrue(self.vreg['views'].select('propertiesform', req1, rset=rset1))
+        self.assertTrue(self.vreg['views'].select('propertiesform', req2, rset=rset2))
 
     def test_propertiesform_anon(self):
         self.login('anon')
@@ -184,9 +184,9 @@
         req2 = self.request()
         rset1 = req1.execute('CWUser X WHERE X login "admin"')
         rset2 = req2.execute('CWUser X WHERE X login "jdoe"')
-        self.failUnless(self.vreg['views'].select('propertiesform', req1, rset=None))
+        self.assertTrue(self.vreg['views'].select('propertiesform', req1, rset=None))
         self.assertRaises(NoSelectableObject, self.vreg['views'].select, 'propertiesform', req1, rset=rset1)
-        self.failUnless(self.vreg['views'].select('propertiesform', req2, rset=rset2))
+        self.assertTrue(self.vreg['views'].select('propertiesform', req2, rset=rset2))
 
     def test_possible_views_multiple_different_types(self):
         req = self.request()
@@ -225,7 +225,7 @@
         rset = req.execute('CWUser X')
         self.assertListEqual(self.pviews(req, rset),
                              [('csvexport', csvexport.CSVRsetView),
-                              ('cw.user-table', cwuser.CWUserTable),
+                              ('cw.users-table', cwuser.CWUsersTable),
                               ('ecsvexport', csvexport.CSVEntityView),
                               ('editable-table', tableview.EditableTableView),
                               ('filetree', treeview.FileTreeView),
@@ -340,21 +340,21 @@
         req = self.request()
         self.assertIsInstance(self.vreg['views'].select('index', req, rset=rset),
                              startup.IndexView)
-        self.failUnlessRaises(NoSelectableObject,
+        self.assertRaises(NoSelectableObject,
                              self.vreg['views'].select, 'primary', req, rset=rset)
-        self.failUnlessRaises(NoSelectableObject,
+        self.assertRaises(NoSelectableObject,
                              self.vreg['views'].select, 'table', req, rset=rset)
 
         # no entity
         req = self.request()
         rset = req.execute('Any X WHERE X eid 999999')
-        self.failUnlessRaises(NoSelectableObject,
+        self.assertRaises(NoSelectableObject,
                               self.vreg['views'].select, 'index', req, rset=rset)
-        self.failUnlessRaises(NoSelectableObject,
+        self.assertRaises(NoSelectableObject,
                               self.vreg['views'].select, 'creation', req, rset=rset)
-        self.failUnlessRaises(NoSelectableObject,
+        self.assertRaises(NoSelectableObject,
                               self.vreg['views'].select, 'primary', req, rset=rset)
-        self.failUnlessRaises(NoSelectableObject,
+        self.assertRaises(NoSelectableObject,
                              self.vreg['views'].select, 'table', req, rset=rset)
         # one entity
         req = self.request()
@@ -367,9 +367,9 @@
                              editforms.EditionFormView)
         self.assertIsInstance(self.vreg['views'].select('table', req, rset=rset),
                              tableview.TableView)
-        self.failUnlessRaises(NoSelectableObject,
+        self.assertRaises(NoSelectableObject,
                               self.vreg['views'].select, 'creation', req, rset=rset)
-        self.failUnlessRaises(NoSelectableObject,
+        self.assertRaises(NoSelectableObject,
                               self.vreg['views'].select, 'index', req, rset=rset)
         # list of entities of the same type
         req = self.request()
@@ -380,7 +380,7 @@
                              baseviews.ListView)
         self.assertIsInstance(self.vreg['views'].select('table', req, rset=rset),
                              tableview.TableView)
-        self.failUnlessRaises(NoSelectableObject,
+        self.assertRaises(NoSelectableObject,
                               self.vreg['views'].select, 'creation', req, rset=rset)
         # list of entities of different types
         req = self.request()
@@ -391,31 +391,31 @@
                                   baseviews.ListView)
         self.assertIsInstance(self.vreg['views'].select('table', req, rset=rset),
                                   tableview.TableView)
-        self.failUnlessRaises(NoSelectableObject,
+        self.assertRaises(NoSelectableObject,
                              self.vreg['views'].select, 'creation', req, rset=rset)
-        self.failUnlessRaises(NoSelectableObject,
+        self.assertRaises(NoSelectableObject,
                               self.vreg['views'].select, 'index', req, rset=rset)
         # whatever
         req = self.request()
         rset = req.execute('Any N, X WHERE X in_group Y, Y name N')
         self.assertIsInstance(self.vreg['views'].select('table', req, rset=rset),
                                   tableview.TableView)
-        self.failUnlessRaises(NoSelectableObject,
+        self.assertRaises(NoSelectableObject,
                               self.vreg['views'].select, 'index', req, rset=rset)
-        self.failUnlessRaises(NoSelectableObject,
+        self.assertRaises(NoSelectableObject,
                               self.vreg['views'].select, 'creation', req, rset=rset)
-        self.failUnlessRaises(NoSelectableObject,
+        self.assertRaises(NoSelectableObject,
                              self.vreg['views'].select, 'primary', req, rset=rset)
-        self.failUnlessRaises(NoSelectableObject,
+        self.assertRaises(NoSelectableObject,
                              self.vreg['views'].select, 'list', req, rset=rset)
-        self.failUnlessRaises(NoSelectableObject,
+        self.assertRaises(NoSelectableObject,
                              self.vreg['views'].select, 'edition', req, rset=rset)
         # mixed query
         req = self.request()
         rset = req.execute('Any U,G WHERE U is CWUser, G is CWGroup')
-        self.failUnlessRaises(NoSelectableObject,
+        self.assertRaises(NoSelectableObject,
                               self.vreg['views'].select, 'edition', req, rset=rset)
-        self.failUnlessRaises(NoSelectableObject,
+        self.assertRaises(NoSelectableObject,
                               self.vreg['views'].select, 'creation', req, rset=rset)
         self.assertIsInstance(self.vreg['views'].select('table', req, rset=rset),
                               tableview.TableView)
--- a/web/test/unittest_web.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/test/unittest_web.py	Fri Oct 14 09:21:45 2011 +0200
@@ -34,8 +34,8 @@
         arurl = req.ajax_replace_url
         # NOTE: for the simplest use cases, we could use doctest
         url = arurl('foo', **kwargs)
-        self.failUnless(url.startswith('javascript:'))
-        self.failUnless(url.endswith('()'))
+        self.assertTrue(url.startswith('javascript:'))
+        self.assertTrue(url.endswith('()'))
         cbname = url.split()[1][:-2]
         self.assertMultiLineEqual(
             'function %s() { $("#foo").loadxhtml("http://testing.fr/cubicweb/json?%s",{"pageid": "%s"},"get","replace"); }' % (cbname, qs, req.pageid),
--- a/web/test/unittest_webconfig.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/test/unittest_webconfig.py	Fri Oct 14 09:21:45 2011 +0200
@@ -34,16 +34,16 @@
         """make sure PRINT_CSS *must* is a list"""
         config = self.config
         print_css = config.uiprops['STYLESHEETS_PRINT']
-        self.failUnless(isinstance(print_css, list))
+        self.assertTrue(isinstance(print_css, list))
         ie_css = config.uiprops['STYLESHEETS_IE']
-        self.failUnless(isinstance(ie_css, list))
+        self.assertTrue(isinstance(ie_css, list))
 
     def test_locate_resource(self):
-        self.failUnless('FILE_ICON' in self.config.uiprops)
+        self.assertTrue('FILE_ICON' in self.config.uiprops)
         rname = self.config.uiprops['FILE_ICON'].replace(self.config.datadir_url, '')
-        self.failUnless('file' in self.config.locate_resource(rname)[0].split(os.sep))
+        self.assertTrue('file' in self.config.locate_resource(rname)[0].split(os.sep))
         cubicwebcsspath = self.config.locate_resource('cubicweb.css')[0].split(os.sep)
-        self.failUnless('web' in cubicwebcsspath or 'shared' in cubicwebcsspath) # 'shared' if tests under apycot
+        self.assertTrue('web' in cubicwebcsspath or 'shared' in cubicwebcsspath) # 'shared' if tests under apycot
 
 if __name__ == '__main__':
     unittest_main()
--- a/web/views/actions.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/views/actions.py	Fri Oct 14 09:21:45 2011 +0200
@@ -182,15 +182,6 @@
     category = 'moreactions'
     order = 15
 
-    @classmethod
-    def __registered__(cls, reg):
-        if 'require_permission' in reg.schema:
-            cls.__select__ = (one_line_rset() & non_final_entity() &
-                              (match_user_groups('managers')
-                               | relation_possible('require_permission', 'subject', 'CWPermission',
-                                                   action='add')))
-        return super(ManagePermissionsAction, cls).__registered__(reg)
-
     def url(self):
         return self.cw_rset.get_entity(self.cw_row or 0, self.cw_col or 0).absolute_url(vid='security')
 
@@ -437,7 +428,6 @@
 ## default actions ui configuration ###########################################
 
 addmenu = uicfg.actionbox_appearsin_addmenu
-addmenu.tag_subject_of(('*', 'require_permission', '*'), False)
 addmenu.tag_object_of(('*', 'relation_type', 'CWRType'), True)
 addmenu.tag_object_of(('*', 'from_entity', 'CWEType'), False)
 addmenu.tag_object_of(('*', 'to_entity', 'CWEType'), False)
--- a/web/views/autoform.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/views/autoform.py	Fri Oct 14 09:21:45 2011 +0200
@@ -928,7 +928,6 @@
               'owned_by', 'created_by', 'cw_source'):
     _AFS.tag_subject_of(('*', rtype, '*'), 'main', 'metadata')
 
-_AFS.tag_subject_of(('*', 'require_permission', '*'), 'main', 'hidden')
 _AFS.tag_subject_of(('*', 'by_transition', '*'), 'main', 'attributes')
 _AFS.tag_subject_of(('*', 'by_transition', '*'), 'muledit', 'attributes')
 _AFS.tag_object_of(('*', 'by_transition', '*'), 'main', 'hidden')
@@ -937,8 +936,6 @@
 _AFS.tag_subject_of(('*', 'wf_info_for', '*'), 'main', 'attributes')
 _AFS.tag_subject_of(('*', 'wf_info_for', '*'), 'muledit', 'attributes')
 _AFS.tag_object_of(('*', 'wf_info_for', '*'), 'main', 'hidden')
-_AFS.tag_subject_of(('CWPermission', 'require_group', '*'), 'main', 'attributes')
-_AFS.tag_subject_of(('CWPermission', 'require_group', '*'), 'muledit', 'attributes')
 _AFS.tag_attribute(('CWEType', 'final'), 'main', 'hidden')
 _AFS.tag_attribute(('CWRType', 'final'), 'main', 'hidden')
 _AFS.tag_attribute(('CWUser', 'firstname'), 'main', 'attributes')
--- a/web/views/baseviews.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/views/baseviews.py	Fri Oct 14 09:21:45 2011 +0200
@@ -89,7 +89,7 @@
 from cubicweb.selectors import yes, empty_rset, one_etype_rset, match_kwargs
 from cubicweb.schema import display_name
 from cubicweb.view import EntityView, AnyRsetView, View
-from cubicweb.uilib import cut, printable_value
+from cubicweb.uilib import cut
 from cubicweb.web.views import calendar
 
 
@@ -132,65 +132,25 @@
     though usually dedicated for cells containing an attribute's value.
     """
     __regid__ = 'final'
-    # record generated i18n catalog messages
-    _('%d&#160;years')
-    _('%d&#160;months')
-    _('%d&#160;weeks')
-    _('%d&#160;days')
-    _('%d&#160;hours')
-    _('%d&#160;minutes')
-    _('%d&#160;seconds')
-    _('%d years')
-    _('%d months')
-    _('%d weeks')
-    _('%d days')
-    _('%d hours')
-    _('%d minutes')
-    _('%d seconds')
 
     def cell_call(self, row, col, props=None, format='text/html'):
-        etype = self.cw_rset.description[row][col]
         value = self.cw_rset.rows[row][col]
-
         if value is None:
             self.w(u'')
             return
+        etype = self.cw_rset.description[row][col]
         if etype == 'String':
             entity, rtype = self.cw_rset.related_entity(row, col)
             if entity is not None:
-                # yes !
+                # call entity's printable_value which may have more information
+                # about string format & all
                 self.w(entity.printable_value(rtype, value, format=format))
                 return
-        elif etype in ('Time', 'Interval'):
-            if etype == 'Interval' and isinstance(value, (int, long)):
-                # `date - date`, unlike `datetime - datetime` gives an int
-                # (number of days), not a timedelta
-                # XXX should rql be fixed to return Int instead of Interval in
-                #     that case? that would be probably the proper fix but we
-                #     loose information on the way...
-                value = timedelta(days=value)
-            # value is DateTimeDelta but we have no idea about what is the
-            # reference date here, so we can only approximate years and months
-            if format == 'text/html':
-                space = '&#160;'
-            else:
-                space = ' '
-            if value.days > 730: # 2 years
-                self.w(self._cw.__('%%d%syears' % space) % (value.days // 365))
-            elif value.days > 60: # 2 months
-                self.w(self._cw.__('%%d%smonths' % space) % (value.days // 30))
-            elif value.days > 14: # 2 weeks
-                self.w(self._cw.__('%%d%sweeks' % space) % (value.days // 7))
-            elif value.days > 2:
-                self.w(self._cw.__('%%d%sdays' % space) % int(value.days))
-            elif value.seconds > 3600:
-                self.w(self._cw.__('%%d%shours' % space) % int(value.seconds // 3600))
-            elif value.seconds >= 120:
-                self.w(self._cw.__('%%d%sminutes' % space) % int(value.seconds // 60))
-            else:
-                self.w(self._cw.__('%%d%sseconds' % space) % int(value.seconds))
-            return
-        self.wdata(printable_value(self._cw, etype, value, props))
+        value = self._cw.printable_value(etype, value, props)
+        if etype in ('Time', 'Interval'):
+            self.w(value.replace(' ', '&#160;'))
+        else:
+            self.wdata(value)
 
 
 class InContextView(EntityView):
--- a/web/views/cwproperties.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/views/cwproperties.py	Fri Oct 14 09:21:45 2011 +0200
@@ -112,72 +112,18 @@
         self._cw.add_js(('cubicweb.preferences.js',
                          'cubicweb.edition.js', 'cubicweb.ajax.js'))
         self._cw.add_css('cubicweb.preferences.css')
-        vreg = self._cw.vreg
         values = self.defined_keys
-        groupedopts = {}
-        mainopts = {}
-        # "self.id=='systempropertiesform'" to skip site wide properties on
-        # user's preference but not site's configuration
-        for key in vreg.user_property_keys(self.__regid__=='systempropertiesform'):
-            parts = key.split('.')
-            if parts[0] in vreg and len(parts) >= 3:
-                # appobject configuration
-                reg = parts[0]
-                propid = parts[-1]
-                oid = '.'.join(parts[1:-1])
-                groupedopts.setdefault(reg, {}).setdefault(oid, []).append(key)
-            else:
-                mainopts.setdefault(parts[0], []).append(key)
-        # precompute form to consume error message
-        for group, keys in mainopts.items():
-            mainopts[group] = self.form(group, keys, False)
-
-        for group, objects in groupedopts.items():
-            for oid, keys in objects.items():
-                groupedopts[group][oid] = self.form(group + '_' + oid, keys, True)
-
-        w = self.w
-        req = self._cw
-        _ = req._
-        w(u'<h1>%s</h1>\n' % _(self.title))
+        mainopts, groupedopts = self.group_properties()
+        # precompute all forms first to consume error message
+        mainforms, groupedforms = self.build_forms(mainopts, groupedopts)
+        _ = self._cw._
+        self.w(u'<h1>%s</h1>\n' % _(self.title))
         for label, group, form in sorted((_(g), g, f)
-                                         for g, f in mainopts.iteritems()):
-            status = css_class(self._group_status(group))
-            w(u'<div class="propertiesform">%s</div>\n' %
-            (make_togglable_link('fieldset_' + group, label.capitalize())))
-            w(u'<div id="fieldset_%s" %s>' % (group, status))
-            w(u'<fieldset class="preferences">')
-            w(form)
-            w(u'</fieldset></div>')
-
+                                         for g, f in mainforms.iteritems()):
+            self.wrap_main_form(group, label, form)
         for label, group, objects in sorted((_(g), g, o)
-                                            for g, o in groupedopts.iteritems()):
-            status = css_class(self._group_status(group))
-            w(u'<div class="propertiesform">%s</div>\n' %
-              (make_togglable_link('fieldset_' + group, label.capitalize())))
-            w(u'<div id="fieldset_%s" %s>' % (group, status))
-            # create selection
-            sorted_objects =  sorted((self._cw.__('%s_%s' % (group, o)), o, f)
-                                           for o, f in objects.iteritems())
-            for label, oid, form in sorted_objects:
-                w(u'<div class="component">')
-                w(u'''<div class="componentLink"><a href="javascript:$.noop();"
-                           onclick="javascript:toggleVisibility('field_%(oid)s_%(group)s')"
-                           class="componentTitle">%(label)s</a>''' % {'label':label, 'oid':oid, 'group':group})
-                w(u''' (<div class="openlink"><a href="javascript:$.noop();"
-                             onclick="javascript:openFieldset('fieldset_%(group)s')">%(label)s</a></div>)'''
-                  % {'label':_('open all'), 'group':group})
-                w(u'</div>')
-                docmsgid = '%s_%s_description' % (group, oid)
-                doc = _(docmsgid)
-                if doc != docmsgid:
-                    w(u'<div class="helper">%s</div>' % xml_escape(doc).capitalize())
-                w(u'</div>')
-                w(u'<fieldset id="field_%(oid)s_%(group)s" class="%(group)s preferences hidden">'
-                  % {'oid':oid, 'group':group})
-                w(form)
-                w(u'</fieldset>')
-            w(u'</div>')
+                                            for g, o in groupedforms.iteritems()):
+            self.wrap_grouped_form(group, label, objects)
 
     @property
     @cached
@@ -192,6 +138,33 @@
             values[entity.pkey] = i
         return values
 
+    def group_properties(self):
+        mainopts, groupedopts = {}, {}
+        vreg = self._cw.vreg
+        # "self._regid__=='systempropertiesform'" to skip site wide properties on
+        # user's preference but not site's configuration
+        for key in vreg.user_property_keys(self.__regid__=='systempropertiesform'):
+            parts = key.split('.')
+            if parts[0] in vreg and len(parts) >= 3:
+                # appobject configuration
+                reg = parts[0]
+                propid = parts[-1]
+                oid = '.'.join(parts[1:-1])
+                groupedopts.setdefault(reg, {}).setdefault(oid, []).append(key)
+            else:
+                mainopts.setdefault(parts[0], []).append(key)
+        return mainopts, groupedopts
+
+    def build_forms(self, mainopts, groupedopts):
+        mainforms, groupedforms = {}, {}
+        for group, keys in mainopts.items():
+            mainforms[group] = self.form(group, keys, False)
+        for group, objects in groupedopts.items():
+            groupedforms[group] = {}
+            for oid, keys in objects.items():
+                groupedforms[group][oid] = self.form(group + '_' + oid, keys, True)
+        return mainforms, groupedforms
+
     def entity_for_key(self, key):
         values = self.defined_keys
         if key in values:
@@ -232,11 +205,50 @@
                                                 mainform=False)
         subform.append_field(PropertyValueField(name='value', label=label, role='subject',
                                                 eidparam=True))
-        #subform.vreg = self._cw.vreg
         subform.add_hidden('pkey', key, eidparam=True, role='subject')
         form.add_subform(subform)
         return subform
 
+    def wrap_main_form(self, group, label, form):
+        status = css_class(self._group_status(group))
+        self.w(u'<div class="propertiesform">%s</div>\n' %
+               (make_togglable_link('fieldset_' + group, label)))
+        self.w(u'<div id="fieldset_%s" %s>' % (group, status))
+        self.w(u'<fieldset class="preferences">')
+        self.w(form)
+        self.w(u'</fieldset></div>')
+
+    def wrap_grouped_form(self, group, label, objects):
+        status = css_class(self._group_status(group))
+        self.w(u'<div class="propertiesform">%s</div>\n' %
+          (make_togglable_link('fieldset_' + group, label)))
+        self.w(u'<div id="fieldset_%s" %s>' % (group, status))
+        sorted_objects = sorted((self._cw.__('%s_%s' % (group, o)), o, f)
+                                for o, f in objects.iteritems())
+        for label, oid, form in sorted_objects:
+            self.wrap_object_form(group, oid, label, form)
+        self.w(u'</div>')
+
+    def wrap_object_form(self, group, oid, label, form):
+        w = self.w
+        w(u'<div class="component">')
+        w(u'''<div class="componentLink"><a href="javascript:$.noop();"
+                   onclick="javascript:toggleVisibility('field_%(oid)s_%(group)s')"
+                   class="componentTitle">%(label)s</a>''' % {'label':label, 'oid':oid, 'group':group})
+        w(u''' (<div class="openlink"><a href="javascript:$.noop();"
+                onclick="javascript:openFieldset('fieldset_%(group)s')">%(label)s</a></div>)'''
+                  % {'label':self._cw._('open all'), 'group':group})
+        w(u'</div>')
+        docmsgid = '%s_%s_description' % (group, oid)
+        doc = self._cw._(docmsgid)
+        if doc != docmsgid:
+            w(u'<div class="helper">%s</div>' % xml_escape(doc).capitalize())
+        w(u'</div>')
+        w(u'<fieldset id="field_%(oid)s_%(group)s" class="%(group)s preferences hidden">'
+          % {'oid':oid, 'group':group})
+        w(form)
+        w(u'</fieldset>')
+
 
 class CWPropertiesForm(SystemCWPropertiesForm):
     """user's preferences properties edition form"""
@@ -267,7 +279,7 @@
         # we have to set for_user explicitly
         if not subform.edited_entity.has_eid() and self.user.matching_groups('managers'):
             subform.add_hidden('for_user', self.user.eid, eidparam=True, role='subject')
-
+        return subform
 
 # cwproperty form objects ######################################################
 
--- a/web/views/cwuser.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/views/cwuser.py	Fri Oct 14 09:21:45 2011 +0200
@@ -68,8 +68,8 @@
             self.cell_call(i, 0)
         self.w(u'</rdf:RDF>\n')
 
-    def cell_call(self, row, col):
-        entity = self.cw_rset.complete_entity(row, col)
+    def entity_call(self, entity, **kwargs):
+        entity.complete()
         # account
         self.w(u'<foaf:OnlineAccount rdf:about="%s">\n' % entity.absolute_url())
         self.w(u'  <foaf:accountName>%s</foaf:accountName>\n' % entity.login)
@@ -122,15 +122,15 @@
         self.wview('editable-table', rset, 'null', displayfilter=True,
                    displaycols=range(5), mainindex=0, headers=headers)
 
+
 class CWGroupPermTab(EntityView):
     __regid__ = 'cwgroup-permissions'
     __select__ = is_instance('CWGroup')
 
-    def cell_call(self, row, col):
+    def entity_call(self, entity):
         self._cw.add_css(('cubicweb.schema.css','cubicweb.acl.css'))
         access_types = ('read', 'delete', 'add', 'update')
         w = self.w
-        entity = self.cw_rset.get_entity(row, col)
         objtype_access = {'CWEType': ('read', 'delete', 'add', 'update'),
                           'CWRelation': ('add', 'delete')}
         rql_cwetype = 'DISTINCT Any X WHERE X %s_permission CWG, X is CWEType, ' \
@@ -148,12 +148,13 @@
                 self.w(u'<div>%s:</div>' % self._cw.__(access_type + '_permission'))
                 self.w(u'<div>%s</div><br/>' % self._cw.view('csv', rset, 'null'))
 
+
 class CWGroupInContextView(EntityView):
     __regid__ = 'incontext'
     __select__ = is_instance('CWGroup')
 
-    def cell_call(self, row, col):
-        entity = self.cw_rset.complete_entity(row, col)
+    def entity_call(self, entity, **kwargs):
+        entity.complete()
         self.w(u'<a href="%s" class="%s">%s</a>' % (
             entity.absolute_url(), entity.name, entity.printable_value('name')))
 
@@ -166,30 +167,57 @@
     category = 'manage'
 
 
+class UsersAndGroupsManagementView(tabs.TabsMixin, StartupView):
+    __regid__ = 'cw.users-and-groups-management'
+    __select__ = StartupView.__select__ & match_user_groups('managers')
+    title = _('Users and groups management')
+    tabs = [_('cw.users-management'), _('cw.groups-management'),]
+    default_tab = 'cw.users-management'
+
+    def call(self, **kwargs):
+        """The default view representing the instance's management"""
+        self.w(u'<h1>%s</h1>' % self._cw._(self.title))
+        self.render_tabs(self.tabs, self.default_tab)
+
+
 class CWUserManagementView(StartupView):
-    __regid__ = 'cw.user-management'
+    __regid__ = 'cw.users-management'
+    __select__ = StartupView.__select__ & match_user_groups('managers')
+    cache_max_age = 0 # disable caching
     # XXX one could wish to display for instance only user's firstname/surname
     # for non managers but filtering out NULL cause crash with an ldapuser
     # source.
-    __select__ = StartupView.__select__ & match_user_groups('managers')
-    rql = ('Any U,USN,F,S,U,UAA,UDS, L,UAA,UDSN ORDERBY L WHERE U is CWUser, '
+    rql = ('Any U,US,F,S,U,UAA,UDS, L,UAA,USN,UDSN ORDERBY L WHERE U is CWUser, '
            'U login L, U firstname F, U surname S, '
            'U in_state US, US name USN, '
            'U primary_email UA?, UA address UAA, '
            'U cw_source UDS, US name UDSN')
-    title = _('users and groups management')
+
+    def call(self, **kwargs):
+        self.w(add_etype_button(self._cw, 'CWGroup'))
+        self.w(u'<div class="clear"></div>')
+        self.wview('cw.users-table', self._cw.execute(self.rql))
+
+
+class CWGroupsManagementView(StartupView):
+    __regid__ = 'cw.groups-management'
+    __select__ = StartupView.__select__ & match_user_groups('managers')
     cache_max_age = 0 # disable caching
+    rql = ('Any G,COUNT(U), GN GROUPBY G,GN ORDERBY GN '
+           'WHERE G is CWGroup, U? in_group G, G name GN, NOT G name "owners"')
+    headers = [None, None]
+    cellvids = {}
 
     def call(self, **kwargs):
         self.w('<h1>%s</h1>' % self._cw._(self.title))
         self.w(add_etype_button(self._cw, 'CWUser'))
-        self.w(add_etype_button(self._cw, 'CWGroup'))
         self.w(u'<div class="clear"></div>')
-        self.wview('cw.user-table', self._cw.execute(self.rql))
+        self.wview('editable-table', self._cw.execute(self.rql),
+                   headers=self.headers, cellvids=self.cellvids)
 
 
-class CWUserTable(tableview.EditableTableView):
-    __regid__ = 'cw.user-table'
+class CWUsersTable(tableview.EditableTableView):
+    __regid__ = 'cw.users-table'
     __select__ = is_instance('CWUser')
 
     def call(self, **kwargs):
@@ -199,25 +227,24 @@
                    display_name(self._cw, 'CWGroup', 'plural'),
                    display_name(self._cw, 'primary_email'),
                    display_name(self._cw, 'CWSource'))
-        super(CWUserTable, self).call(
+        super(CWUsersTable, self).call(
             paginate=True, displayfilter=True,
             cellvids={0: 'cw.user.login',
-                      4: 'cw.user-table.group-cell'},
+                      4: 'cw.users-table.group-cell'},
             headers=headers, **kwargs)
 
 
 class CWUserGroupCell(EntityView):
-    __regid__ = 'cw.user-table.group-cell'
+    __regid__ = 'cw.users-table.group-cell'
     __select__ = is_instance('CWUser')
 
-    def cell_call(self, row, col, **kwargs):
-        entity = self.cw_rset.get_entity(row, col)
+    def entity_call(self, entity, **kwargs):
         self.w(entity.view('reledit', rtype='in_group', role='subject'))
 
+
 class CWUserLoginCell(EntityView):
     __regid__ = 'cw.user.login'
     __select__ = is_instance('CWUser')
 
-    def cell_call(self, row, col, **kwargs):
-        entity = self.cw_rset.get_entity(row, col)
+    def entity_call(self, entity, **kwargs):
         self.w(tags.a(entity.login, href=entity.absolute_url()))
--- a/web/views/debug.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/views/debug.py	Fri Oct 14 09:21:45 2011 +0200
@@ -42,7 +42,7 @@
 class SiteInfoAction(actions.ManagersAction):
     __regid__ = 'siteinfo'
     __select__ = match_user_groups('users','managers')
-    title = _('siteinfo')
+    title = _('Site information')
     category = 'manage'
     order = 1000
 
--- a/web/views/editcontroller.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/views/editcontroller.py	Fri Oct 14 09:21:45 2011 +0200
@@ -47,7 +47,7 @@
         return str(self.entity.e_schema).lower(), {}
 
     @implements_adapter_compat('IEditControl')
-    def pre_web_edit(self):
+    def pre_web_edit(self, form):
         """callback called by the web editcontroller when an entity will be
         created/modified, to let a chance to do some entity specific stuff.
 
@@ -173,13 +173,6 @@
         entity = self._cw.vreg['etypes'].etype_class(etype)(self._cw)
         entity.eid = valerror_eid(formparams['eid'])
         is_main_entity = self._cw.form.get('__maineid') == formparams['eid']
-        # let a chance to do some entity specific stuff
-        entity.cw_adapt_to('IEditControl').pre_web_edit()
-        # create a rql query from parameters
-        rqlquery = RqlQuery()
-        # process inlined relations at the same time as attributes
-        # this will generate less rql queries and might be useful in
-        # a few dark corners
         if is_main_entity:
             formid = self._cw.form.get('__form_id', 'edition')
         else:
@@ -187,6 +180,13 @@
             # inbetween, use cubicweb standard formid for inlined forms
             formid = 'edition'
         form = self._cw.vreg['forms'].select(formid, self._cw, entity=entity)
+        # let a chance to do some entity specific stuff
+        entity.cw_adapt_to('IEditControl').pre_web_edit(form)
+        # create a rql query from parameters
+        rqlquery = RqlQuery()
+        # process inlined relations at the same time as attributes
+        # this will generate less rql queries and might be useful in
+        # a few dark corners
         eid = form.actual_eid(entity.eid)
         try:
             editedfields = formparams['_cw_entity_fields']
--- a/web/views/facets.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/views/facets.py	Fri Oct 14 09:21:45 2011 +0200
@@ -31,7 +31,12 @@
 
 def facets(req, rset, context, mainvar=None):
     """return the base rql and a list of widgets for facets applying to the
-    given rset/context (cached version)
+    given rset/context (cached version of :func:`_facet`)
+
+    :param req: A :class:`~cubicweb.req.RequestSessionBase` object
+    :param rset: A :class:`~cubicweb.rset.ResultSet`
+    :param context: A string that match the ``__regid__`` of a ``FacetFilter``
+    :param mainvar: A string that match a select var from the rset
     """
     try:
         cache = req.__rset_facets
@@ -47,12 +52,19 @@
 def _facets(req, rset, context, mainvar):
     """return the base rql and a list of widgets for facets applying to the
     given rset/context
+
+    :param req: A :class:`~cubicweb.req.RequestSessionBase` object
+    :param rset: A :class:`~cubicweb.rset.ResultSet`
+    :param context: A string that match the ``__regid__`` of a ``FacetFilter``
+    :param mainvar: A string that match a select var from the rset
     """
+    ### initialisation
     # XXX done by selectors, though maybe necessary when rset has been hijacked
     # (e.g. contextview_selector matched)
     origqlst = rset.syntax_tree()
     # union not yet supported
     if len(origqlst.children) != 1:
+        req.debug('facette disabled on union request %s', origqlst)
         return None, ()
 
     # Add type restriction to rql. This allow the get_type() method to return
@@ -68,9 +80,15 @@
     rqlst = origqlst.copy()
     select = rqlst.children[0]
     filtered_variable, baserql = facetbase.init_facets(rset, select, mainvar)
-    wdgs = [(facet, facet.get_widget()) for facet in req.vreg['facets'].poss_visible_objects(
-        req, rset=rset, rqlst=origqlst, select=select, context=context,
-        filtered_variable=filtered_variable)]
+    ### Selection
+    possible_facets = req.vreg['facets'].poss_visible_objects(
+                        req,
+                        rset=rset,
+                        rqlst=origqlst,
+                        select=select,
+                        context=context,
+                        filtered_variable=filtered_variable)
+    wdgs = [(facet, facet.get_widget()) for facet in possible_facets]
     return baserql, [wdg for facet, wdg in wdgs if wdg is not None]
 
 
@@ -106,13 +124,45 @@
 
 
 class FacetFilterMixIn(object):
+    """Mixin Class to generate Facet Filter Form
+
+    To generate the form, you need to explicitly the following methode with the
+    right argument:
+
+    .. automethod:: generate_form
+
+    The most useful function to overwrite is:
+
+    .. automethod:: layout_widgets
+
+    """
     needs_js = ['cubicweb.ajax.js', 'cubicweb.facets.js']
     needs_css = ['cubicweb.facets.css']
     roundcorners = True
 
-    def generate_form(self, w, rset, divid, vid, vidargs,
+    def generate_form(self, w, rset, divid, vid, vidargs=None,
                       paginate=False, cssclass='', **hiddens):
-        """display a form to filter some view's content"""
+        """display a form to filter some view's content
+
+        :param w:        Write function
+
+        :param rset:     ResultSet to be filtered
+
+        :param divid:    Dom ID of the div where the rendering of the view is done.
+        :type divid:     string
+
+        :param vid:      ID of the view display in the div
+        :type vid:       string
+
+        :param paginate: Is the view paginated ?
+        :type paginate:  boolean
+
+        :param cssclass: Additional css classes to put on the form.
+        :type cssclass:  string
+
+        :param hiddens:  other hidden parametters to include in the forms.
+        :type hiddens:   dict from extra keyword argument
+        """
         mainvar = self.cw_extra_kwargs.get('mainvar')
         baserql, wdgs = facets(self._cw, rset, self.__regid__, mainvar)
         assert wdgs
@@ -123,7 +173,11 @@
         if self.roundcorners:
             self._cw.html_headers.add_onload(
                 'jQuery(".facet").corner("tl br 10px");')
-        # drop False / None values from vidargs
+        if vidargs is not None:
+            warn("[3.14] vidargs is deprecated. Maybe you're using some TableView?",
+                 DeprecationWarning, stacklevel=2)
+        else:
+            vidargs = {}
         vidargs = dict((k, v) for k, v in vidargs.iteritems() if v)
         facetargs = xml_escape(json_dumps([divid, vid, paginate, vidargs]))
         w(u'<form id="%sForm" class="%s" method="post" action="" '
@@ -154,7 +208,7 @@
         """sort widgets: by default sort by widget height, then according to
         widget.order (the original widgets order)
         """
-        return sorted(wdgs, key=lambda x: x.height())
+        return sorted(wdgs, key=lambda x: x.height)
 
     def layout_widgets(self, w, wdgs):
         """layout widgets: by default simply render each of them
@@ -189,8 +243,7 @@
         for param in ('subvid', 'vtitle'):
             if param in req.form:
                 hiddens[param] = req.form[param]
-        self.generate_form(w, rset, divid, vid, self.vidargs(),
-                           paginate=paginate, **hiddens)
+        self.generate_form(w, rset, divid, vid, paginate=paginate, **hiddens)
 
     def _get_context(self):
         view = self.cw_extra_kwargs.get('view')
@@ -220,12 +273,6 @@
                 req._('bookmark this search'))
         return self.bk_linkbox_template % bk_link
 
-    def vidargs(self):
-        """this method returns the list of extra arguments that should be used
-        by the filter or the view using it
-        """
-        return {}
-
 
 from cubicweb.view import AnyRsetView
 
@@ -234,11 +281,9 @@
     __select__ = has_facets()
     compact_layout_threshold = 5
 
-    def call(self, vid, divid, vidargs, cssclass=''):
-        self.generate_form(self.w, self.cw_rset, divid, vid, vidargs,
-                           cssclass=cssclass, fromformfilter='1',
-                           # divid=divid XXX
-                           )
+    def call(self, vid, divid, vidargs=None, cssclass=''):
+        self.generate_form(self.w, self.cw_rset, divid, vid, vidargs=vidargs,
+                           cssclass=cssclass, fromformfilter='1')
 
     def _simple_horizontal_layout(self, w, wdgs):
         w(u'<table class="filter">\n')
@@ -252,7 +297,7 @@
 
     def layout_widgets(self, w, wdgs):
         """layout widgets: put them in a table where each column should have
-        sum(wdg.height()) < wdg_stack_size.
+        sum(wdg.height) < wdg_stack_size.
         """
         if len(wdgs) < self.compact_layout_threshold:
             self._simple_horizontal_layout(w, wdgs)
@@ -260,10 +305,10 @@
         w(u'<table class="filter">\n')
         widget_queue = []
         queue_height = 0
-        wdg_stack_size = max(wdgs, key=lambda wdg:wdg.height()).height()
+        wdg_stack_size = max(wdgs, key=lambda wdg:wdg.height).height
         w(u'<tr>\n')
         for wdg in wdgs:
-            height = wdg.height()
+            height = wdg.height
             if queue_height + height <= wdg_stack_size:
                 widget_queue.append(wdg)
                 queue_height += height
--- a/web/views/forms.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/views/forms.py	Fri Oct 14 09:21:45 2011 +0200
@@ -47,7 +47,7 @@
 from warnings import warn
 
 from logilab.common import dictattr, tempattr
-from logilab.common.decorators import iclassmethod
+from logilab.common.decorators import iclassmethod, cached
 from logilab.common.compat import any
 from logilab.common.textutils import splitstrip
 from logilab.common.deprecation import deprecated
@@ -57,7 +57,7 @@
 from cubicweb.selectors import non_final_entity, match_kwargs, one_line_rset
 from cubicweb.web import RequestError, ProcessFormError
 from cubicweb.web import uicfg, form, formwidgets as fwdgs
-from cubicweb.web.formfields import relvoc_unrelated, guess_field
+from cubicweb.web.formfields import guess_field
 
 
 class FieldsForm(form.Form):
@@ -376,9 +376,7 @@
         if kwargs.get('mainform', True) or kwargs.get('mainentity', False):
             self.add_hidden(u'__maineid', self.edited_entity.eid)
             # If we need to directly attach the new object to another one
-            if self._cw.list_form_param('__linkto'):
-                for linkto in self._cw.list_form_param('__linkto'):
-                    self.add_hidden('__linkto', linkto)
+            if '__linkto' in self._cw.form:
                 if msg:
                     msg = '%s %s' % (msg, self._cw._('and linked'))
                 else:
@@ -387,6 +385,40 @@
             msgid = self._cw.set_redirect_message(msg)
             self.add_hidden('_cwmsgid', msgid)
 
+    def add_linkto_hidden(self):
+        """add the __linkto hidden field used to directly attach the new object
+        to an existing other one when the relation between those two is not
+        already present in the form.
+
+        Warning: this method must be called only when all form fields are setup
+        """
+        for (rtype, role), eids in self.linked_to.iteritems():
+            # if the relation is already setup by a form field, do not add it
+            # in a __linkto hidden to avoid setting it twice in the controller
+            try:
+                self.field_by_name(rtype, role)
+            except form.FieldNotFound:
+                for eid in eids:
+                    self.add_hidden('__linkto', '%s:%s:%s' % (rtype, eid, role))
+
+    def render(self, *args, **kwargs):
+        self.add_linkto_hidden()
+        return super(EntityFieldsForm, self).render(*args, **kwargs)
+
+    @property
+    @cached
+    def linked_to(self):
+        # if current form is not the main form, exit immediately
+        try:
+            self.field_by_name('__maineid')
+        except form.FieldNotFound:
+            return {}
+        linked_to = {}
+        for linkto in self._cw.list_form_param('__linkto'):
+            ltrtype, eid, ltrole = linkto.split(':')
+            linked_to.setdefault((ltrtype, ltrole), []).append(typed_eid(eid))
+        return linked_to
+
     def session_key(self):
         """return the key that may be used to store / retreive data about a
         previous post which failed because of a validation error
@@ -427,16 +459,18 @@
     def editable_relations(self):
         return ()
 
-    @deprecated('[3.6] use cw.web.formfields.relvoc_unrelated function')
+    @deprecated('[3.6] use cw.web.formfields.RelationField.relvoc_unrelated method')
     def subject_relation_vocabulary(self, rtype, limit=None):
         """defaut vocabulary method for the given relation, looking for
         relation's object entities (i.e. self is the subject)
         """
-        return relvoc_unrelated(self.edited_entity, rtype, 'subject', limit=None)
+        field = self.field_by_name(rtype, 'subject')
+        return field.relvoc_unrelated(form, limit=None)
 
-    @deprecated('[3.6] use cw.web.formfields.relvoc_unrelated function')
+    @deprecated('[3.6] use cw.web.formfields.relvoc_unrelated method')
     def object_relation_vocabulary(self, rtype, limit=None):
-        return relvoc_unrelated(self.edited_entity, rtype, 'object', limit=None)
+        field = self.field_by_name(rtype, 'object')
+        return field.relvoc_unrelated(form, limit=None)
 
 
 class CompositeFormMixIn(object):
--- a/web/views/ibreadcrumbs.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/views/ibreadcrumbs.py	Fri Oct 14 09:21:45 2011 +0200
@@ -28,7 +28,8 @@
 from cubicweb import tags, uilib
 from cubicweb.entity import Entity
 from cubicweb.selectors import (is_instance, one_line_rset, adaptable,
-                                one_etype_rset, multi_lines_rset, any_rset)
+                                one_etype_rset, multi_lines_rset, any_rset,
+                                match_form_params)
 from cubicweb.view import EntityView, EntityAdapter
 from cubicweb.web.views import basecomponents
 # don't use AnyEntity since this may cause bug with isinstance() due to reloading
@@ -120,7 +121,10 @@
     # XXX support kwargs for compat with other components which gets the view as
     # argument
     def render(self, w, **kwargs):
-        entity = self.cw_rset.get_entity(0, 0)
+        try:
+            entity = self.cw_extra_kwargs['entity']
+        except KeyError:
+            entity = self.cw_rset.get_entity(0, 0)
         adapter = ibreadcrumb_adapter(entity)
         view = self.cw_extra_kwargs.get('view')
         path = adapter.breadcrumbs(view)
@@ -190,6 +194,17 @@
         w(u'</span>')
 
 
+class BreadCrumbLinkToVComponent(BreadCrumbEntityVComponent):
+    __select__ = basecomponents.HeaderComponent.__select__ & match_form_params('__linkto')
+
+    def render(self, w, **kwargs):
+        eid = self._cw.list_form_param('__linkto')[0].split(':')[1]
+        entity = self._cw.entity_from_eid(eid)
+        ecmp = self._cw.vreg[self.__registry__].select(
+            self.__regid__, self._cw, entity=entity, **kwargs)
+        ecmp.render(w, **kwargs)
+
+
 class BreadCrumbView(EntityView):
     __regid__ = 'breadcrumbs'
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/web/views/json.py	Fri Oct 14 09:21:45 2011 +0200
@@ -0,0 +1,114 @@
+# copyright 2003-2011 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
+# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
+#
+# This file is part of CubicWeb.
+#
+# CubicWeb is free software: you can redistribute it and/or modify it under the
+# terms of the GNU Lesser General Public License as published by the Free
+# Software Foundation, either version 2.1 of the License, or (at your option)
+# any later version.
+#
+# CubicWeb 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 Lesser General Public License for more
+# details.
+#
+# You should have received a copy of the GNU Lesser General Public License along
+# with CubicWeb.  If not, see <http://www.gnu.org/licenses/>.
+"""json export views"""
+
+from __future__ import with_statement
+
+__docformat__ = "restructuredtext en"
+_ = unicode
+
+from cubicweb.utils import json_dumps
+from cubicweb.view import EntityView, AnyRsetView
+from cubicweb.web.application import anonymized_request
+from cubicweb.web.views import basecontrollers
+
+class JsonpController(basecontrollers.ViewController):
+    """The jsonp controller is the same as a ViewController but :
+
+    - anonymize request (avoid CSRF attacks)
+    - if ``vid`` parameter is passed, make sure it's sensible (i.e. either
+      "jsonexport" or "ejsonexport")
+    - if ``callback`` request parameter is passed, it's used as json padding
+
+
+    Response's content-type will either be ``application/javascript`` or
+    ``application/json`` depending on ``callback`` parameter presence or not.
+    """
+    __regid__ = 'jsonp'
+
+    def publish(self, rset=None):
+        if 'vid' in self._cw.form:
+            vid = self._cw.form['vid']
+            if vid not in ('jsonexport', 'ejsonexport'):
+                self.warning("vid %s can't be used with jsonp controller, "
+                             "falling back to jsonexport", vid)
+                self._cw.form['vid'] = 'jsonexport'
+        else: # if no vid is specified, use jsonexport
+            self._cw.form['vid'] = 'jsonexport'
+        with anonymized_request(self._cw):
+            json_data = super(JsonpController, self).publish(rset)
+            if 'callback' in self._cw.form: # jsonp
+                json_padding = self._cw.form['callback']
+                # use ``application/javascript`` is ``callback`` parameter is
+                # provided, let ``application/json`` otherwise
+                self._cw.set_content_type('application/javascript')
+                json_data = '%s(%s)' % (json_padding, json_data)
+        return json_data
+
+
+class JsonMixIn(object):
+    """mixin class for json views
+
+    Handles the following optional request parameters:
+
+    - ``_indent`` : must be an integer. If found, it is used to pretty print
+      json output
+    """
+    templatable = False
+    content_type = 'application/json'
+    binary = True
+
+    def wdata(self, data):
+        if '_indent' in self._cw.form:
+            indent = int(self._cw.form['_indent'])
+        else:
+            indent = None
+        self.w(json_dumps(data, indent=indent))
+
+
+class JsonRsetView(JsonMixIn, AnyRsetView):
+    """dumps raw result set in JSON format"""
+    __regid__ = 'jsonexport'
+    title = _('json-export-view')
+
+    def call(self):
+        # XXX mimic w3c recommandations to serialize SPARQL results in json ?
+        #     http://www.w3.org/TR/rdf-sparql-json-res/
+        self.wdata(self.cw_rset.rows)
+
+
+class JsonEntityView(JsonMixIn, EntityView):
+    """dumps rset entities in JSON
+
+    The following additional metadata is added to each row :
+
+    - ``__cwetype__`` : entity type
+    """
+    __regid__ = 'ejsonexport'
+    title = _('json-entities-export-view')
+
+    def call(self):
+        entities = []
+        for entity in self.cw_rset.entities():
+            entity.complete() # fetch all attributes
+            # hack to add extra metadata
+            entity.cw_attr_cache.update({
+                    '__cwetype__': entity.__regid__,
+                    })
+            entities.append(entity)
+        self.wdata(entities)
--- a/web/views/management.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/views/management.py	Fri Oct 14 09:21:45 2011 +0200
@@ -1,4 +1,4 @@
-# copyright 2003-2010 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
+# copyright 2003-2011 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
 # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
 #
 # This file is part of CubicWeb.
@@ -45,10 +45,9 @@
         self.w(u'<div id="progress">%s</div>' % self._cw._('validating...'))
         super(SecurityManagementView, self).call()
 
-    def cell_call(self, row, col):
+    def entity_call(self, entity):
         self._cw.add_js('cubicweb.edition.js')
         self._cw.add_css('cubicweb.acl.css')
-        entity = self.cw_rset.get_entity(row, col)
         w = self.w
         _ = self._cw._
         w(u'<h1><span class="etype">%s</span> <a href="%s">%s</a></h1>'
@@ -56,28 +55,21 @@
              xml_escape(entity.absolute_url()),
              xml_escape(entity.dc_title())))
         # first show permissions defined by the schema
-        self.w('<h2>%s</h2>' % _('schema\'s permissions definitions'))
+        self.w('<h2>%s</h2>' % _('Schema\'s permissions definitions'))
         self.permissions_table(entity.e_schema)
-        self.w('<h2>%s</h2>' % _('manage security'))
+        self.w('<h2>%s</h2>' % _('Manage security'))
         # ownership information
         if self._cw.vreg.schema.rschema('owned_by').has_perm(self._cw, 'add',
                                                     fromeid=entity.eid):
             self.owned_by_edit_form(entity)
         else:
             self.owned_by_information(entity)
-        # cwpermissions
-        if 'require_permission' in entity.e_schema.subject_relations():
-            w('<h3>%s</h3>' % _('permissions for this entity'))
-            reqpermschema = self._cw.vreg.schema.rschema('require_permission')
-            self.require_permission_information(entity, reqpermschema)
-            if reqpermschema.has_perm(self._cw, 'add', fromeid=entity.eid):
-                self.require_permission_edit_form(entity)
 
     def owned_by_edit_form(self, entity):
-        self.w('<h3>%s</h3>' % self._cw._('ownership'))
+        self.w('<h3>%s</h3>' % self._cw._('Ownership'))
         msg = self._cw._('ownerships have been changed')
         form = self._cw.vreg['forms'].select('base', self._cw, entity=entity,
-                                         form_renderer_id='base', submitmsg=msg,
+                                         form_renderer_id='onerowtable', submitmsg=msg,
                                          form_buttons=[wdgs.SubmitButton()],
                                          domid='ownership%s' % entity.eid,
                                          __redirectvid='security',
@@ -89,7 +81,7 @@
     def owned_by_information(self, entity):
         ownersrset = entity.related('owned_by')
         if ownersrset:
-            self.w('<h3>%s</h3>' % self._cw._('ownership'))
+            self.w('<h3>%s</h3>' % self._cw._('Ownership'))
             self.w(u'<div class="ownerInfo">')
             self.w(self._cw._('this entity is currently owned by') + ' ')
             self.wview('csv', entity.related('owned_by'), 'null')
@@ -97,65 +89,6 @@
         # else we don't know if this is because entity has no owner or becayse
         # user as no access to owner users entities
 
-    def require_permission_information(self, entity, reqpermschema):
-        if entity.require_permission:
-            w = self.w
-            _ = self._cw._
-            if reqpermschema.has_perm(self._cw, 'delete', fromeid=entity.eid):
-                delurl = self._cw.build_url('edit', __redirectvid='security',
-                                            __redirectpath=entity.rest_path())
-                delurl = delurl.replace('%', '%%')
-                # don't give __delete value to build_url else it will be urlquoted
-                # and this will replace %s by %25s
-                delurl += '&__delete=%s:require_permission:%%s' % entity.eid
-                dellinktempl = u'[<a href="%s" title="%s">-</a>]&#160;' % (
-                    xml_escape(delurl), _('delete this permission'))
-            else:
-                dellinktempl = None
-            w(u'<table class="schemaInfo">')
-            w(u'<tr><th>%s</th><th>%s</th></tr>' % (_("permission"),
-                                                    _('granted to groups')))
-            for cwperm in entity.require_permission:
-                w(u'<tr>')
-                if dellinktempl:
-                    w(u'<td>%s%s</td>' % (dellinktempl % cwperm.eid,
-                                          cwperm.view('oneline')))
-                else:
-                    w(u'<td>%s</td>' % cwperm.view('oneline'))
-                w(u'<td>%s</td>' % self._cw.view('csv', cwperm.related('require_group'), 'null'))
-                w(u'</tr>\n')
-            w(u'</table>')
-        else:
-            self.w(self._cw._('no associated permissions'))
-
-    def require_permission_edit_form(self, entity):
-        newperm = self._cw.vreg['etypes'].etype_class('CWPermission')(self._cw)
-        newperm.eid = self._cw.varmaker.next()
-        self.w(u'<p>%s</p>' % self._cw._('add a new permission'))
-        form = self._cw.vreg['forms'].select('base', self._cw, entity=newperm,
-                                         form_buttons=[wdgs.SubmitButton()],
-                                         domid='reqperm%s' % entity.eid,
-                                         __redirectvid='security',
-                                         __redirectpath=entity.rest_path())
-        form.add_hidden('require_permission', entity.eid, role='object',
-                        eidparam=True)
-        permnames = getattr(entity, '__permissions__', None)
-        cwpermschema = newperm.e_schema
-        if permnames is not None:
-            field = guess_field(cwpermschema, self._cw.vreg.schema.rschema('name'),
-                                widget=wdgs.Select({'size': 1}),
-                                choices=permnames)
-        else:
-            field = guess_field(cwpermschema, self._cw.vreg.schema.rschema('name'))
-        form.append_field(field)
-        field = guess_field(cwpermschema, self._cw.vreg.schema.rschema('label'))
-        form.append_field(field)
-        field = guess_field(cwpermschema, self._cw.vreg.schema.rschema('require_group'))
-        form.append_field(field)
-        renderer = self._cw.vreg['formrenderers'].select(
-            'htable', self._cw, rset=None, display_progress_div=False)
-        form.render(w=self.w, renderer=renderer)
-
 
 class ErrorView(AnyRsetView):
     """default view when no result has been found"""
--- a/web/views/plots.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/views/plots.py	Fri Oct 14 09:21:45 2011 +0200
@@ -21,6 +21,7 @@
 _ = unicode
 
 from logilab.common.date import datetime2ticks
+from logilab.common.deprecation import class_deprecated
 from logilab.mtconverter import xml_escape
 
 from cubicweb.utils import UStringIO, json_dumps
@@ -84,6 +85,8 @@
 
 class FlotPlotWidget(PlotWidget):
     """PlotRenderer widget using Flot"""
+    __metaclass__ = class_deprecated
+    __deprecation_warning__ = '[3.14] cubicweb.web.views.plots module is deprecated, use the jqplot cube instead'
     onload = u"""
 var fig = jQuery('#%(figid)s');
 if (fig.attr('cubicweb:type') != 'prepared-plot') {
@@ -135,6 +138,8 @@
 
 
 class PlotView(baseviews.AnyRsetView):
+    __metaclass__ = class_deprecated
+    __deprecation_warning__ = '[3.14] cubicweb.web.views.plots module is deprecated, use the jqplot cube instead'
     __regid__ = 'plot'
     title = _('generic plot')
     __select__ = multi_columns_rset() & all_columns_are_numbers()
--- a/web/views/primary.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/views/primary.py	Fri Oct 14 09:21:45 2011 +0200
@@ -494,5 +494,3 @@
 for rtype in META_RTYPES:
     _pvs.tag_subject_of(('*', rtype, '*'), 'hidden')
     _pvs.tag_object_of(('*', rtype, '*'), 'hidden')
-_pvs.tag_subject_of(('*', 'require_permission', '*'), 'hidden')
-_pvs.tag_object_of(('*', 'require_permission', '*'), 'hidden')
--- a/web/views/schema.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/views/schema.py	Fri Oct 14 09:21:45 2011 +0200
@@ -143,13 +143,13 @@
 class SchemaView(tabs.TabsMixin, StartupView):
     """display schema information (graphically, listing tables...) in tabs"""
     __regid__ = 'schema'
-    title = _('instance schema')
+    title = _('data model schema')
     tabs = [_('schema-diagram'), _('schema-entity-types'),
             _('schema-relation-types')]
     default_tab = 'schema-diagram'
 
     def call(self):
-        self.w(u'<h1>%s</h1>' % self._cw._('Schema of the data model'))
+        self.w(u'<h1>%s</h1>' % self._cw._(self.title))
         self.render_tabs(self.tabs, self.default_tab)
 
 
@@ -676,14 +676,6 @@
     def parent_entity(self):
         return self.entity.expression_of
 
-class CWPermissionIBreadCrumbsAdapter(ibreadcrumbs.IBreadCrumbsAdapter):
-    __select__ = is_instance('CWPermission')
-    def parent_entity(self):
-        # XXX useless with permission propagation
-        permissionof = getattr(self.entity, 'reverse_require_permission', ())
-        if len(permissionof) == 1:
-            return permissionof[0]
-
 
 # misc: facets, actions ########################################################
 
@@ -697,7 +689,7 @@
     __regid__ = 'schema'
     __select__ = yes()
 
-    title = _("data model schema")
+    title = _('data model schema')
     order = 30
     category = 'manage'
 
--- a/web/views/tableview.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/views/tableview.py	Fri Oct 14 09:21:45 2011 +0200
@@ -46,7 +46,8 @@
     table_column_class = TableColumn
 
     tablesorter_settings = {
-        'textExtraction': JSString('cubicwebSortValueExtraction'),
+        'textExtraction': JSString('cw.sortValueExtraction'),
+        'selectorHeaders: "thead tr:first th"' # only plug on the first row
         }
 
     def form_filter(self, divid, displaycols, displayactions, displayfilter,
@@ -209,7 +210,9 @@
                 continue
             # compute column header
             if headers is not None:
-                label = headers[displaycols.index(colindex)]
+                _label = headers[displaycols.index(colindex)]
+                if _label is not None:
+                    label = _label
             if colindex == mainindex and label is not None:
                 label += ' (%s)' % self.cw_rset.rowcount
             column = self.table_column_class(label, colindex)
--- a/web/views/urlpublishing.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/views/urlpublishing.py	Fri Oct 14 09:21:45 2011 +0200
@@ -174,7 +174,7 @@
                 except KeyError:
                     raise PathDontMatch()
             else:
-                attrname = cls._rest_attr_info()[0]
+                attrname = cls.cw_rest_attr_info()[0]
             value = req.url_unquote(parts.pop(0))
             return self.handle_etype_attr(req, cls, attrname, value)
         return self.handle_etype(req, cls)
@@ -195,16 +195,17 @@
         return None, rset
 
     def handle_etype_attr(self, req, cls, attrname, value):
-        rql = cls.fetch_rql(req.user, ['X %s %%(x)s' % (attrname)],
-                            mainvar='X', ordermethod=None)
+        st = cls.fetch_rqlst(req.user, ordermethod=None)
+        st.add_constant_restriction(st.get_variable('X'), attrname,
+                                    'x', 'Substitute')
         if attrname == 'eid':
             try:
-                rset = req.execute(rql, {'x': typed_eid(value)})
+                rset = req.execute(st.as_string(), {'x': typed_eid(value)})
             except (ValueError, TypeResolverException):
                 # conflicting eid/type
                 raise PathDontMatch()
         else:
-            rset = req.execute(rql, {'x': value})
+            rset = req.execute(st.as_string(), {'x': value})
         self.set_vid_for_rset(req, cls, rset)
         return None, rset
 
--- a/web/views/urlrewrite.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/views/urlrewrite.py	Fri Oct 14 09:21:45 2011 +0200
@@ -20,6 +20,7 @@
 import re
 
 from cubicweb import typed_eid
+from cubicweb.uilib import domid
 from cubicweb.appobject import AppObject
 
 
@@ -96,7 +97,10 @@
         ('/error', dict(vid='error')),
         ('/sparql', dict(vid='sparql')),
         ('/processinfo', dict(vid='processinfo')),
-        (rgx('/cwuser', re.I), dict(vid='cw.user-management')),
+        (rgx('/cwuser', re.I), dict(vid='cw.users-and-groups-management',
+                                    tab=domid('cw.users-management'))),
+        (rgx('/cwgroup', re.I), dict(vid='cw.users-and-groups-management',
+                                     tab=domid('cw.groups-management'))),
         (rgx('/cwsource', re.I), dict(vid='cw.source-management')),
         # XXX should be case insensitive as 'create', but I would like to find another way than
         # relying on the etype_selector
--- a/web/views/workflow.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/views/workflow.py	Fri Oct 14 09:21:45 2011 +0200
@@ -341,7 +341,7 @@
 def transition_states_vocabulary(form, field):
     entity = form.edited_entity
     if not entity.has_eid():
-        eids = entity.linked_to('transition_of', 'subject')
+        eids = form.linked_to.get(('transition_of', 'subject'))
         if not eids:
             return []
         return _wf_items_for_relation(form._cw, eids[0], 'state_of', field)
@@ -359,7 +359,7 @@
 def state_transitions_vocabulary(form, field):
     entity = form.edited_entity
     if not entity.has_eid():
-        eids = entity.linked_to('state_of', 'subject')
+        eids = form.linked_to.get(('state_of', 'subject'))
         if eids:
             return _wf_items_for_relation(form._cw, eids[0], 'transition_of', field)
         return []
--- a/web/webconfig.py	Fri Oct 14 09:04:39 2011 +0200
+++ b/web/webconfig.py	Fri Oct 14 09:21:45 2011 +0200
@@ -203,6 +203,12 @@
           'help': 'use cubicweb.old.css instead of 3.9 cubicweb.css',
           'group': 'web', 'level': 2,
           }),
+        ('concat-resources',
+         {'type' : 'yn',
+          'default': True,
+          'help': 'use modconcat-like URLS to concat and serve JS / CSS files',
+          'group': 'web', 'level': 2,
+          }),
         ))
 
     def fckeditor_installed(self):