Index: /package_tags/invirt-web/0.1.5/code/Makefile
===================================================================
--- /package_tags/invirt-web/0.1.5/code/Makefile	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/code/Makefile	(revision 2955)
@@ -0,0 +1,8 @@
+all: kill chmod
+
+chmod:
+	chgrp -R invirt . 2>/dev/null || true
+	chmod -R g+w . 2>/dev/null || true
+
+kill:
+	-pkill invirt.fcgi
Index: /package_tags/invirt-web/0.1.5/code/auth.fcgi
===================================================================
--- /package_tags/invirt-web/0.1.5/code/auth.fcgi	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/code/auth.fcgi	(revision 2955)
@@ -0,0 +1,3 @@
+#!/bin/sh
+
+exec ./invirt.fcgi auth "$@"
Index: /package_tags/invirt-web/0.1.5/code/cache_acls.py
===================================================================
--- /package_tags/invirt-web/0.1.5/code/cache_acls.py	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/code/cache_acls.py	(revision 2955)
@@ -0,0 +1,93 @@
+#!/usr/bin/python
+from invirt.database import *
+from invirt.config import structs as config
+import sys
+import getafsgroups
+import subprocess
+
+def expandLocker(name):
+    try:
+        groups = getafsgroups.getLockerAcl(name)
+    except getafsgroups.AfsProcessError, e:
+        if e.message.startswith("fs: You don't have the required access rights on"):
+            return []
+        elif e.message.endswith("doesn't exist\n"):
+            # presumably deactivated
+            return []
+        else:
+            raise
+    cell = getafsgroups.getCell(name)
+    ans = set()
+    for group in groups:
+        if ':' in group:
+            ans.update(getafsgroups.getAfsGroupMembers(group, cell))
+        else:
+            ans.add(group)
+    return ans
+
+def isUser(name):
+    p = subprocess.Popen(['vos', 'examine', 'user.'+name],
+                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+    if p.wait():
+        return False
+    return True
+    
+
+def expandName(name):
+    if ':' not in name:
+        if isUser(name):
+            return [name]
+        return []
+    try:
+        return getafsgroups.getAfsGroupMembers(name, config.authz.afs.cells[0].cell)
+    except getafsgroups.AfsProcessError:
+        return []
+
+def accessList(m):
+    people = set()
+    people.update(expandLocker(m.owner))
+    if m.administrator is not None:
+        people.update(expandName(m.administrator))
+    return people
+
+def refreshMachine(m):
+    people = accessList(m)
+    old_people = set(a.user for a in m.acl)
+    for removed in old_people - people:
+        ma = [x for x in m.acl if x.user == removed][0]
+        session.delete(ma)
+    for p in people - old_people:
+        ma = MachineAccess(user=p)
+        m.acl.append(ma)
+        session.save_or_update(ma)
+    
+def refreshCache():
+    session.begin()
+
+    try:
+        machines = Machine.query().all()
+        for m in machines:
+            refreshMachine(m)
+        session.flush()
+            
+        # Update the admin ACL as well
+        admin_acl = set(expandName(config.adminacl))
+        old_admin_acl = set(a.user for a in Admin.query())
+        for removed in old_admin_acl - admin_acl:
+            old = Admin.query.filter_by(user=removed).first()
+            session.delete(old)
+        for added in admin_acl - old_admin_acl:
+            a = Admin(user=added)
+            session.save_or_update(a)
+        session.flush()
+    
+        # Atomically execute our changes
+        session.commit()
+    except:
+        # Failed! Rollback all the changes.
+        session.rollback()
+        raise
+
+if __name__ == '__main__':
+    connect()
+    refreshCache()
Index: /package_tags/invirt-web/0.1.5/code/controls.py
===================================================================
--- /package_tags/invirt-web/0.1.5/code/controls.py	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/code/controls.py	(revision 2955)
@@ -0,0 +1,286 @@
+import validation
+from invirt.common import CodeError, InvalidInput
+import random
+import sys
+import time
+import re
+import cache_acls
+import yaml
+
+from invirt.config import structs as config
+from invirt.database import Machine, Disk, Type, NIC, CDROM, session, meta
+from invirt.remctl import remctl as gen_remctl
+
+# ... and stolen from xend/uuid.py
+def randomUUID():
+    """Generate a random UUID."""
+
+    return [ random.randint(0, 255) for _ in range(0, 16) ]
+
+def uuidToString(u):
+    """Turn a numeric UUID to a hyphen-seperated one."""
+    return "-".join(["%02x" * 4, "%02x" * 2, "%02x" * 2, "%02x" * 2,
+                     "%02x" * 6]) % tuple(u)
+# end stolen code
+
+def remctl(*args, **kwargs):
+    return gen_remctl(config.remote.hostname,
+                      principal='daemon/'+config.web.hostname,
+                      *args, **kwargs)
+
+def lvcreate(machine, disk):
+    """Create a single disk for a machine"""
+    remctl('web', 'lvcreate', machine.name,
+           disk.guest_device_name, str(disk.size))
+    
+def makeDisks(machine):
+    """Update the lvm partitions to add a disk."""
+    for disk in machine.disks:
+        lvcreate(machine, disk)
+
+def getswap(disksize, memsize):
+    """Returns the recommended swap partition size."""
+    return int(min(disksize / 4, memsize * 1.5))
+
+def lvinstall(machine, autoinstall):
+    disksize = machine.disks[0].size
+    memsize = machine.memory
+    swapsize = getswap(disksize, memsize)
+    imagesize = disksize - swapsize
+    ip = machine.nics[0].ip
+    remctl('control', machine.name, 'install', 
+           'dist=%s' % autoinstall.distribution,
+           'mirror=%s' % autoinstall.mirror,
+           'arch=%s' % autoinstall.arch,
+           'imagesize=%s' % imagesize)
+
+def lvcopy(machine_orig_name, machine, rootpw):
+    """Copy a golden image onto a machine's disk"""
+    remctl('web', 'lvcopy', machine_orig_name, machine.name, rootpw)
+
+def bootMachine(machine, cdtype):
+    """Boot a machine with a given boot CD.
+
+    If cdtype is None, give no boot cd.  Otherwise, it is the string
+    id of the CD (e.g. 'gutsy_i386')
+    """
+    if cdtype is not None:
+        out, err = remctl('control', machine.name, 'create', 
+                          cdtype, err=True)
+    else:
+        out, err = remctl('control', machine.name, 'create',
+                          err=True)
+    if 'already running' in err:
+        raise InvalidInput('action', 'create',
+                           'VM %s is already on' % machine.name)
+    elif 'I need' in err and 'but dom0_min_mem is' in err:
+        raise InvalidInput('action', 'create',
+                           "We're really sorry, but our servers don't have enough capacity to create your VM right now. Try creating a VM with less RAM, or shutting down another VM of yours. Feel free to ask %s if you would like to know when we plan to have more resources." % (config.contact))
+    elif ('Booting VMs is temporarily disabled for maintenance, sorry' in err or
+          'LVM operations are temporarily disabled for maintenance, sorry' in err):
+        raise InvalidInput('action', 'create',
+                           err)
+    elif "Boot loader didn't return any data!" in err:
+        raise InvalidInput('action', 'create',
+                           "The ParaVM bootloader was unable to find an operating system to boot. Do you have GRUB configured correctly?")
+    elif 'xc_dom_find_loader: no loader found' in err:
+        raise InvalidInput('action', 'create',
+                           "The ParaVM bootloader was unable to boot the kernel you have configured. Are you sure this kernel is capable of running as a Xen ParaVM guest?")
+    elif err:
+        raise CodeError('"%s" on "control %s create %s' 
+                        % (err, machine.name, cdtype))
+
+def createVm(username, state, owner, contact, name, description, memory, disksize, machine_type, cdrom, autoinstall):
+    """Create a VM and put it in the database"""
+    # put stuff in the table
+    session.begin()
+    try:
+        validation.Validate(username, state, name=name, description=description, owner=owner, memory=memory, disksize=disksize/1024.)
+        machine = Machine()
+        machine.name = name
+        machine.description = description
+        machine.memory = memory
+        machine.owner = owner
+        machine.administrator = None
+        machine.contact = contact
+        machine.uuid = uuidToString(randomUUID())
+        machine.boot_off_cd = True
+        machine.type = machine_type
+        session.save_or_update(machine)
+        disk = Disk(machine=machine,
+                    guest_device_name='hda', size=disksize)
+        nic = NIC.query().filter_by(machine_id=None).filter_by(reusable=True).first()
+        if not nic: #No IPs left!
+            raise CodeError("No IP addresses left!  "
+                            "Contact %s." % config.web.errormail)
+        nic.machine = machine
+        nic.hostname = name
+        session.save_or_update(nic)
+        session.save_or_update(disk)
+        cache_acls.refreshMachine(machine)
+        makeDisks(machine)
+        session.commit()
+    except:
+        session.rollback()
+        raise
+    try:
+        if autoinstall:
+            lvinstall(machine, autoinstall)
+        else:
+            # tell it to boot with cdrom
+            bootMachine(machine, cdrom)
+    except CodeError, e:
+        deleteVM(machine)
+        raise
+    return machine
+
+def getList():
+    """Return a dictionary mapping machine names to dicts."""
+    value_string = remctl('web', 'listvms')
+    value_dict = yaml.load(value_string, yaml.CSafeLoader)
+    return value_dict
+
+def parseStatus(s):
+    """Parse a status string into nested tuples of strings.
+
+    s = output of xm list --long <machine_name>
+    """
+    values = re.split('([()])', s)
+    stack = [[]]
+    for v in values[2:-2]: #remove initial and final '()'
+        if not v:
+            continue
+        v = v.strip()
+        if v == '(':
+            stack.append([])
+        elif v == ')':
+            if len(stack[-1]) == 1:
+                stack[-1].append('')
+            stack[-2].append(stack[-1])
+            stack.pop()
+        else:
+            if not v:
+                continue
+            stack[-1].extend(v.split())
+    return stack[-1]
+
+def statusInfo(machine):
+    """Return the status list for a given machine.
+
+    Gets and parses xm list --long
+    """
+    value_string, err_string = remctl('control', machine.name, 'list-long', 
+                                      err=True)
+    if 'Unknown command' in err_string:
+        raise CodeError("ERROR in remctl list-long %s is not registered" % 
+                        (machine.name,))
+    elif 'is not on' in err_string:
+        return None
+    elif err_string:
+        raise CodeError("ERROR in remctl list-long %s:  %s" % 
+                        (machine.name, err_string))
+    status = parseStatus(value_string)
+    return status
+
+def listHost(machine):
+    """Return the host a machine is running on"""
+    out, err = remctl('control', machine.name, 'listhost', err=True)
+    if err:
+        return None
+    return out.strip()
+
+def vnctoken(machine):
+    """Return a time-stamped VNC token"""
+    out, err = remctl('control', machine.name, 'vnctoken', err=True)
+    if err:
+        return None
+    return out.strip()
+
+def deleteVM(machine):
+    """Delete a VM."""
+    remctl('control', machine.name, 'destroy', err=True)
+    session.begin()
+    delete_disk_pairs = [(machine.name, d.guest_device_name) 
+                         for d in machine.disks]
+    try:
+        for mname, dname in delete_disk_pairs:
+            remctl('web', 'lvremove', mname, dname)
+        for nic in machine.nics:
+            nic.machine_id = None
+            nic.hostname = None
+            session.save_or_update(nic)
+        for disk in machine.disks:
+            session.delete(disk)
+        session.delete(machine)
+        session.commit()
+    except:
+        session.rollback()
+        raise
+
+def commandResult(username, state, command_name, machine_id, fields):
+    start_time = 0
+    machine = validation.Validate(username, state, machine_id=machine_id).machine
+    action = command_name
+    cdrom = fields.get('cdrom') or None
+    if cdrom is not None and not CDROM.query().filter_by(cdrom_id=cdrom).one():
+        raise CodeError("Invalid cdrom type '%s'" % cdrom)    
+    if action not in "reboot create destroy shutdown delete".split(" "):
+        raise CodeError("Invalid action '%s'" % action)
+    if action == 'reboot':
+        if cdrom is not None:
+            out, err = remctl('control', machine.name, 'reboot', cdrom,
+                              err=True)
+        else:
+            out, err = remctl('control', machine.name, 'reboot',
+                              err=True)
+        if err:
+            if re.match("machine '.*' is not on", err):
+                raise InvalidInput("action", "reboot", 
+                                   "Machine is not on")
+            else:
+                print >> sys.stderr, 'Error on reboot:'
+                print >> sys.stderr, err
+                raise CodeError('ERROR on remctl')
+                
+    elif action == 'create':
+        if validation.maxMemory(username, state, machine) < machine.memory:
+            raise InvalidInput('action', 'Power on',
+                               "You don't have enough free RAM quota "
+                               "to turn on this machine.")
+        bootMachine(machine, cdrom)
+    elif action == 'destroy':
+        out, err = remctl('control', machine.name, 'destroy', err=True)
+        if err:
+            if re.match("machine '.*' is not on", err):
+                raise InvalidInput("action", "Power off", 
+                                   "Machine is not on.")
+            else:
+                print >> sys.stderr, 'Error on power off:'
+                print >> sys.stderr, err
+                raise CodeError('ERROR on remctl')
+    elif action == 'shutdown':
+        out, err = remctl('control', machine.name, 'shutdown', err=True)
+        if err:
+            if re.match("machine '.*' is not on", err):
+                raise InvalidInput("action", "Shutdown", 
+                                   "Machine is not on.")
+            else:
+                print >> sys.stderr, 'Error on Shutdown:'
+                print >> sys.stderr, err
+                raise CodeError('ERROR on remctl')
+    elif action == 'delete':
+        deleteVM(machine)
+
+    d = dict(user=username,
+             command=action,
+             machine=machine)
+    return d
+
+def resizeDisk(machine_name, disk_name, new_size):
+    remctl("web", "lvresize", machine_name, disk_name, new_size)
+
+def renameMachine(machine, old_name, new_name):
+    for disk in machine.disks:
+        remctl("web", "lvrename", old_name, 
+               disk.guest_device_name, new_name)
+    
Index: /package_tags/invirt-web/0.1.5/code/dev.conf
===================================================================
--- /package_tags/invirt-web/0.1.5/code/dev.conf	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/code/dev.conf	(revision 2955)
@@ -0,0 +1,11 @@
+# For the testing site.
+
+[global]
+server.socket_port = 8080
+log.access_file = "/tmp/invirt-web-access_log.dev"
+log.error_file = "/tmp/invirt-web-error_log.dev"
+tools.mako.module_directory = "/tmp/invirt-web-templatecache.dev"
+tools.basic_auth.on = True
+tools.basic_auth.realm = 'Invirt Web DEVELOPMENT'
+tools.basic_auth.users = {'quentin': 'quentin','broder': 'broder'}
+tools.basic_auth.encrypt = __builtin__.str
Index: /package_tags/invirt-web/0.1.5/code/getafsgroups.py
===================================================================
--- /package_tags/invirt-web/0.1.5/code/getafsgroups.py	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/code/getafsgroups.py	(revision 2955)
@@ -0,0 +1,105 @@
+#!/usr/bin/python
+import pprint
+import subprocess
+from invirt.config import structs as config
+
+# import ldap
+# l = ldap.open("W92-130-LDAP-2.mit.edu")
+# # ldap.mit.edu is 1/2 broken right now so we're going to the working backend
+# l.simple_bind_s("", "")
+
+# def getLdapGroups(user):
+#     """
+#     getLdapGroups(user): returns a generator for the list of LDAP groups containing user
+#     """
+#     for user_data in l.search_s("ou=affiliates,dc=mit,dc=edu", ldap.SCOPE_ONELEVEL, "uid=" + user, []):
+#         for group_data in l.search_s("ou=groups,dc=mit,dc=edu", ldap.SCOPE_ONELEVEL, "uniqueMember="+user_data[0], ['cn']):
+#             yield group_data[1]['cn'][0]
+
+# def checkLdapGroups(user, group):
+#     """
+#     checkLdapGroups(user, group): returns True if and only if user is in LDAP group group
+#     """
+#     for result_data in l.search_s("ou=affiliates,dc=mit,dc=edu", ldap.SCOPE_ONELEVEL, "uid=" + user, []):
+#         if l.search_s("ou=groups,dc=mit,dc=edu", ldap.SCOPE_ONELEVEL, "(&(cn=" + group + ")(uniqueMember="+result_data[0] + "))", []) != []:
+#             return True
+#     return False
+
+class AfsProcessError(Exception):
+    pass
+
+def getAfsGroupMembers(group, cell):
+    encrypt = True
+    for c in config.authz.afs.cells:
+        if c.cell == cell and hasattr(c, 'auth'):
+            encrypt = c.auth
+    if encrypt:
+        subprocess.check_call(['aklog', cell], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+    p = subprocess.Popen(["pts", "membership", "-encrypt" if encrypt else '-noauth', group, '-c', cell],
+                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+    err = p.stderr.read()
+    if err: #Error code doesn't reveal missing groups, but stderr does
+        if err.startswith('pts: Permission denied ; unable to get membership of '):
+            return []
+        raise AfsProcessError(err)
+    return [line.strip() for line in p.stdout.readlines()[1:]]
+
+def getLockerPath(locker):
+    if '/' in locker or locker in ['.', '..']:
+        raise AfsProcessError("Locker '%s' is invalid." % locker)
+    return '/mit/' + locker
+
+def getCell(locker):
+    p = subprocess.Popen(["fs", "whichcell", getLockerPath(locker)], 
+                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+    if p.wait():
+        raise AfsProcessError(p.stderr.read())
+    return p.stdout.read().split()[-1][1:-1]
+
+def getLockerAcl(locker):
+    p = subprocess.Popen(["fs", "listacl", getLockerPath(locker)], 
+                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+    if p.wait():
+        raise AfsProcessError(p.stderr.read())
+    lines = p.stdout.readlines()
+    values = []
+    for line in lines[1:]:
+        fields = line.split()
+        if fields[0] == 'Negative':
+            break
+        if 'a' in fields[1]:
+            values.append(fields[0])
+    return values
+
+def notLockerOwner(user, locker):
+    """
+    notLockerOwner(user, locker) returns false if and only if user administers locker.
+
+    If the user does not own the locker, returns the string reason for
+    the failure.
+    """
+    try:
+        cell = getCell(locker)
+        values = getLockerAcl(locker)
+    except AfsProcessError, e:
+        return str(e)
+
+    for entry in values:
+        if entry == user or (entry[0:6] == "system" and
+                                user in getAfsGroupMembers(entry, cell)):
+            return False
+    return "You don't have admin bits on " + getLockerPath(locker)
+
+
+if __name__ == "__main__":
+#    print list(getldapgroups("tabbott"))
+    print "tabbott" in getAfsGroupMembers("system:debathena", 'athena.mit.edu')
+    print "tabbott" in getAfsGroupMembers("system:debathena", 'sipb.mit.edu')
+    print "tabbott" in getAfsGroupMembers("system:debathena-root", 'athena.mit.edu')
+    print "tabbott" in getAfsGroupMembers("system:hmmt-request", 'athena.mit.edu')
+    print notLockerOwner("tabbott", "tabbott")
+    print notLockerOwner("tabbott", "debathena")
+    print notLockerOwner("tabbott", "sipb")
+    print notLockerOwner("tabbott", "lsc")
+    print notLockerOwner("tabbott", "scripts")
+    print notLockerOwner("ecprice", "hmmt")
Index: /package_tags/invirt-web/0.1.5/code/invirt.fcgi
===================================================================
--- /package_tags/invirt-web/0.1.5/code/invirt.fcgi	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/code/invirt.fcgi	(revision 2955)
@@ -0,0 +1,69 @@
+#!/usr/bin/python
+"""Main FastCGI entry point for web interface"""
+
+import cherrypy
+import os
+import sys
+
+import main
+
+dev = False
+base_dir = os.path.dirname(__file__)
+
+def usage():
+    argv0_dir = os.path.dirname(sys.argv[0])
+    print >>sys.stderr, """%s <unauth|auth> [config]
+
+Or via the provided wrapper scripts:
+%s/auth.fcgi [config]
+%s/unauth.fcgi [config]
+
+Run server as FastCGI, with CherryPy config from "main.conf".
+With `config`, run standalone with CherryPy config from `config`.
+
+Serve the authenticated site with 'auth' or under 'auth.fcgi',
+and the unauthenticated site with 'unauth' or under 'unauth.fcgi'.
+""" % (sys.argv[0], argv0_dir, argv0_dir)
+    sys.exit(2)
+
+if __name__ == "__main__":
+    if '-h' in sys.argv or '--help' in sys.argv:
+        usage()
+    if not (2 <= len(sys.argv) <= 3):
+        usage()
+
+    mode = sys.argv[1]
+    if len(sys.argv) == 3:
+        conf_file = sys.argv[2]
+        dev = True
+    else:
+        conf_file = os.path.join(base_dir, 'main.conf')
+
+    app_config = {
+        '/': {
+            'tools.invirtwebstate.on': True,
+            },
+        }
+
+    if mode.startswith('auth'):
+        root = main.InvirtWeb()
+        app_config['/']['tools.mako.module_directory'] = "/tmp/invirt-auth-web-templatecache"
+    elif mode.startswith('unauth'):
+        root = main.InvirtUnauthWeb()
+        app_config['/']['tools.mako.module_directory'] = "/tmp/invirt-unauth-web-templatecache"
+    else:
+        usage()
+
+    app = cherrypy.tree.mount(root, '/', app_config)
+    app.merge(conf_file)
+    cherrypy.config.update(conf_file)
+
+    if dev:
+        cherrypy.server.quickstart()
+        cherrypy.engine.start()
+        cherrypy.engine.block()
+    else:
+        cherrypy.engine.start(blocking=False)
+        from flup.server.fcgi import WSGIServer
+        server = WSGIServer(cherrypy.tree)
+        server.run()
Index: /package_tags/invirt-web/0.1.5/code/main.conf
===================================================================
--- /package_tags/invirt-web/0.1.5/code/main.conf	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/code/main.conf	(revision 2955)
@@ -0,0 +1,10 @@
+# This file is used when the web interface is loaded as a FastCGI
+[global]
+#auto_reload doesn't work with FastCGI
+engine.auto_reload = False
+tools.remote_user_login.on = True
+
+engine.SIGHUP = None
+engine.SIGTERM = None
+
+log.screen = False
Index: /package_tags/invirt-web/0.1.5/code/main.py
===================================================================
--- /package_tags/invirt-web/0.1.5/code/main.py	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/code/main.py	(revision 2955)
@@ -0,0 +1,672 @@
+#!/usr/bin/python
+"""Main CGI script for web interface"""
+
+import base64
+import cPickle
+import cgi
+import datetime
+import hmac
+import os
+import random
+import sha
+import sys
+import time
+import urllib
+import socket
+import cherrypy
+from cherrypy import _cperror
+from StringIO import StringIO
+
+def printError():
+    """Revert stderr to stdout, and print the contents of stderr"""
+    if isinstance(sys.stderr, StringIO):
+        print revertStandardError()
+
+if __name__ == '__main__':
+    import atexit
+    atexit.register(printError)
+
+import validation
+import cache_acls
+from webcommon import State
+import controls
+from getafsgroups import getAfsGroupMembers
+from invirt import database
+from invirt.database import Machine, CDROM, session, connect, MachineAccess, Type, Autoinstall
+from invirt.config import structs as config
+from invirt.common import InvalidInput, CodeError
+
+from view import View, revertStandardError
+
+
+static_dir = os.path.join(os.path.dirname(__file__), 'static')
+InvirtStatic = cherrypy.tools.staticdir.handler(
+    root=static_dir,
+    dir=static_dir,
+    section='/static')
+
+class InvirtUnauthWeb(View):
+    static = InvirtStatic
+
+    @cherrypy.expose
+    @cherrypy.tools.mako(filename="/unauth.mako")
+    def index(self):
+        return dict(simple=True)
+
+class InvirtWeb(View):
+    def __init__(self):
+        super(self.__class__,self).__init__()
+        connect()
+        self._cp_config['tools.require_login.on'] = True
+        self._cp_config['tools.catch_stderr.on'] = True
+        self._cp_config['tools.mako.imports'] = ['from invirt.config import structs as config',
+                                                 'from invirt import database']
+        self._cp_config['request.error_response'] = self.handle_error
+
+    static = InvirtStatic
+
+    @cherrypy.expose
+    @cherrypy.tools.mako(filename="/invalid.mako")
+    def invalidInput(self):
+        """Print an error page when an InvalidInput exception occurs"""
+        err = cherrypy.request.prev.params["err"]
+        emsg = cherrypy.request.prev.params["emsg"]
+        d = dict(err_field=err.err_field,
+                 err_value=str(err.err_value), stderr=emsg,
+                 errorMessage=str(err))
+        return d
+
+    @cherrypy.expose
+    @cherrypy.tools.mako(filename="/error.mako")
+    def error(self):
+        """Print an error page when an exception occurs"""
+        op = cherrypy.request.prev.path_info
+        username = cherrypy.request.login
+        err = cherrypy.request.prev.params["err"]
+        emsg = cherrypy.request.prev.params["emsg"]
+        traceback = cherrypy.request.prev.params["traceback"]
+        d = dict(op=op, user=username, fields=cherrypy.request.prev.params,
+                 errorMessage=str(err), stderr=emsg, traceback=traceback)
+        error_raw = cherrypy.request.lookup.get_template("/error_raw.mako")
+        details = error_raw.render(**d)
+        exclude = config.web.errormail_exclude
+        if username not in exclude and '*' not in exclude:
+            send_error_mail('xvm error on %s for %s: %s' % (op, cherrypy.request.login, err),
+                            details)
+        d['details'] = details
+        return d
+
+    def __getattr__(self, name):
+        if name in ("admin", "overlord"):
+            if not cherrypy.request.login in getAfsGroupMembers(config.adminacl, config.authz.afs.cells[0].cell):
+                raise InvalidInput('username', cherrypy.request.login,
+                                   'Not in admin group %s.' % config.adminacl)
+            cherrypy.request.state = State(cherrypy.request.login, isadmin=True)
+            return self
+        else:
+            return super(InvirtWeb, self).__getattr__(name)
+
+    def handle_error(self):
+        err = sys.exc_info()[1]
+        if isinstance(err, InvalidInput):
+            cherrypy.request.params['err'] = err
+            cherrypy.request.params['emsg'] = revertStandardError()
+            raise cherrypy.InternalRedirect('/invalidInput')
+        if not cherrypy.request.prev or 'err' not in cherrypy.request.prev.params:
+            cherrypy.request.params['err'] = err
+            cherrypy.request.params['emsg'] = revertStandardError()
+            cherrypy.request.params['traceback'] = _cperror.format_exc()
+            raise cherrypy.InternalRedirect('/error')
+        # fall back to cherrypy default error page
+        cherrypy.HTTPError(500).set_response()
+
+    @cherrypy.expose
+    @cherrypy.tools.mako(filename="/list.mako")
+    def list(self, result=None):
+        """Handler for list requests."""
+        d = getListDict(cherrypy.request.login, cherrypy.request.state)
+        if result is not None:
+            d['result'] = result
+        return d
+    index=list
+
+    @cherrypy.expose
+    @cherrypy.tools.mako(filename="/help.mako")
+    def help(self, subject=None, simple=False):
+        """Handler for help messages."""
+
+        help_mapping = {
+            'Autoinstalls': """
+The autoinstaller builds a minimal Debian or Ubuntu system to run as a
+ParaVM.  You can access the resulting system by logging into the <a
+href="help?simple=true&subject=ParaVM+Console">serial console server</a>
+with your Kerberos tickets; there is no root password so sshd will
+refuse login.</p>
+
+<p>Under the covers, the autoinstaller uses our own patched version of
+xen-create-image, which is a tool based on debootstrap.  If you log
+into the serial console while the install is running, you can watch
+it.
+""",
+            'ParaVM Console': """
+ParaVM machines do not support local console access over VNC.  To
+access the serial console of these machines, you can SSH with Kerberos
+to %s, using the name of the machine as your
+username.""" % config.console.hostname,
+            'HVM/ParaVM': """
+HVM machines use the virtualization features of the processor, while
+ParaVM machines rely on a modified kernel to communicate directly with
+the hypervisor.  HVMs support boot CDs of any operating system, and
+the VNC console applet.  The three-minute autoinstaller produces
+ParaVMs.  ParaVMs typically are more efficient, and always support the
+<a href="help?subject=ParaVM+Console">console server</a>.</p>
+
+<p>More details are <a
+href="https://xvm.scripts.mit.edu/wiki/Paravirtualization">on the
+wiki</a>, including steps to prepare an HVM guest to boot as a ParaVM
+(which you can skip by using the autoinstaller to begin with.)</p>
+
+<p>We recommend using a ParaVM when possible and an HVM when necessary.
+""",
+            'CPU Weight': """
+Don't ask us!  We're as mystified as you are.""",
+            'Owner': """
+The owner field is used to determine <a
+href="help?subject=Quotas">quotas</a>.  It must be the name of a
+locker that you are an AFS administrator of.  In particular, you or an
+AFS group you are a member of must have AFS rlidwka bits on the
+locker.  You can check who administers the LOCKER locker using the
+commands 'attach LOCKER; fs la /mit/LOCKER' on Athena.)  See also <a
+href="help?subject=Administrator">administrator</a>.""",
+            'Administrator': """
+The administrator field determines who can access the console and
+power on and off the machine.  This can be either a user or a moira
+group.""",
+            'Quotas': """
+Quotas are determined on a per-locker basis.  Each locker may have a
+maximum of 512 mebibytes of active ram, 50 gibibytes of disk, and 4
+active machines.""",
+            'Console': """
+<strong>Framebuffer:</strong> At a Linux boot prompt in your VM, try
+setting <tt>fb=false</tt> to disable the framebuffer.  If you don't,
+your machine will run just fine, but the applet's display of the
+console will suffer artifacts.
+""",
+            'Windows': """
+<strong>Windows Vista:</strong> The Vista image is licensed for all MIT students and will automatically activate off the network; see <a href="/static/msca-email.txt">the licensing confirmation e-mail</a> for details. The installer requires 512 MiB RAM and at least 7.5 GiB disk space (15 GiB or more recommended).<br>
+<strong>Windows XP:</strong> This is the volume license CD image. You will need your own volume license key to complete the install. We do not have these available for the general MIT community; ask your department if they have one, or visit <a href="http://msca.mit.edu/">http://msca.mit.edu/</a> if you are staff/faculty to request one.
+"""
+            }
+
+        if not subject:
+            subject = sorted(help_mapping.keys())
+        if not isinstance(subject, list):
+            subject = [subject]
+
+        return dict(simple=simple,
+                    subjects=subject,
+                    mapping=help_mapping)
+    help._cp_config['tools.require_login.on'] = False
+
+    def parseCreate(self, fields):
+        kws = dict([(kw, fields[kw]) for kw in
+         'name description owner memory disksize vmtype cdrom autoinstall'.split()
+                    if fields[kw]])
+        validate = validation.Validate(cherrypy.request.login,
+                                       cherrypy.request.state,
+                                       strict=True, **kws)
+        return dict(contact=cherrypy.request.login, name=validate.name,
+                    description=validate.description, memory=validate.memory,
+                    disksize=validate.disksize, owner=validate.owner,
+                    machine_type=getattr(validate, 'vmtype', Defaults.type),
+                    cdrom=getattr(validate, 'cdrom', None),
+                    autoinstall=getattr(validate, 'autoinstall', None))
+
+    @cherrypy.expose
+    @cherrypy.tools.mako(filename="/list.mako")
+    @cherrypy.tools.require_POST()
+    def create(self, **fields):
+        """Handler for create requests."""
+        try:
+            parsed_fields = self.parseCreate(fields)
+            machine = controls.createVm(cherrypy.request.login,
+                                        cherrypy.request.state, **parsed_fields)
+        except InvalidInput, err:
+            pass
+        else:
+            err = None
+        cherrypy.request.state.clear() #Changed global state
+        d = getListDict(cherrypy.request.login, cherrypy.request.state)
+        d['err'] = err
+        if err:
+            for field, value in fields.items():
+                setattr(d['defaults'], field, value)
+        else:
+            d['new_machine'] = parsed_fields['name']
+        return d
+
+    @cherrypy.expose
+    @cherrypy.tools.mako(filename="/helloworld.mako")
+    def helloworld(self, **kwargs):
+        return {'request': cherrypy.request, 'kwargs': kwargs}
+    helloworld._cp_config['tools.require_login.on'] = False
+
+    @cherrypy.expose
+    def errortest(self):
+        """Throw an error, to test the error-tracing mechanisms."""
+        print >>sys.stderr, "look ma, it's a stderr"
+        raise RuntimeError("test of the emergency broadcast system")
+
+    class MachineView(View):
+        def __getattr__(self, name):
+            """Synthesize attributes to allow RESTful URLs like
+            /machine/13/info. This is hairy. CherryPy 3.2 adds a
+            method called _cp_dispatch that allows you to explicitly
+            handle URLs that can't be mapped, and it allows you to
+            rewrite the path components and continue processing.
+
+            This function gets the next path component being resolved
+            as a string. _cp_dispatch will get an array of strings
+            representing any subsequent path components as well."""
+
+            try:
+                cherrypy.request.params['machine_id'] = int(name)
+                return self
+            except ValueError:
+                return None
+
+        @cherrypy.expose
+        @cherrypy.tools.mako(filename="/info.mako")
+        def info(self, machine_id):
+            """Handler for info on a single VM."""
+            machine = validation.Validate(cherrypy.request.login,
+                                          cherrypy.request.state,
+                                          machine_id=machine_id).machine
+            d = infoDict(cherrypy.request.login, cherrypy.request.state, machine)
+            return d
+        index = info
+
+        @cherrypy.expose
+        @cherrypy.tools.mako(filename="/info.mako")
+        @cherrypy.tools.require_POST()
+        def modify(self, machine_id, **fields):
+            """Handler for modifying attributes of a machine."""
+            try:
+                modify_dict = modifyDict(cherrypy.request.login,
+                                         cherrypy.request.state,
+                                         machine_id, fields)
+            except InvalidInput, err:
+                result = None
+                machine = validation.Validate(cherrypy.request.login,
+                                              cherrypy.request.state,
+                                              machine_id=machine_id).machine
+            else:
+                machine = modify_dict['machine']
+                result = 'Success!'
+                err = None
+            info_dict = infoDict(cherrypy.request.login,
+                                 cherrypy.request.state, machine)
+            info_dict['err'] = err
+            if err:
+                for field, value in fields.items():
+                    setattr(info_dict['defaults'], field, value)
+            info_dict['result'] = result
+            return info_dict
+
+        @cherrypy.expose
+        @cherrypy.tools.mako(filename="/vnc.mako")
+        def vnc(self, machine_id):
+            """VNC applet page.
+
+            Note that due to same-domain restrictions, the applet connects to
+            the webserver, which needs to forward those requests to the xen
+            server.  The Xen server runs another proxy that (1) authenticates
+            and (2) finds the correct port for the VM.
+
+            You might want iptables like:
+
+            -t nat -A PREROUTING -s ! 18.181.0.60 -i eth1 -p tcp -m tcp \
+            --dport 10003 -j DNAT --to-destination 18.181.0.60:10003
+            -t nat -A POSTROUTING -d 18.181.0.60 -o eth1 -p tcp -m tcp \
+            --dport 10003 -j SNAT --to-source 18.187.7.142
+            -A FORWARD -d 18.181.0.60 -i eth1 -o eth1 -p tcp -m tcp \
+            --dport 10003 -j ACCEPT
+
+            Remember to enable iptables!
+            echo 1 > /proc/sys/net/ipv4/ip_forward
+            """
+            machine = validation.Validate(cherrypy.request.login,
+                                          cherrypy.request.state,
+                                          machine_id=machine_id).machine
+            token = controls.vnctoken(machine)
+            host = controls.listHost(machine)
+            if host:
+                port = 10003 + [h.hostname for h in config.hosts].index(host)
+            else:
+                port = 5900 # dummy
+
+            status = controls.statusInfo(machine)
+            has_vnc = hasVnc(status)
+
+            d = dict(on=status,
+                     has_vnc=has_vnc,
+                     machine=machine,
+                     hostname=cherrypy.request.local.name,
+                     port=port,
+                     authtoken=token)
+            return d
+
+        @cherrypy.expose
+        @cherrypy.tools.mako(filename="/command.mako")
+        @cherrypy.tools.require_POST()
+        def command(self, command_name, machine_id, **kwargs):
+            """Handler for running commands like boot and delete on a VM."""
+            back = kwargs.get('back')
+            if command_name == 'delete':
+                back = 'list'
+            try:
+                d = controls.commandResult(cherrypy.request.login,
+                                           cherrypy.request.state,
+                                           command_name, machine_id, kwargs)
+            except InvalidInput, err:
+                if not back:
+                    raise
+                print >> sys.stderr, err
+                result = str(err)
+            else:
+                result = 'Success!'
+                if not back:
+                    return d
+            if back == 'list':
+                cherrypy.request.state.clear() #Changed global state
+                raise cherrypy.InternalRedirect('/list?result=%s'
+                                                % urllib.quote(result))
+            elif back == 'info':
+                raise cherrypy.HTTPRedirect(cherrypy.request.base
+                                            + '/machine/%d/' % machine_id,
+                                            status=303)
+            else:
+                raise InvalidInput('back', back, 'Not a known back page.')
+
+    machine = MachineView()
+
+
+class Defaults:
+    """Class to store default values for fields."""
+    memory = 256
+    disk = 4.0
+    cdrom = ''
+    autoinstall = ''
+    name = ''
+    description = ''
+    administrator = ''
+    type = 'linux-hvm'
+
+    def __init__(self, max_memory=None, max_disk=None, **kws):
+        if max_memory is not None:
+            self.memory = min(self.memory, max_memory)
+        if max_disk is not None:
+            self.disk = min(self.disk, max_disk)
+        for key in kws:
+            setattr(self, key, kws[key])
+
+def hasVnc(status):
+    """Does the machine with a given status list support VNC?"""
+    if status is None:
+        return False
+    for l in status:
+        if l[0] == 'device' and l[1][0] == 'vfb':
+            d = dict(l[1][1:])
+            return 'location' in d
+    return False
+
+
+def getListDict(username, state):
+    """Gets the list of local variables used by list.tmpl."""
+    machines = state.machines
+    on = {}
+    has_vnc = {}
+    installing = {}
+    xmlist = state.xmlist
+    for m in machines:
+        if m not in xmlist:
+            has_vnc[m] = 'Off'
+            m.uptime = None
+        else:
+            m.uptime = xmlist[m]['uptime']
+            installing[m] = bool(xmlist[m].get('autoinstall'))
+            if xmlist[m]['console']:
+                has_vnc[m] = True
+            elif m.type.hvm:
+                has_vnc[m] = "WTF?"
+            else:
+                has_vnc[m] = "ParaVM"
+    max_memory = validation.maxMemory(username, state)
+    max_disk = validation.maxDisk(username)
+    defaults = Defaults(max_memory=max_memory,
+                        max_disk=max_disk,
+                        owner=username)
+    def sortkey(machine):
+        return (machine.owner != username, machine.owner, machine.name)
+    machines = sorted(machines, key=sortkey)
+    d = dict(user=username,
+             cant_add_vm=validation.cantAddVm(username, state),
+             max_memory=max_memory,
+             max_disk=max_disk,
+             defaults=defaults,
+             machines=machines,
+             has_vnc=has_vnc,
+             installing=installing)
+    return d
+
+def getHostname(nic):
+    """Find the hostname associated with a NIC.
+
+    XXX this should be merged with the similar logic in DNS and DHCP.
+    """
+    if nic.hostname:
+        hostname = nic.hostname
+    elif nic.machine:
+        hostname = nic.machine.name
+    else:
+        return None
+    if '.' in hostname:
+        return hostname
+    else:
+        return hostname + '.' + config.dns.domains[0]
+
+def getNicInfo(data_dict, machine):
+    """Helper function for info, get data on nics for a machine.
+
+    Modifies data_dict to include the relevant data, and returns a list
+    of (key, name) pairs to display "name: data_dict[key]" to the user.
+    """
+    data_dict['num_nics'] = len(machine.nics)
+    nic_fields_template = [('nic%s_hostname', 'NIC %s Hostname'),
+                           ('nic%s_mac', 'NIC %s MAC Addr'),
+                           ('nic%s_ip', 'NIC %s IP'),
+                           ]
+    nic_fields = []
+    for i in range(len(machine.nics)):
+        nic_fields.extend([(x % i, y % i) for x, y in nic_fields_template])
+        data_dict['nic%s_hostname' % i] = getHostname(machine.nics[i])
+        data_dict['nic%s_mac' % i] = machine.nics[i].mac_addr
+        data_dict['nic%s_ip' % i] = machine.nics[i].ip
+    if len(machine.nics) == 1:
+        nic_fields = [(x, y.replace('NIC 0 ', '')) for x, y in nic_fields]
+    return nic_fields
+
+def getDiskInfo(data_dict, machine):
+    """Helper function for info, get data on disks for a machine.
+
+    Modifies data_dict to include the relevant data, and returns a list
+    of (key, name) pairs to display "name: data_dict[key]" to the user.
+    """
+    data_dict['num_disks'] = len(machine.disks)
+    disk_fields_template = [('%s_size', '%s size')]
+    disk_fields = []
+    for disk in machine.disks:
+        name = disk.guest_device_name
+        disk_fields.extend([(x % name, y % name) for x, y in
+                            disk_fields_template])
+        data_dict['%s_size' % name] = "%0.1f GiB" % (disk.size / 1024.)
+    return disk_fields
+
+def modifyDict(username, state, machine_id, fields):
+    """Modify a machine as specified by CGI arguments.
+
+    Return a dict containing the machine that was modified.
+    """
+    olddisk = {}
+    session.begin()
+    try:
+        kws = dict((kw, fields[kw]) for kw in
+         'owner admin contact name description memory vmtype disksize'.split()
+                    if fields.get(kw))
+        kws['machine_id'] = machine_id
+        validate = validation.Validate(username, state, **kws)
+        machine = validate.machine
+        oldname = machine.name
+
+        if hasattr(validate, 'memory'):
+            machine.memory = validate.memory
+
+        if hasattr(validate, 'vmtype'):
+            machine.type = validate.vmtype
+
+        if hasattr(validate, 'disksize'):
+            disksize = validate.disksize
+            disk = machine.disks[0]
+            if disk.size != disksize:
+                olddisk[disk.guest_device_name] = disksize
+                disk.size = disksize
+                session.save_or_update(disk)
+
+        update_acl = False
+        if hasattr(validate, 'owner') and validate.owner != machine.owner:
+            machine.owner = validate.owner
+            update_acl = True
+        if hasattr(validate, 'name'):
+            machine.name = validate.name
+            for n in machine.nics:
+                if n.hostname == oldname:
+                    n.hostname = validate.name
+        if hasattr(validate, 'description'):
+            machine.description = validate.description
+        if hasattr(validate, 'admin') and validate.admin != machine.administrator:
+            machine.administrator = validate.admin
+            update_acl = True
+        if hasattr(validate, 'contact'):
+            machine.contact = validate.contact
+
+        session.save_or_update(machine)
+        if update_acl:
+            cache_acls.refreshMachine(machine)
+        session.commit()
+    except:
+        session.rollback()
+        raise
+    for diskname in olddisk:
+        controls.resizeDisk(oldname, diskname, str(olddisk[diskname]))
+    if hasattr(validate, 'name'):
+        controls.renameMachine(machine, oldname, validate.name)
+    return dict(machine=machine)
+
+def infoDict(username, state, machine):
+    """Get the variables used by info.tmpl."""
+    status = controls.statusInfo(machine)
+    has_vnc = hasVnc(status)
+    if status is None:
+        main_status = dict(name=machine.name,
+                           memory=str(machine.memory))
+        uptime = None
+        cputime = None
+    else:
+        main_status = dict(status[1:])
+        main_status['host'] = controls.listHost(machine)
+        start_time = float(main_status.get('start_time', 0))
+        uptime = datetime.timedelta(seconds=int(time.time()-start_time))
+        cpu_time_float = float(main_status.get('cpu_time', 0))
+        cputime = datetime.timedelta(seconds=int(cpu_time_float))
+    display_fields = [('name', 'Name'),
+                      ('description', 'Description'),
+                      ('owner', 'Owner'),
+                      ('administrator', 'Administrator'),
+                      ('contact', 'Contact'),
+                      ('type', 'Type'),
+                      'NIC_INFO',
+                      ('uptime', 'uptime'),
+                      ('cputime', 'CPU usage'),
+                      ('host', 'Hosted on'),
+                      ('memory', 'RAM'),
+                      'DISK_INFO',
+                      ('state', 'state (xen format)'),
+                      ]
+    fields = []
+    machine_info = {}
+    machine_info['name'] = machine.name
+    machine_info['description'] = machine.description
+    machine_info['type'] = machine.type.hvm and 'HVM' or 'ParaVM'
+    machine_info['owner'] = machine.owner
+    machine_info['administrator'] = machine.administrator
+    machine_info['contact'] = machine.contact
+
+    nic_fields = getNicInfo(machine_info, machine)
+    nic_point = display_fields.index('NIC_INFO')
+    display_fields = (display_fields[:nic_point] + nic_fields +
+                      display_fields[nic_point+1:])
+
+    disk_fields = getDiskInfo(machine_info, machine)
+    disk_point = display_fields.index('DISK_INFO')
+    display_fields = (display_fields[:disk_point] + disk_fields +
+                      display_fields[disk_point+1:])
+
+    main_status['memory'] += ' MiB'
+    for field, disp in display_fields:
+        if field in ('uptime', 'cputime') and locals()[field] is not None:
+            fields.append((disp, locals()[field]))
+        elif field in machine_info:
+            fields.append((disp, machine_info[field]))
+        elif field in main_status:
+            fields.append((disp, main_status[field]))
+        else:
+            pass
+            #fields.append((disp, None))
+
+    max_mem = validation.maxMemory(machine.owner, state, machine, False)
+    max_disk = validation.maxDisk(machine.owner, machine)
+    defaults = Defaults()
+    for name in 'machine_id name description administrator owner memory contact'.split():
+        if getattr(machine, name):
+            setattr(defaults, name, getattr(machine, name))
+    defaults.type = machine.type.type_id
+    defaults.disk = "%0.2f" % (machine.disks[0].size/1024.)
+    d = dict(user=username,
+             on=status is not None,
+             machine=machine,
+             defaults=defaults,
+             has_vnc=has_vnc,
+             uptime=str(uptime),
+             ram=machine.memory,
+             max_mem=max_mem,
+             max_disk=max_disk,
+             fields = fields)
+    return d
+
+def send_error_mail(subject, body):
+    import subprocess
+
+    to = config.web.errormail
+    mail = """To: %s
+From: root@%s
+Subject: %s
+
+%s
+""" % (to, config.web.hostname, subject, body)
+    p = subprocess.Popen(['/usr/sbin/sendmail', '-f', to, to],
+                         stdin=subprocess.PIPE)
+    p.stdin.write(mail)
+    p.stdin.close()
+    p.wait()
+
+random.seed() #sigh
Index: /package_tags/invirt-web/0.1.5/code/static/VncViewer.jar
===================================================================
--- /package_tags/invirt-web/0.1.5/code/static/VncViewer.jar	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/code/static/VncViewer.jar	(revision 2955)
@@ -0,0 +1,1 @@
+link /usr/share/invirt-vnc-client/VncViewer.jar
Index: /package_tags/invirt-web/0.1.5/code/static/layout.css
===================================================================
--- /package_tags/invirt-web/0.1.5/code/static/layout.css	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/code/static/layout.css	(revision 2955)
@@ -0,0 +1,30 @@
+/*
+  Good layout ideas stolen from Debathena.
+  Hey, we use some different fonts (in style.css.)
+  And the background color is unmistakably different.
+  Some other things are tweaked too.
+*/
+
+/* This file contains screen-only layout declarations that won't be
+   used for printing. */
+
+/* Make <body /> show up as a centered white box with rounded border,
+   over the darker enclosing <html />. */
+html {
+    padding: .75em;
+    background: #09c;
+}
+body {
+    position: relative;
+    margin: 0 auto;
+    padding: 1.2em;
+    border: 1px solid black;
+    -moz-border-radius: .4em;
+    -webkit-border-radius: .4em;
+    border-radius: .4em;
+    background: #fff;
+}
+
+body.help {
+    max-width: 50em;
+}
Index: /package_tags/invirt-web/0.1.5/code/static/msca-email.txt
===================================================================
--- /package_tags/invirt-web/0.1.5/code/static/msca-email.txt	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/code/static/msca-email.txt	(revision 2955)
@@ -0,0 +1,65 @@
+From: MIT MS Campus Agreement <ms-campus-agreement@MIT.EDU>
+Subject: Windows Vista upgrade - student download
+
+Greetings,
+
+Thank-you for visiting Information Services and Technology's (IS&T) download 
+site for Windows Vista Enterprise.  This software upgrade service is 
+provided via MIT's Microsoft Campus Agreement (MSCA).
+
+MIT has signed a three year Campus Agreement with Microsoft effective 
+through June 2007 which allows IS&T to provide Windows Vista Enterprise 
+software upgrades at no cost to MIT undergraduate and graduate students. 
+MIT students are entitled to install this software on one personally owned 
+machine to be used for educational purposes.  Graduating students retain the 
+continued right to run the last version of the software received while at 
+MIT by completing the Campus Agreement Student License Confirmation.  This 
+agreement will be e-mailed to you during your last semester at MIT.
+
+Undergraduate or graduate students who withdraw, transfer, or otherwise 
+leave MIT prior to graduation do not have the continued right to use this 
+software and should delete it from your machines.
+
+Your right to use the software shall be governed by the most current license 
+rights, which you may view at
+
+     <http://www.microsoft.com/education/license/terms.asp>.
+
+The following website includes helpful information about Windows Vista 
+Enterprise and topics to consider prior to upgrading one's machine
+
+     <http://itinfo.mit.edu/product.php?vid=735>
+
+Windows Vista Enterprise does not require a product key to install or use 
+the software.  Instead, Activation is used instead of a product key.  If 
+properly configured, your machine will automatically activate when on the 
+MIT Network.  If you have troubles activating your system or are using on a 
+machine that is not on the MIT Network, such as a home machine, see the 
+Activation instructions at
+
+        <http://itinfo.mit.edu/article.php?id=8299>
+
+IS&T wishes to remind colleagues and students of the importance of keeping 
+one's computer current with operating system patches.  IS&T recommends the 
+use of vendor's automatic update services in tandem of our local 
+implementations of...
+
+     MIT Windows Automatic Update Service (WAUS) 
+     <http://web.mit.edu/ist/topics/windows/updates/>
+
+What is MIT Windows Automatic Update Service?
+
+The MIT Windows Automatic Update Service (WAUS) enables the MIT community to 
+utilize Microsoft's "Automatic Update" feature with a more conservative 
+selection of patches -- focused on critical security updates -- than those 
+available directly from Microsoft. This service may be used by MIT faculty, 
+staff, and students on MIT-owned and personal machines.
+
+Should you have any questions or concerns about the operating system 
+upgrade, please contact the Computing Help Desk, <computing-help@mit.edu> 
+Questions, comments or suggestions about the Campus Agreement may be 
+directed to the Software Release Team, <swrt@mit.edu>
+
+Cordially,
+
+Information Services and Technology
Index: /package_tags/invirt-web/0.1.5/code/static/prototype.js
===================================================================
--- /package_tags/invirt-web/0.1.5/code/static/prototype.js	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/code/static/prototype.js	(revision 2955)
@@ -0,0 +1,4221 @@
+/*  Prototype JavaScript framework, version 1.6.0.2
+ *  (c) 2005-2008 Sam Stephenson
+ *
+ *  Prototype is freely distributable under the terms of an MIT-style license.
+ *  For details, see the Prototype web site: http://www.prototypejs.org/
+ *
+ *--------------------------------------------------------------------------*/
+
+var Prototype = {
+  Version: '1.6.0.2',
+
+  Browser: {
+    IE:     !!(window.attachEvent && !window.opera),
+    Opera:  !!window.opera,
+    WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
+    Gecko:  navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
+    MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
+  },
+
+  BrowserFeatures: {
+    XPath: !!document.evaluate,
+    ElementExtensions: !!window.HTMLElement,
+    SpecificElementExtensions:
+      document.createElement('div').__proto__ &&
+      document.createElement('div').__proto__ !==
+        document.createElement('form').__proto__
+  },
+
+  ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
+  JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,
+
+  emptyFunction: function() { },
+  K: function(x) { return x }
+};
+
+if (Prototype.Browser.MobileSafari)
+  Prototype.BrowserFeatures.SpecificElementExtensions = false;
+
+
+/* Based on Alex Arnell's inheritance implementation. */
+var Class = {
+  create: function() {
+    var parent = null, properties = $A(arguments);
+    if (Object.isFunction(properties[0]))
+      parent = properties.shift();
+
+    function klass() {
+      this.initialize.apply(this, arguments);
+    }
+
+    Object.extend(klass, Class.Methods);
+    klass.superclass = parent;
+    klass.subclasses = [];
+
+    if (parent) {
+      var subclass = function() { };
+      subclass.prototype = parent.prototype;
+      klass.prototype = new subclass;
+      parent.subclasses.push(klass);
+    }
+
+    for (var i = 0; i < properties.length; i++)
+      klass.addMethods(properties[i]);
+
+    if (!klass.prototype.initialize)
+      klass.prototype.initialize = Prototype.emptyFunction;
+
+    klass.prototype.constructor = klass;
+
+    return klass;
+  }
+};
+
+Class.Methods = {
+  addMethods: function(source) {
+    var ancestor   = this.superclass && this.superclass.prototype;
+    var properties = Object.keys(source);
+
+    if (!Object.keys({ toString: true }).length)
+      properties.push("toString", "valueOf");
+
+    for (var i = 0, length = properties.length; i < length; i++) {
+      var property = properties[i], value = source[property];
+      if (ancestor && Object.isFunction(value) &&
+          value.argumentNames().first() == "$super") {
+        var method = value, value = Object.extend((function(m) {
+          return function() { return ancestor[m].apply(this, arguments) };
+        })(property).wrap(method), {
+          valueOf:  function() { return method },
+          toString: function() { return method.toString() }
+        });
+      }
+      this.prototype[property] = value;
+    }
+
+    return this;
+  }
+};
+
+var Abstract = { };
+
+Object.extend = function(destination, source) {
+  for (var property in source)
+    destination[property] = source[property];
+  return destination;
+};
+
+Object.extend(Object, {
+  inspect: function(object) {
+    try {
+      if (Object.isUndefined(object)) return 'undefined';
+      if (object === null) return 'null';
+      return object.inspect ? object.inspect() : String(object);
+    } catch (e) {
+      if (e instanceof RangeError) return '...';
+      throw e;
+    }
+  },
+
+  toJSON: function(object) {
+    var type = typeof object;
+    switch (type) {
+      case 'undefined':
+      case 'function':
+      case 'unknown': return;
+      case 'boolean': return object.toString();
+    }
+
+    if (object === null) return 'null';
+    if (object.toJSON) return object.toJSON();
+    if (Object.isElement(object)) return;
+
+    var results = [];
+    for (var property in object) {
+      var value = Object.toJSON(object[property]);
+      if (!Object.isUndefined(value))
+        results.push(property.toJSON() + ': ' + value);
+    }
+
+    return '{' + results.join(', ') + '}';
+  },
+
+  toQueryString: function(object) {
+    return $H(object).toQueryString();
+  },
+
+  toHTML: function(object) {
+    return object && object.toHTML ? object.toHTML() : String.interpret(object);
+  },
+
+  keys: function(object) {
+    var keys = [];
+    for (var property in object)
+      keys.push(property);
+    return keys;
+  },
+
+  values: function(object) {
+    var values = [];
+    for (var property in object)
+      values.push(object[property]);
+    return values;
+  },
+
+  clone: function(object) {
+    return Object.extend({ }, object);
+  },
+
+  isElement: function(object) {
+    return object && object.nodeType == 1;
+  },
+
+  isArray: function(object) {
+    return object != null && typeof object == "object" &&
+      'splice' in object && 'join' in object;
+  },
+
+  isHash: function(object) {
+    return object instanceof Hash;
+  },
+
+  isFunction: function(object) {
+    return typeof object == "function";
+  },
+
+  isString: function(object) {
+    return typeof object == "string";
+  },
+
+  isNumber: function(object) {
+    return typeof object == "number";
+  },
+
+  isUndefined: function(object) {
+    return typeof object == "undefined";
+  }
+});
+
+Object.extend(Function.prototype, {
+  argumentNames: function() {
+    var names = this.toString().match(/^[\s\(]*function[^(]*\((.*?)\)/)[1].split(",").invoke("strip");
+    return names.length == 1 && !names[0] ? [] : names;
+  },
+
+  bind: function() {
+    if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this;
+    var __method = this, args = $A(arguments), object = args.shift();
+    return function() {
+      return __method.apply(object, args.concat($A(arguments)));
+    }
+  },
+
+  bindAsEventListener: function() {
+    var __method = this, args = $A(arguments), object = args.shift();
+    return function(event) {
+      return __method.apply(object, [event || window.event].concat(args));
+    }
+  },
+
+  curry: function() {
+    if (!arguments.length) return this;
+    var __method = this, args = $A(arguments);
+    return function() {
+      return __method.apply(this, args.concat($A(arguments)));
+    }
+  },
+
+  delay: function() {
+    var __method = this, args = $A(arguments), timeout = args.shift() * 1000;
+    return window.setTimeout(function() {
+      return __method.apply(__method, args);
+    }, timeout);
+  },
+
+  wrap: function(wrapper) {
+    var __method = this;
+    return function() {
+      return wrapper.apply(this, [__method.bind(this)].concat($A(arguments)));
+    }
+  },
+
+  methodize: function() {
+    if (this._methodized) return this._methodized;
+    var __method = this;
+    return this._methodized = function() {
+      return __method.apply(null, [this].concat($A(arguments)));
+    };
+  }
+});
+
+Function.prototype.defer = Function.prototype.delay.curry(0.01);
+
+Date.prototype.toJSON = function() {
+  return '"' + this.getUTCFullYear() + '-' +
+    (this.getUTCMonth() + 1).toPaddedString(2) + '-' +
+    this.getUTCDate().toPaddedString(2) + 'T' +
+    this.getUTCHours().toPaddedString(2) + ':' +
+    this.getUTCMinutes().toPaddedString(2) + ':' +
+    this.getUTCSeconds().toPaddedString(2) + 'Z"';
+};
+
+var Try = {
+  these: function() {
+    var returnValue;
+
+    for (var i = 0, length = arguments.length; i < length; i++) {
+      var lambda = arguments[i];
+      try {
+        returnValue = lambda();
+        break;
+      } catch (e) { }
+    }
+
+    return returnValue;
+  }
+};
+
+RegExp.prototype.match = RegExp.prototype.test;
+
+RegExp.escape = function(str) {
+  return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
+};
+
+/*--------------------------------------------------------------------------*/
+
+var PeriodicalExecuter = Class.create({
+  initialize: function(callback, frequency) {
+    this.callback = callback;
+    this.frequency = frequency;
+    this.currentlyExecuting = false;
+
+    this.registerCallback();
+  },
+
+  registerCallback: function() {
+    this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
+  },
+
+  execute: function() {
+    this.callback(this);
+  },
+
+  stop: function() {
+    if (!this.timer) return;
+    clearInterval(this.timer);
+    this.timer = null;
+  },
+
+  onTimerEvent: function() {
+    if (!this.currentlyExecuting) {
+      try {
+        this.currentlyExecuting = true;
+        this.execute();
+      } finally {
+        this.currentlyExecuting = false;
+      }
+    }
+  }
+});
+Object.extend(String, {
+  interpret: function(value) {
+    return value == null ? '' : String(value);
+  },
+  specialChar: {
+    '\b': '\\b',
+    '\t': '\\t',
+    '\n': '\\n',
+    '\f': '\\f',
+    '\r': '\\r',
+    '\\': '\\\\'
+  }
+});
+
+Object.extend(String.prototype, {
+  gsub: function(pattern, replacement) {
+    var result = '', source = this, match;
+    replacement = arguments.callee.prepareReplacement(replacement);
+
+    while (source.length > 0) {
+      if (match = source.match(pattern)) {
+        result += source.slice(0, match.index);
+        result += String.interpret(replacement(match));
+        source  = source.slice(match.index + match[0].length);
+      } else {
+        result += source, source = '';
+      }
+    }
+    return result;
+  },
+
+  sub: function(pattern, replacement, count) {
+    replacement = this.gsub.prepareReplacement(replacement);
+    count = Object.isUndefined(count) ? 1 : count;
+
+    return this.gsub(pattern, function(match) {
+      if (--count < 0) return match[0];
+      return replacement(match);
+    });
+  },
+
+  scan: function(pattern, iterator) {
+    this.gsub(pattern, iterator);
+    return String(this);
+  },
+
+  truncate: function(length, truncation) {
+    length = length || 30;
+    truncation = Object.isUndefined(truncation) ? '...' : truncation;
+    return this.length > length ?
+      this.slice(0, length - truncation.length) + truncation : String(this);
+  },
+
+  strip: function() {
+    return this.replace(/^\s+/, '').replace(/\s+$/, '');
+  },
+
+  stripTags: function() {
+    return this.replace(/<\/?[^>]+>/gi, '');
+  },
+
+  stripScripts: function() {
+    return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
+  },
+
+  extractScripts: function() {
+    var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
+    var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
+    return (this.match(matchAll) || []).map(function(scriptTag) {
+      return (scriptTag.match(matchOne) || ['', ''])[1];
+    });
+  },
+
+  evalScripts: function() {
+    return this.extractScripts().map(function(script) { return eval(script) });
+  },
+
+  escapeHTML: function() {
+    var self = arguments.callee;
+    self.text.data = this;
+    return self.div.innerHTML;
+  },
+
+  unescapeHTML: function() {
+    var div = new Element('div');
+    div.innerHTML = this.stripTags();
+    return div.childNodes[0] ? (div.childNodes.length > 1 ?
+      $A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue }) :
+      div.childNodes[0].nodeValue) : '';
+  },
+
+  toQueryParams: function(separator) {
+    var match = this.strip().match(/([^?#]*)(#.*)?$/);
+    if (!match) return { };
+
+    return match[1].split(separator || '&').inject({ }, function(hash, pair) {
+      if ((pair = pair.split('='))[0]) {
+        var key = decodeURIComponent(pair.shift());
+        var value = pair.length > 1 ? pair.join('=') : pair[0];
+        if (value != undefined) value = decodeURIComponent(value);
+
+        if (key in hash) {
+          if (!Object.isArray(hash[key])) hash[key] = [hash[key]];
+          hash[key].push(value);
+        }
+        else hash[key] = value;
+      }
+      return hash;
+    });
+  },
+
+  toArray: function() {
+    return this.split('');
+  },
+
+  succ: function() {
+    return this.slice(0, this.length - 1) +
+      String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
+  },
+
+  times: function(count) {
+    return count < 1 ? '' : new Array(count + 1).join(this);
+  },
+
+  camelize: function() {
+    var parts = this.split('-'), len = parts.length;
+    if (len == 1) return parts[0];
+
+    var camelized = this.charAt(0) == '-'
+      ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
+      : parts[0];
+
+    for (var i = 1; i < len; i++)
+      camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
+
+    return camelized;
+  },
+
+  capitalize: function() {
+    return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
+  },
+
+  underscore: function() {
+    return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
+  },
+
+  dasherize: function() {
+    return this.gsub(/_/,'-');
+  },
+
+  inspect: function(useDoubleQuotes) {
+    var escapedString = this.gsub(/[\x00-\x1f\\]/, function(match) {
+      var character = String.specialChar[match[0]];
+      return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16);
+    });
+    if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"';
+    return "'" + escapedString.replace(/'/g, '\\\'') + "'";
+  },
+
+  toJSON: function() {
+    return this.inspect(true);
+  },
+
+  unfilterJSON: function(filter) {
+    return this.sub(filter || Prototype.JSONFilter, '#{1}');
+  },
+
+  isJSON: function() {
+    var str = this;
+    if (str.blank()) return false;
+    str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
+    return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
+  },
+
+  evalJSON: function(sanitize) {
+    var json = this.unfilterJSON();
+    try {
+      if (!sanitize || json.isJSON()) return eval('(' + json + ')');
+    } catch (e) { }
+    throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
+  },
+
+  include: function(pattern) {
+    return this.indexOf(pattern) > -1;
+  },
+
+  startsWith: function(pattern) {
+    return this.indexOf(pattern) === 0;
+  },
+
+  endsWith: function(pattern) {
+    var d = this.length - pattern.length;
+    return d >= 0 && this.lastIndexOf(pattern) === d;
+  },
+
+  empty: function() {
+    return this == '';
+  },
+
+  blank: function() {
+    return /^\s*$/.test(this);
+  },
+
+  interpolate: function(object, pattern) {
+    return new Template(this, pattern).evaluate(object);
+  }
+});
+
+if (Prototype.Browser.WebKit || Prototype.Browser.IE) Object.extend(String.prototype, {
+  escapeHTML: function() {
+    return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
+  },
+  unescapeHTML: function() {
+    return this.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
+  }
+});
+
+String.prototype.gsub.prepareReplacement = function(replacement) {
+  if (Object.isFunction(replacement)) return replacement;
+  var template = new Template(replacement);
+  return function(match) { return template.evaluate(match) };
+};
+
+String.prototype.parseQuery = String.prototype.toQueryParams;
+
+Object.extend(String.prototype.escapeHTML, {
+  div:  document.createElement('div'),
+  text: document.createTextNode('')
+});
+
+with (String.prototype.escapeHTML) div.appendChild(text);
+
+var Template = Class.create({
+  initialize: function(template, pattern) {
+    this.template = template.toString();
+    this.pattern = pattern || Template.Pattern;
+  },
+
+  evaluate: function(object) {
+    if (Object.isFunction(object.toTemplateReplacements))
+      object = object.toTemplateReplacements();
+
+    return this.template.gsub(this.pattern, function(match) {
+      if (object == null) return '';
+
+      var before = match[1] || '';
+      if (before == '\\') return match[2];
+
+      var ctx = object, expr = match[3];
+      var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;
+      match = pattern.exec(expr);
+      if (match == null) return before;
+
+      while (match != null) {
+        var comp = match[1].startsWith('[') ? match[2].gsub('\\\\]', ']') : match[1];
+        ctx = ctx[comp];
+        if (null == ctx || '' == match[3]) break;
+        expr = expr.substring('[' == match[3] ? match[1].length : match[0].length);
+        match = pattern.exec(expr);
+      }
+
+      return before + String.interpret(ctx);
+    });
+  }
+});
+Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
+
+var $break = { };
+
+var Enumerable = {
+  each: function(iterator, context) {
+    var index = 0;
+    iterator = iterator.bind(context);
+    try {
+      this._each(function(value) {
+        iterator(value, index++);
+      });
+    } catch (e) {
+      if (e != $break) throw e;
+    }
+    return this;
+  },
+
+  eachSlice: function(number, iterator, context) {
+    iterator = iterator ? iterator.bind(context) : Prototype.K;
+    var index = -number, slices = [], array = this.toArray();
+    while ((index += number) < array.length)
+      slices.push(array.slice(index, index+number));
+    return slices.collect(iterator, context);
+  },
+
+  all: function(iterator, context) {
+    iterator = iterator ? iterator.bind(context) : Prototype.K;
+    var result = true;
+    this.each(function(value, index) {
+      result = result && !!iterator(value, index);
+      if (!result) throw $break;
+    });
+    return result;
+  },
+
+  any: function(iterator, context) {
+    iterator = iterator ? iterator.bind(context) : Prototype.K;
+    var result = false;
+    this.each(function(value, index) {
+      if (result = !!iterator(value, index))
+        throw $break;
+    });
+    return result;
+  },
+
+  collect: function(iterator, context) {
+    iterator = iterator ? iterator.bind(context) : Prototype.K;
+    var results = [];
+    this.each(function(value, index) {
+      results.push(iterator(value, index));
+    });
+    return results;
+  },
+
+  detect: function(iterator, context) {
+    iterator = iterator.bind(context);
+    var result;
+    this.each(function(value, index) {
+      if (iterator(value, index)) {
+        result = value;
+        throw $break;
+      }
+    });
+    return result;
+  },
+
+  findAll: function(iterator, context) {
+    iterator = iterator.bind(context);
+    var results = [];
+    this.each(function(value, index) {
+      if (iterator(value, index))
+        results.push(value);
+    });
+    return results;
+  },
+
+  grep: function(filter, iterator, context) {
+    iterator = iterator ? iterator.bind(context) : Prototype.K;
+    var results = [];
+
+    if (Object.isString(filter))
+      filter = new RegExp(filter);
+
+    this.each(function(value, index) {
+      if (filter.match(value))
+        results.push(iterator(value, index));
+    });
+    return results;
+  },
+
+  include: function(object) {
+    if (Object.isFunction(this.indexOf))
+      if (this.indexOf(object) != -1) return true;
+
+    var found = false;
+    this.each(function(value) {
+      if (value == object) {
+        found = true;
+        throw $break;
+      }
+    });
+    return found;
+  },
+
+  inGroupsOf: function(number, fillWith) {
+    fillWith = Object.isUndefined(fillWith) ? null : fillWith;
+    return this.eachSlice(number, function(slice) {
+      while(slice.length < number) slice.push(fillWith);
+      return slice;
+    });
+  },
+
+  inject: function(memo, iterator, context) {
+    iterator = iterator.bind(context);
+    this.each(function(value, index) {
+      memo = iterator(memo, value, index);
+    });
+    return memo;
+  },
+
+  invoke: function(method) {
+    var args = $A(arguments).slice(1);
+    return this.map(function(value) {
+      return value[method].apply(value, args);
+    });
+  },
+
+  max: function(iterator, context) {
+    iterator = iterator ? iterator.bind(context) : Prototype.K;
+    var result;
+    this.each(function(value, index) {
+      value = iterator(value, index);
+      if (result == null || value >= result)
+        result = value;
+    });
+    return result;
+  },
+
+  min: function(iterator, context) {
+    iterator = iterator ? iterator.bind(context) : Prototype.K;
+    var result;
+    this.each(function(value, index) {
+      value = iterator(value, index);
+      if (result == null || value < result)
+        result = value;
+    });
+    return result;
+  },
+
+  partition: function(iterator, context) {
+    iterator = iterator ? iterator.bind(context) : Prototype.K;
+    var trues = [], falses = [];
+    this.each(function(value, index) {
+      (iterator(value, index) ?
+        trues : falses).push(value);
+    });
+    return [trues, falses];
+  },
+
+  pluck: function(property) {
+    var results = [];
+    this.each(function(value) {
+      results.push(value[property]);
+    });
+    return results;
+  },
+
+  reject: function(iterator, context) {
+    iterator = iterator.bind(context);
+    var results = [];
+    this.each(function(value, index) {
+      if (!iterator(value, index))
+        results.push(value);
+    });
+    return results;
+  },
+
+  sortBy: function(iterator, context) {
+    iterator = iterator.bind(context);
+    return this.map(function(value, index) {
+      return {value: value, criteria: iterator(value, index)};
+    }).sort(function(left, right) {
+      var a = left.criteria, b = right.criteria;
+      return a < b ? -1 : a > b ? 1 : 0;
+    }).pluck('value');
+  },
+
+  toArray: function() {
+    return this.map();
+  },
+
+  zip: function() {
+    var iterator = Prototype.K, args = $A(arguments);
+    if (Object.isFunction(args.last()))
+      iterator = args.pop();
+
+    var collections = [this].concat(args).map($A);
+    return this.map(function(value, index) {
+      return iterator(collections.pluck(index));
+    });
+  },
+
+  size: function() {
+    return this.toArray().length;
+  },
+
+  inspect: function() {
+    return '#<Enumerable:' + this.toArray().inspect() + '>';
+  }
+};
+
+Object.extend(Enumerable, {
+  map:     Enumerable.collect,
+  find:    Enumerable.detect,
+  select:  Enumerable.findAll,
+  filter:  Enumerable.findAll,
+  member:  Enumerable.include,
+  entries: Enumerable.toArray,
+  every:   Enumerable.all,
+  some:    Enumerable.any
+});
+function $A(iterable) {
+  if (!iterable) return [];
+  if (iterable.toArray) return iterable.toArray();
+  var length = iterable.length || 0, results = new Array(length);
+  while (length--) results[length] = iterable[length];
+  return results;
+}
+
+if (Prototype.Browser.WebKit) {
+  $A = function(iterable) {
+    if (!iterable) return [];
+    if (!(Object.isFunction(iterable) && iterable == '[object NodeList]') &&
+        iterable.toArray) return iterable.toArray();
+    var length = iterable.length || 0, results = new Array(length);
+    while (length--) results[length] = iterable[length];
+    return results;
+  };
+}
+
+Array.from = $A;
+
+Object.extend(Array.prototype, Enumerable);
+
+if (!Array.prototype._reverse) Array.prototype._reverse = Array.prototype.reverse;
+
+Object.extend(Array.prototype, {
+  _each: function(iterator) {
+    for (var i = 0, length = this.length; i < length; i++)
+      iterator(this[i]);
+  },
+
+  clear: function() {
+    this.length = 0;
+    return this;
+  },
+
+  first: function() {
+    return this[0];
+  },
+
+  last: function() {
+    return this[this.length - 1];
+  },
+
+  compact: function() {
+    return this.select(function(value) {
+      return value != null;
+    });
+  },
+
+  flatten: function() {
+    return this.inject([], function(array, value) {
+      return array.concat(Object.isArray(value) ?
+        value.flatten() : [value]);
+    });
+  },
+
+  without: function() {
+    var values = $A(arguments);
+    return this.select(function(value) {
+      return !values.include(value);
+    });
+  },
+
+  reverse: function(inline) {
+    return (inline !== false ? this : this.toArray())._reverse();
+  },
+
+  reduce: function() {
+    return this.length > 1 ? this : this[0];
+  },
+
+  uniq: function(sorted) {
+    return this.inject([], function(array, value, index) {
+      if (0 == index || (sorted ? array.last() != value : !array.include(value)))
+        array.push(value);
+      return array;
+    });
+  },
+
+  intersect: function(array) {
+    return this.uniq().findAll(function(item) {
+      return array.detect(function(value) { return item === value });
+    });
+  },
+
+  clone: function() {
+    return [].concat(this);
+  },
+
+  size: function() {
+    return this.length;
+  },
+
+  inspect: function() {
+    return '[' + this.map(Object.inspect).join(', ') + ']';
+  },
+
+  toJSON: function() {
+    var results = [];
+    this.each(function(object) {
+      var value = Object.toJSON(object);
+      if (!Object.isUndefined(value)) results.push(value);
+    });
+    return '[' + results.join(', ') + ']';
+  }
+});
+
+// use native browser JS 1.6 implementation if available
+if (Object.isFunction(Array.prototype.forEach))
+  Array.prototype._each = Array.prototype.forEach;
+
+if (!Array.prototype.indexOf) Array.prototype.indexOf = function(item, i) {
+  i || (i = 0);
+  var length = this.length;
+  if (i < 0) i = length + i;
+  for (; i < length; i++)
+    if (this[i] === item) return i;
+  return -1;
+};
+
+if (!Array.prototype.lastIndexOf) Array.prototype.lastIndexOf = function(item, i) {
+  i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1;
+  var n = this.slice(0, i).reverse().indexOf(item);
+  return (n < 0) ? n : i - n - 1;
+};
+
+Array.prototype.toArray = Array.prototype.clone;
+
+function $w(string) {
+  if (!Object.isString(string)) return [];
+  string = string.strip();
+  return string ? string.split(/\s+/) : [];
+}
+
+if (Prototype.Browser.Opera){
+  Array.prototype.concat = function() {
+    var array = [];
+    for (var i = 0, length = this.length; i < length; i++) array.push(this[i]);
+    for (var i = 0, length = arguments.length; i < length; i++) {
+      if (Object.isArray(arguments[i])) {
+        for (var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
+          array.push(arguments[i][j]);
+      } else {
+        array.push(arguments[i]);
+      }
+    }
+    return array;
+  };
+}
+Object.extend(Number.prototype, {
+  toColorPart: function() {
+    return this.toPaddedString(2, 16);
+  },
+
+  succ: function() {
+    return this + 1;
+  },
+
+  times: function(iterator) {
+    $R(0, this, true).each(iterator);
+    return this;
+  },
+
+  toPaddedString: function(length, radix) {
+    var string = this.toString(radix || 10);
+    return '0'.times(length - string.length) + string;
+  },
+
+  toJSON: function() {
+    return isFinite(this) ? this.toString() : 'null';
+  }
+});
+
+$w('abs round ceil floor').each(function(method){
+  Number.prototype[method] = Math[method].methodize();
+});
+function $H(object) {
+  return new Hash(object);
+};
+
+var Hash = Class.create(Enumerable, (function() {
+
+  function toQueryPair(key, value) {
+    if (Object.isUndefined(value)) return key;
+    return key + '=' + encodeURIComponent(String.interpret(value));
+  }
+
+  return {
+    initialize: function(object) {
+      this._object = Object.isHash(object) ? object.toObject() : Object.clone(object);
+    },
+
+    _each: function(iterator) {
+      for (var key in this._object) {
+        var value = this._object[key], pair = [key, value];
+        pair.key = key;
+        pair.value = value;
+        iterator(pair);
+      }
+    },
+
+    set: function(key, value) {
+      return this._object[key] = value;
+    },
+
+    get: function(key) {
+      return this._object[key];
+    },
+
+    unset: function(key) {
+      var value = this._object[key];
+      delete this._object[key];
+      return value;
+    },
+
+    toObject: function() {
+      return Object.clone(this._object);
+    },
+
+    keys: function() {
+      return this.pluck('key');
+    },
+
+    values: function() {
+      return this.pluck('value');
+    },
+
+    index: function(value) {
+      var match = this.detect(function(pair) {
+        return pair.value === value;
+      });
+      return match && match.key;
+    },
+
+    merge: function(object) {
+      return this.clone().update(object);
+    },
+
+    update: function(object) {
+      return new Hash(object).inject(this, function(result, pair) {
+        result.set(pair.key, pair.value);
+        return result;
+      });
+    },
+
+    toQueryString: function() {
+      return this.map(function(pair) {
+        var key = encodeURIComponent(pair.key), values = pair.value;
+
+        if (values && typeof values == 'object') {
+          if (Object.isArray(values))
+            return values.map(toQueryPair.curry(key)).join('&');
+        }
+        return toQueryPair(key, values);
+      }).join('&');
+    },
+
+    inspect: function() {
+      return '#<Hash:{' + this.map(function(pair) {
+        return pair.map(Object.inspect).join(': ');
+      }).join(', ') + '}>';
+    },
+
+    toJSON: function() {
+      return Object.toJSON(this.toObject());
+    },
+
+    clone: function() {
+      return new Hash(this);
+    }
+  }
+})());
+
+Hash.prototype.toTemplateReplacements = Hash.prototype.toObject;
+Hash.from = $H;
+var ObjectRange = Class.create(Enumerable, {
+  initialize: function(start, end, exclusive) {
+    this.start = start;
+    this.end = end;
+    this.exclusive = exclusive;
+  },
+
+  _each: function(iterator) {
+    var value = this.start;
+    while (this.include(value)) {
+      iterator(value);
+      value = value.succ();
+    }
+  },
+
+  include: function(value) {
+    if (value < this.start)
+      return false;
+    if (this.exclusive)
+      return value < this.end;
+    return value <= this.end;
+  }
+});
+
+var $R = function(start, end, exclusive) {
+  return new ObjectRange(start, end, exclusive);
+};
+
+var Ajax = {
+  getTransport: function() {
+    return Try.these(
+      function() {return new XMLHttpRequest()},
+      function() {return new ActiveXObject('Msxml2.XMLHTTP')},
+      function() {return new ActiveXObject('Microsoft.XMLHTTP')}
+    ) || false;
+  },
+
+  activeRequestCount: 0
+};
+
+Ajax.Responders = {
+  responders: [],
+
+  _each: function(iterator) {
+    this.responders._each(iterator);
+  },
+
+  register: function(responder) {
+    if (!this.include(responder))
+      this.responders.push(responder);
+  },
+
+  unregister: function(responder) {
+    this.responders = this.responders.without(responder);
+  },
+
+  dispatch: function(callback, request, transport, json) {
+    this.each(function(responder) {
+      if (Object.isFunction(responder[callback])) {
+        try {
+          responder[callback].apply(responder, [request, transport, json]);
+        } catch (e) { }
+      }
+    });
+  }
+};
+
+Object.extend(Ajax.Responders, Enumerable);
+
+Ajax.Responders.register({
+  onCreate:   function() { Ajax.activeRequestCount++ },
+  onComplete: function() { Ajax.activeRequestCount-- }
+});
+
+Ajax.Base = Class.create({
+  initialize: function(options) {
+    this.options = {
+      method:       'post',
+      asynchronous: true,
+      contentType:  'application/x-www-form-urlencoded',
+      encoding:     'UTF-8',
+      parameters:   '',
+      evalJSON:     true,
+      evalJS:       true
+    };
+    Object.extend(this.options, options || { });
+
+    this.options.method = this.options.method.toLowerCase();
+
+    if (Object.isString(this.options.parameters))
+      this.options.parameters = this.options.parameters.toQueryParams();
+    else if (Object.isHash(this.options.parameters))
+      this.options.parameters = this.options.parameters.toObject();
+  }
+});
+
+Ajax.Request = Class.create(Ajax.Base, {
+  _complete: false,
+
+  initialize: function($super, url, options) {
+    $super(options);
+    this.transport = Ajax.getTransport();
+    this.request(url);
+  },
+
+  request: function(url) {
+    this.url = url;
+    this.method = this.options.method;
+    var params = Object.clone(this.options.parameters);
+
+    if (!['get', 'post'].include(this.method)) {
+      // simulate other verbs over post
+      params['_method'] = this.method;
+      this.method = 'post';
+    }
+
+    this.parameters = params;
+
+    if (params = Object.toQueryString(params)) {
+      // when GET, append parameters to URL
+      if (this.method == 'get')
+        this.url += (this.url.include('?') ? '&' : '?') + params;
+      else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent))
+        params += '&_=';
+    }
+
+    try {
+      var response = new Ajax.Response(this);
+      if (this.options.onCreate) this.options.onCreate(response);
+      Ajax.Responders.dispatch('onCreate', this, response);
+
+      this.transport.open(this.method.toUpperCase(), this.url,
+        this.options.asynchronous);
+
+      if (this.options.asynchronous) this.respondToReadyState.bind(this).defer(1);
+
+      this.transport.onreadystatechange = this.onStateChange.bind(this);
+      this.setRequestHeaders();
+
+      this.body = this.method == 'post' ? (this.options.postBody || params) : null;
+      this.transport.send(this.body);
+
+      /* Force Firefox to handle ready state 4 for synchronous requests */
+      if (!this.options.asynchronous && this.transport.overrideMimeType)
+        this.onStateChange();
+
+    }
+    catch (e) {
+      this.dispatchException(e);
+    }
+  },
+
+  onStateChange: function() {
+    var readyState = this.transport.readyState;
+    if (readyState > 1 && !((readyState == 4) && this._complete))
+      this.respondToReadyState(this.transport.readyState);
+  },
+
+  setRequestHeaders: function() {
+    var headers = {
+      'X-Requested-With': 'XMLHttpRequest',
+      'X-Prototype-Version': Prototype.Version,
+      'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
+    };
+
+    if (this.method == 'post') {
+      headers['Content-type'] = this.options.contentType +
+        (this.options.encoding ? '; charset=' + this.options.encoding : '');
+
+      /* Force "Connection: close" for older Mozilla browsers to work
+       * around a bug where XMLHttpRequest sends an incorrect
+       * Content-length header. See Mozilla Bugzilla #246651.
+       */
+      if (this.transport.overrideMimeType &&
+          (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
+            headers['Connection'] = 'close';
+    }
+
+    // user-defined headers
+    if (typeof this.options.requestHeaders == 'object') {
+      var extras = this.options.requestHeaders;
+
+      if (Object.isFunction(extras.push))
+        for (var i = 0, length = extras.length; i < length; i += 2)
+          headers[extras[i]] = extras[i+1];
+      else
+        $H(extras).each(function(pair) { headers[pair.key] = pair.value });
+    }
+
+    for (var name in headers)
+      this.transport.setRequestHeader(name, headers[name]);
+  },
+
+  success: function() {
+    var status = this.getStatus();
+    return !status || (status >= 200 && status < 300);
+  },
+
+  getStatus: function() {
+    try {
+      return this.transport.status || 0;
+    } catch (e) { return 0 }
+  },
+
+  respondToReadyState: function(readyState) {
+    var state = Ajax.Request.Events[readyState], response = new Ajax.Response(this);
+
+    if (state == 'Complete') {
+      try {
+        this._complete = true;
+        (this.options['on' + response.status]
+         || this.options['on' + (this.success() ? 'Success' : 'Failure')]
+         || Prototype.emptyFunction)(response, response.headerJSON);
+      } catch (e) {
+        this.dispatchException(e);
+      }
+
+      var contentType = response.getHeader('Content-type');
+      if (this.options.evalJS == 'force'
+          || (this.options.evalJS && this.isSameOrigin() && contentType
+          && contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i)))
+        this.evalResponse();
+    }
+
+    try {
+      (this.options['on' + state] || Prototype.emptyFunction)(response, response.headerJSON);
+      Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON);
+    } catch (e) {
+      this.dispatchException(e);
+    }
+
+    if (state == 'Complete') {
+      // avoid memory leak in MSIE: clean up
+      this.transport.onreadystatechange = Prototype.emptyFunction;
+    }
+  },
+
+  isSameOrigin: function() {
+    var m = this.url.match(/^\s*https?:\/\/[^\/]*/);
+    return !m || (m[0] == '#{protocol}//#{domain}#{port}'.interpolate({
+      protocol: location.protocol,
+      domain: document.domain,
+      port: location.port ? ':' + location.port : ''
+    }));
+  },
+
+  getHeader: function(name) {
+    try {
+      return this.transport.getResponseHeader(name) || null;
+    } catch (e) { return null }
+  },
+
+  evalResponse: function() {
+    try {
+      return eval((this.transport.responseText || '').unfilterJSON());
+    } catch (e) {
+      this.dispatchException(e);
+    }
+  },
+
+  dispatchException: function(exception) {
+    (this.options.onException || Prototype.emptyFunction)(this, exception);
+    Ajax.Responders.dispatch('onException', this, exception);
+  }
+});
+
+Ajax.Request.Events =
+  ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];
+
+Ajax.Response = Class.create({
+  initialize: function(request){
+    this.request = request;
+    var transport  = this.transport  = request.transport,
+        readyState = this.readyState = transport.readyState;
+
+    if((readyState > 2 && !Prototype.Browser.IE) || readyState == 4) {
+      this.status       = this.getStatus();
+      this.statusText   = this.getStatusText();
+      this.responseText = String.interpret(transport.responseText);
+      this.headerJSON   = this._getHeaderJSON();
+    }
+
+    if(readyState == 4) {
+      var xml = transport.responseXML;
+      this.responseXML  = Object.isUndefined(xml) ? null : xml;
+      this.responseJSON = this._getResponseJSON();
+    }
+  },
+
+  status:      0,
+  statusText: '',
+
+  getStatus: Ajax.Request.prototype.getStatus,
+
+  getStatusText: function() {
+    try {
+      return this.transport.statusText || '';
+    } catch (e) { return '' }
+  },
+
+  getHeader: Ajax.Request.prototype.getHeader,
+
+  getAllHeaders: function() {
+    try {
+      return this.getAllResponseHeaders();
+    } catch (e) { return null }
+  },
+
+  getResponseHeader: function(name) {
+    return this.transport.getResponseHeader(name);
+  },
+
+  getAllResponseHeaders: function() {
+    return this.transport.getAllResponseHeaders();
+  },
+
+  _getHeaderJSON: function() {
+    var json = this.getHeader('X-JSON');
+    if (!json) return null;
+    json = decodeURIComponent(escape(json));
+    try {
+      return json.evalJSON(this.request.options.sanitizeJSON ||
+        !this.request.isSameOrigin());
+    } catch (e) {
+      this.request.dispatchException(e);
+    }
+  },
+
+  _getResponseJSON: function() {
+    var options = this.request.options;
+    if (!options.evalJSON || (options.evalJSON != 'force' &&
+      !(this.getHeader('Content-type') || '').include('application/json')) ||
+        this.responseText.blank())
+          return null;
+    try {
+      return this.responseText.evalJSON(options.sanitizeJSON ||
+        !this.request.isSameOrigin());
+    } catch (e) {
+      this.request.dispatchException(e);
+    }
+  }
+});
+
+Ajax.Updater = Class.create(Ajax.Request, {
+  initialize: function($super, container, url, options) {
+    this.container = {
+      success: (container.success || container),
+      failure: (container.failure || (container.success ? null : container))
+    };
+
+    options = Object.clone(options);
+    var onComplete = options.onComplete;
+    options.onComplete = (function(response, json) {
+      this.updateContent(response.responseText);
+      if (Object.isFunction(onComplete)) onComplete(response, json);
+    }).bind(this);
+
+    $super(url, options);
+  },
+
+  updateContent: function(responseText) {
+    var receiver = this.container[this.success() ? 'success' : 'failure'],
+        options = this.options;
+
+    if (!options.evalScripts) responseText = responseText.stripScripts();
+
+    if (receiver = $(receiver)) {
+      if (options.insertion) {
+        if (Object.isString(options.insertion)) {
+          var insertion = { }; insertion[options.insertion] = responseText;
+          receiver.insert(insertion);
+        }
+        else options.insertion(receiver, responseText);
+      }
+      else receiver.update(responseText);
+    }
+  }
+});
+
+Ajax.PeriodicalUpdater = Class.create(Ajax.Base, {
+  initialize: function($super, container, url, options) {
+    $super(options);
+    this.onComplete = this.options.onComplete;
+
+    this.frequency = (this.options.frequency || 2);
+    this.decay = (this.options.decay || 1);
+
+    this.updater = { };
+    this.container = container;
+    this.url = url;
+
+    this.start();
+  },
+
+  start: function() {
+    this.options.onComplete = this.updateComplete.bind(this);
+    this.onTimerEvent();
+  },
+
+  stop: function() {
+    this.updater.options.onComplete = undefined;
+    clearTimeout(this.timer);
+    (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
+  },
+
+  updateComplete: function(response) {
+    if (this.options.decay) {
+      this.decay = (response.responseText == this.lastText ?
+        this.decay * this.options.decay : 1);
+
+      this.lastText = response.responseText;
+    }
+    this.timer = this.onTimerEvent.bind(this).delay(this.decay * this.frequency);
+  },
+
+  onTimerEvent: function() {
+    this.updater = new Ajax.Updater(this.container, this.url, this.options);
+  }
+});
+function $(element) {
+  if (arguments.length > 1) {
+    for (var i = 0, elements = [], length = arguments.length; i < length; i++)
+      elements.push($(arguments[i]));
+    return elements;
+  }
+  if (Object.isString(element))
+    element = document.getElementById(element);
+  return Element.extend(element);
+}
+
+if (Prototype.BrowserFeatures.XPath) {
+  document._getElementsByXPath = function(expression, parentElement) {
+    var results = [];
+    var query = document.evaluate(expression, $(parentElement) || document,
+      null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
+    for (var i = 0, length = query.snapshotLength; i < length; i++)
+      results.push(Element.extend(query.snapshotItem(i)));
+    return results;
+  };
+}
+
+/*--------------------------------------------------------------------------*/
+
+if (!window.Node) var Node = { };
+
+if (!Node.ELEMENT_NODE) {
+  // DOM level 2 ECMAScript Language Binding
+  Object.extend(Node, {
+    ELEMENT_NODE: 1,
+    ATTRIBUTE_NODE: 2,
+    TEXT_NODE: 3,
+    CDATA_SECTION_NODE: 4,
+    ENTITY_REFERENCE_NODE: 5,
+    ENTITY_NODE: 6,
+    PROCESSING_INSTRUCTION_NODE: 7,
+    COMMENT_NODE: 8,
+    DOCUMENT_NODE: 9,
+    DOCUMENT_TYPE_NODE: 10,
+    DOCUMENT_FRAGMENT_NODE: 11,
+    NOTATION_NODE: 12
+  });
+}
+
+(function() {
+  var element = this.Element;
+  this.Element = function(tagName, attributes) {
+    attributes = attributes || { };
+    tagName = tagName.toLowerCase();
+    var cache = Element.cache;
+    if (Prototype.Browser.IE && attributes.name) {
+      tagName = '<' + tagName + ' name="' + attributes.name + '">';
+      delete attributes.name;
+      return Element.writeAttribute(document.createElement(tagName), attributes);
+    }
+    if (!cache[tagName]) cache[tagName] = Element.extend(document.createElement(tagName));
+    return Element.writeAttribute(cache[tagName].cloneNode(false), attributes);
+  };
+  Object.extend(this.Element, element || { });
+}).call(window);
+
+Element.cache = { };
+
+Element.Methods = {
+  visible: function(element) {
+    return $(element).style.display != 'none';
+  },
+
+  toggle: function(element) {
+    element = $(element);
+    Element[Element.visible(element) ? 'hide' : 'show'](element);
+    return element;
+  },
+
+  hide: function(element) {
+    $(element).style.display = 'none';
+    return element;
+  },
+
+  show: function(element) {
+    $(element).style.display = '';
+    return element;
+  },
+
+  remove: function(element) {
+    element = $(element);
+    element.parentNode.removeChild(element);
+    return element;
+  },
+
+  update: function(element, content) {
+    element = $(element);
+    if (content && content.toElement) content = content.toElement();
+    if (Object.isElement(content)) return element.update().insert(content);
+    content = Object.toHTML(content);
+    element.innerHTML = content.stripScripts();
+    content.evalScripts.bind(content).defer();
+    return element;
+  },
+
+  replace: function(element, content) {
+    element = $(element);
+    if (content && content.toElement) content = content.toElement();
+    else if (!Object.isElement(content)) {
+      content = Object.toHTML(content);
+      var range = element.ownerDocument.createRange();
+      range.selectNode(element);
+      content.evalScripts.bind(content).defer();
+      content = range.createContextualFragment(content.stripScripts());
+    }
+    element.parentNode.replaceChild(content, element);
+    return element;
+  },
+
+  insert: function(element, insertions) {
+    element = $(element);
+
+    if (Object.isString(insertions) || Object.isNumber(insertions) ||
+        Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML)))
+          insertions = {bottom:insertions};
+
+    var content, insert, tagName, childNodes;
+
+    for (var position in insertions) {
+      content  = insertions[position];
+      position = position.toLowerCase();
+      insert = Element._insertionTranslations[position];
+
+      if (content && content.toElement) content = content.toElement();
+      if (Object.isElement(content)) {
+        insert(element, content);
+        continue;
+      }
+
+      content = Object.toHTML(content);
+
+      tagName = ((position == 'before' || position == 'after')
+        ? element.parentNode : element).tagName.toUpperCase();
+
+      childNodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
+
+      if (position == 'top' || position == 'after') childNodes.reverse();
+      childNodes.each(insert.curry(element));
+
+      content.evalScripts.bind(content).defer();
+    }
+
+    return element;
+  },
+
+  wrap: function(element, wrapper, attributes) {
+    element = $(element);
+    if (Object.isElement(wrapper))
+      $(wrapper).writeAttribute(attributes || { });
+    else if (Object.isString(wrapper)) wrapper = new Element(wrapper, attributes);
+    else wrapper = new Element('div', wrapper);
+    if (element.parentNode)
+      element.parentNode.replaceChild(wrapper, element);
+    wrapper.appendChild(element);
+    return wrapper;
+  },
+
+  inspect: function(element) {
+    element = $(element);
+    var result = '<' + element.tagName.toLowerCase();
+    $H({'id': 'id', 'className': 'class'}).each(function(pair) {
+      var property = pair.first(), attribute = pair.last();
+      var value = (element[property] || '').toString();
+      if (value) result += ' ' + attribute + '=' + value.inspect(true);
+    });
+    return result + '>';
+  },
+
+  recursivelyCollect: function(element, property) {
+    element = $(element);
+    var elements = [];
+    while (element = element[property])
+      if (element.nodeType == 1)
+        elements.push(Element.extend(element));
+    return elements;
+  },
+
+  ancestors: function(element) {
+    return $(element).recursivelyCollect('parentNode');
+  },
+
+  descendants: function(element) {
+    return $(element).select("*");
+  },
+
+  firstDescendant: function(element) {
+    element = $(element).firstChild;
+    while (element && element.nodeType != 1) element = element.nextSibling;
+    return $(element);
+  },
+
+  immediateDescendants: function(element) {
+    if (!(element = $(element).firstChild)) return [];
+    while (element && element.nodeType != 1) element = element.nextSibling;
+    if (element) return [element].concat($(element).nextSiblings());
+    return [];
+  },
+
+  previousSiblings: function(element) {
+    return $(element).recursivelyCollect('previousSibling');
+  },
+
+  nextSiblings: function(element) {
+    return $(element).recursivelyCollect('nextSibling');
+  },
+
+  siblings: function(element) {
+    element = $(element);
+    return element.previousSiblings().reverse().concat(element.nextSiblings());
+  },
+
+  match: function(element, selector) {
+    if (Object.isString(selector))
+      selector = new Selector(selector);
+    return selector.match($(element));
+  },
+
+  up: function(element, expression, index) {
+    element = $(element);
+    if (arguments.length == 1) return $(element.parentNode);
+    var ancestors = element.ancestors();
+    return Object.isNumber(expression) ? ancestors[expression] :
+      Selector.findElement(ancestors, expression, index);
+  },
+
+  down: function(element, expression, index) {
+    element = $(element);
+    if (arguments.length == 1) return element.firstDescendant();
+    return Object.isNumber(expression) ? element.descendants()[expression] :
+      element.select(expression)[index || 0];
+  },
+
+  previous: function(element, expression, index) {
+    element = $(element);
+    if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element));
+    var previousSiblings = element.previousSiblings();
+    return Object.isNumber(expression) ? previousSiblings[expression] :
+      Selector.findElement(previousSiblings, expression, index);
+  },
+
+  next: function(element, expression, index) {
+    element = $(element);
+    if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element));
+    var nextSiblings = element.nextSiblings();
+    return Object.isNumber(expression) ? nextSiblings[expression] :
+      Selector.findElement(nextSiblings, expression, index);
+  },
+
+  select: function() {
+    var args = $A(arguments), element = $(args.shift());
+    return Selector.findChildElements(element, args);
+  },
+
+  adjacent: function() {
+    var args = $A(arguments), element = $(args.shift());
+    return Selector.findChildElements(element.parentNode, args).without(element);
+  },
+
+  identify: function(element) {
+    element = $(element);
+    var id = element.readAttribute('id'), self = arguments.callee;
+    if (id) return id;
+    do { id = 'anonymous_element_' + self.counter++ } while ($(id));
+    element.writeAttribute('id', id);
+    return id;
+  },
+
+  readAttribute: function(element, name) {
+    element = $(element);
+    if (Prototype.Browser.IE) {
+      var t = Element._attributeTranslations.read;
+      if (t.values[name]) return t.values[name](element, name);
+      if (t.names[name]) name = t.names[name];
+      if (name.include(':')) {
+        return (!element.attributes || !element.attributes[name]) ? null :
+         element.attributes[name].value;
+      }
+    }
+    return element.getAttribute(name);
+  },
+
+  writeAttribute: function(element, name, value) {
+    element = $(element);
+    var attributes = { }, t = Element._attributeTranslations.write;
+
+    if (typeof name == 'object') attributes = name;
+    else attributes[name] = Object.isUndefined(value) ? true : value;
+
+    for (var attr in attributes) {
+      name = t.names[attr] || attr;
+      value = attributes[attr];
+      if (t.values[attr]) name = t.values[attr](element, value);
+      if (value === false || value === null)
+        element.removeAttribute(name);
+      else if (value === true)
+        element.setAttribute(name, name);
+      else element.setAttribute(name, value);
+    }
+    return element;
+  },
+
+  getHeight: function(element) {
+    return $(element).getDimensions().height;
+  },
+
+  getWidth: function(element) {
+    return $(element).getDimensions().width;
+  },
+
+  classNames: function(element) {
+    return new Element.ClassNames(element);
+  },
+
+  hasClassName: function(element, className) {
+    if (!(element = $(element))) return;
+    var elementClassName = element.className;
+    return (elementClassName.length > 0 && (elementClassName == className ||
+      new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
+  },
+
+  addClassName: function(element, className) {
+    if (!(element = $(element))) return;
+    if (!element.hasClassName(className))
+      element.className += (element.className ? ' ' : '') + className;
+    return element;
+  },
+
+  removeClassName: function(element, className) {
+    if (!(element = $(element))) return;
+    element.className = element.className.replace(
+      new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ').strip();
+    return element;
+  },
+
+  toggleClassName: function(element, className) {
+    if (!(element = $(element))) return;
+    return element[element.hasClassName(className) ?
+      'removeClassName' : 'addClassName'](className);
+  },
+
+  // removes whitespace-only text node children
+  cleanWhitespace: function(element) {
+    element = $(element);
+    var node = element.firstChild;
+    while (node) {
+      var nextNode = node.nextSibling;
+      if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
+        element.removeChild(node);
+      node = nextNode;
+    }
+    return element;
+  },
+
+  empty: function(element) {
+    return $(element).innerHTML.blank();
+  },
+
+  descendantOf: function(element, ancestor) {
+    element = $(element), ancestor = $(ancestor);
+    var originalAncestor = ancestor;
+
+    if (element.compareDocumentPosition)
+      return (element.compareDocumentPosition(ancestor) & 8) === 8;
+
+    if (element.sourceIndex && !Prototype.Browser.Opera) {
+      var e = element.sourceIndex, a = ancestor.sourceIndex,
+       nextAncestor = ancestor.nextSibling;
+      if (!nextAncestor) {
+        do { ancestor = ancestor.parentNode; }
+        while (!(nextAncestor = ancestor.nextSibling) && ancestor.parentNode);
+      }
+      if (nextAncestor && nextAncestor.sourceIndex)
+       return (e > a && e < nextAncestor.sourceIndex);
+    }
+
+    while (element = element.parentNode)
+      if (element == originalAncestor) return true;
+    return false;
+  },
+
+  scrollTo: function(element) {
+    element = $(element);
+    var pos = element.cumulativeOffset();
+    window.scrollTo(pos[0], pos[1]);
+    return element;
+  },
+
+  getStyle: function(element, style) {
+    element = $(element);
+    style = style == 'float' ? 'cssFloat' : style.camelize();
+    var value = element.style[style];
+    if (!value) {
+      var css = document.defaultView.getComputedStyle(element, null);
+      value = css ? css[style] : null;
+    }
+    if (style == 'opacity') return value ? parseFloat(value) : 1.0;
+    return value == 'auto' ? null : value;
+  },
+
+  getOpacity: function(element) {
+    return $(element).getStyle('opacity');
+  },
+
+  setStyle: function(element, styles) {
+    element = $(element);
+    var elementStyle = element.style, match;
+    if (Object.isString(styles)) {
+      element.style.cssText += ';' + styles;
+      return styles.include('opacity') ?
+        element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element;
+    }
+    for (var property in styles)
+      if (property == 'opacity') element.setOpacity(styles[property]);
+      else
+        elementStyle[(property == 'float' || property == 'cssFloat') ?
+          (Object.isUndefined(elementStyle.styleFloat) ? 'cssFloat' : 'styleFloat') :
+            property] = styles[property];
+
+    return element;
+  },
+
+  setOpacity: function(element, value) {
+    element = $(element);
+    element.style.opacity = (value == 1 || value === '') ? '' :
+      (value < 0.00001) ? 0 : value;
+    return element;
+  },
+
+  getDimensions: function(element) {
+    element = $(element);
+    var display = $(element).getStyle('display');
+    if (display != 'none' && display != null) // Safari bug
+      return {width: element.offsetWidth, height: element.offsetHeight};
+
+    // All *Width and *Height properties give 0 on elements with display none,
+    // so enable the element temporarily
+    var els = element.style;
+    var originalVisibility = els.visibility;
+    var originalPosition = els.position;
+    var originalDisplay = els.display;
+    els.visibility = 'hidden';
+    els.position = 'absolute';
+    els.display = 'block';
+    var originalWidth = element.clientWidth;
+    var originalHeight = element.clientHeight;
+    els.display = originalDisplay;
+    els.position = originalPosition;
+    els.visibility = originalVisibility;
+    return {width: originalWidth, height: originalHeight};
+  },
+
+  makePositioned: function(element) {
+    element = $(element);
+    var pos = Element.getStyle(element, 'position');
+    if (pos == 'static' || !pos) {
+      element._madePositioned = true;
+      element.style.position = 'relative';
+      // Opera returns the offset relative to the positioning context, when an
+      // element is position relative but top and left have not been defined
+      if (window.opera) {
+        element.style.top = 0;
+        element.style.left = 0;
+      }
+    }
+    return element;
+  },
+
+  undoPositioned: function(element) {
+    element = $(element);
+    if (element._madePositioned) {
+      element._madePositioned = undefined;
+      element.style.position =
+        element.style.top =
+        element.style.left =
+        element.style.bottom =
+        element.style.right = '';
+    }
+    return element;
+  },
+
+  makeClipping: function(element) {
+    element = $(element);
+    if (element._overflow) return element;
+    element._overflow = Element.getStyle(element, 'overflow') || 'auto';
+    if (element._overflow !== 'hidden')
+      element.style.overflow = 'hidden';
+    return element;
+  },
+
+  undoClipping: function(element) {
+    element = $(element);
+    if (!element._overflow) return element;
+    element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
+    element._overflow = null;
+    return element;
+  },
+
+  cumulativeOffset: function(element) {
+    var valueT = 0, valueL = 0;
+    do {
+      valueT += element.offsetTop  || 0;
+      valueL += element.offsetLeft || 0;
+      element = element.offsetParent;
+    } while (element);
+    return Element._returnOffset(valueL, valueT);
+  },
+
+  positionedOffset: function(element) {
+    var valueT = 0, valueL = 0;
+    do {
+      valueT += element.offsetTop  || 0;
+      valueL += element.offsetLeft || 0;
+      element = element.offsetParent;
+      if (element) {
+        if (element.tagName == 'BODY') break;
+        var p = Element.getStyle(element, 'position');
+        if (p !== 'static') break;
+      }
+    } while (element);
+    return Element._returnOffset(valueL, valueT);
+  },
+
+  absolutize: function(element) {
+    element = $(element);
+    if (element.getStyle('position') == 'absolute') return;
+    // Position.prepare(); // To be done manually by Scripty when it needs it.
+
+    var offsets = element.positionedOffset();
+    var top     = offsets[1];
+    var left    = offsets[0];
+    var width   = element.clientWidth;
+    var height  = element.clientHeight;
+
+    element._originalLeft   = left - parseFloat(element.style.left  || 0);
+    element._originalTop    = top  - parseFloat(element.style.top || 0);
+    element._originalWidth  = element.style.width;
+    element._originalHeight = element.style.height;
+
+    element.style.position = 'absolute';
+    element.style.top    = top + 'px';
+    element.style.left   = left + 'px';
+    element.style.width  = width + 'px';
+    element.style.height = height + 'px';
+    return element;
+  },
+
+  relativize: function(element) {
+    element = $(element);
+    if (element.getStyle('position') == 'relative') return;
+    // Position.prepare(); // To be done manually by Scripty when it needs it.
+
+    element.style.position = 'relative';
+    var top  = parseFloat(element.style.top  || 0) - (element._originalTop || 0);
+    var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);
+
+    element.style.top    = top + 'px';
+    element.style.left   = left + 'px';
+    element.style.height = element._originalHeight;
+    element.style.width  = element._originalWidth;
+    return element;
+  },
+
+  cumulativeScrollOffset: function(element) {
+    var valueT = 0, valueL = 0;
+    do {
+      valueT += element.scrollTop  || 0;
+      valueL += element.scrollLeft || 0;
+      element = element.parentNode;
+    } while (element);
+    return Element._returnOffset(valueL, valueT);
+  },
+
+  getOffsetParent: function(element) {
+    if (element.offsetParent) return $(element.offsetParent);
+    if (element == document.body) return $(element);
+
+    while ((element = element.parentNode) && element != document.body)
+      if (Element.getStyle(element, 'position') != 'static')
+        return $(element);
+
+    return $(document.body);
+  },
+
+  viewportOffset: function(forElement) {
+    var valueT = 0, valueL = 0;
+
+    var element = forElement;
+    do {
+      valueT += element.offsetTop  || 0;
+      valueL += element.offsetLeft || 0;
+
+      // Safari fix
+      if (element.offsetParent == document.body &&
+        Element.getStyle(element, 'position') == 'absolute') break;
+
+    } while (element = element.offsetParent);
+
+    element = forElement;
+    do {
+      if (!Prototype.Browser.Opera || element.tagName == 'BODY') {
+        valueT -= element.scrollTop  || 0;
+        valueL -= element.scrollLeft || 0;
+      }
+    } while (element = element.parentNode);
+
+    return Element._returnOffset(valueL, valueT);
+  },
+
+  clonePosition: function(element, source) {
+    var options = Object.extend({
+      setLeft:    true,
+      setTop:     true,
+      setWidth:   true,
+      setHeight:  true,
+      offsetTop:  0,
+      offsetLeft: 0
+    }, arguments[2] || { });
+
+    // find page position of source
+    source = $(source);
+    var p = source.viewportOffset();
+
+    // find coordinate system to use
+    element = $(element);
+    var delta = [0, 0];
+    var parent = null;
+    // delta [0,0] will do fine with position: fixed elements,
+    // position:absolute needs offsetParent deltas
+    if (Element.getStyle(element, 'position') == 'absolute') {
+      parent = element.getOffsetParent();
+      delta = parent.viewportOffset();
+    }
+
+    // correct by body offsets (fixes Safari)
+    if (parent == document.body) {
+      delta[0] -= document.body.offsetLeft;
+      delta[1] -= document.body.offsetTop;
+    }
+
+    // set position
+    if (options.setLeft)   element.style.left  = (p[0] - delta[0] + options.offsetLeft) + 'px';
+    if (options.setTop)    element.style.top   = (p[1] - delta[1] + options.offsetTop) + 'px';
+    if (options.setWidth)  element.style.width = source.offsetWidth + 'px';
+    if (options.setHeight) element.style.height = source.offsetHeight + 'px';
+    return element;
+  }
+};
+
+Element.Methods.identify.counter = 1;
+
+Object.extend(Element.Methods, {
+  getElementsBySelector: Element.Methods.select,
+  childElements: Element.Methods.immediateDescendants
+});
+
+Element._attributeTranslations = {
+  write: {
+    names: {
+      className: 'class',
+      htmlFor:   'for'
+    },
+    values: { }
+  }
+};
+
+if (Prototype.Browser.Opera) {
+  Element.Methods.getStyle = Element.Methods.getStyle.wrap(
+    function(proceed, element, style) {
+      switch (style) {
+        case 'left': case 'top': case 'right': case 'bottom':
+          if (proceed(element, 'position') === 'static') return null;
+        case 'height': case 'width':
+          // returns '0px' for hidden elements; we want it to return null
+          if (!Element.visible(element)) return null;
+
+          // returns the border-box dimensions rather than the content-box
+          // dimensions, so we subtract padding and borders from the value
+          var dim = parseInt(proceed(element, style), 10);
+
+          if (dim !== element['offset' + style.capitalize()])
+            return dim + 'px';
+
+          var properties;
+          if (style === 'height') {
+            properties = ['border-top-width', 'padding-top',
+             'padding-bottom', 'border-bottom-width'];
+          }
+          else {
+            properties = ['border-left-width', 'padding-left',
+             'padding-right', 'border-right-width'];
+          }
+          return properties.inject(dim, function(memo, property) {
+            var val = proceed(element, property);
+            return val === null ? memo : memo - parseInt(val, 10);
+          }) + 'px';
+        default: return proceed(element, style);
+      }
+    }
+  );
+
+  Element.Methods.readAttribute = Element.Methods.readAttribute.wrap(
+    function(proceed, element, attribute) {
+      if (attribute === 'title') return element.title;
+      return proceed(element, attribute);
+    }
+  );
+}
+
+else if (Prototype.Browser.IE) {
+  // IE doesn't report offsets correctly for static elements, so we change them
+  // to "relative" to get the values, then change them back.
+  Element.Methods.getOffsetParent = Element.Methods.getOffsetParent.wrap(
+    function(proceed, element) {
+      element = $(element);
+      var position = element.getStyle('position');
+      if (position !== 'static') return proceed(element);
+      element.setStyle({ position: 'relative' });
+      var value = proceed(element);
+      element.setStyle({ position: position });
+      return value;
+    }
+  );
+
+  $w('positionedOffset viewportOffset').each(function(method) {
+    Element.Methods[method] = Element.Methods[method].wrap(
+      function(proceed, element) {
+        element = $(element);
+        var position = element.getStyle('position');
+        if (position !== 'static') return proceed(element);
+        // Trigger hasLayout on the offset parent so that IE6 reports
+        // accurate offsetTop and offsetLeft values for position: fixed.
+        var offsetParent = element.getOffsetParent();
+        if (offsetParent && offsetParent.getStyle('position') === 'fixed')
+          offsetParent.setStyle({ zoom: 1 });
+        element.setStyle({ position: 'relative' });
+        var value = proceed(element);
+        element.setStyle({ position: position });
+        return value;
+      }
+    );
+  });
+
+  Element.Methods.getStyle = function(element, style) {
+    element = $(element);
+    style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize();
+    var value = element.style[style];
+    if (!value && element.currentStyle) value = element.currentStyle[style];
+
+    if (style == 'opacity') {
+      if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
+        if (value[1]) return parseFloat(value[1]) / 100;
+      return 1.0;
+    }
+
+    if (value == 'auto') {
+      if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none'))
+        return element['offset' + style.capitalize()] + 'px';
+      return null;
+    }
+    return value;
+  };
+
+  Element.Methods.setOpacity = function(element, value) {
+    function stripAlpha(filter){
+      return filter.replace(/alpha\([^\)]*\)/gi,'');
+    }
+    element = $(element);
+    var currentStyle = element.currentStyle;
+    if ((currentStyle && !currentStyle.hasLayout) ||
+      (!currentStyle && element.style.zoom == 'normal'))
+        element.style.zoom = 1;
+
+    var filter = element.getStyle('filter'), style = element.style;
+    if (value == 1 || value === '') {
+      (filter = stripAlpha(filter)) ?
+        style.filter = filter : style.removeAttribute('filter');
+      return element;
+    } else if (value < 0.00001) value = 0;
+    style.filter = stripAlpha(filter) +
+      'alpha(opacity=' + (value * 100) + ')';
+    return element;
+  };
+
+  Element._attributeTranslations = {
+    read: {
+      names: {
+        'class': 'className',
+        'for':   'htmlFor'
+      },
+      values: {
+        _getAttr: function(element, attribute) {
+          return element.getAttribute(attribute, 2);
+        },
+        _getAttrNode: function(element, attribute) {
+          var node = element.getAttributeNode(attribute);
+          return node ? node.value : "";
+        },
+        _getEv: function(element, attribute) {
+          attribute = element.getAttribute(attribute);
+          return attribute ? attribute.toString().slice(23, -2) : null;
+        },
+        _flag: function(element, attribute) {
+          return $(element).hasAttribute(attribute) ? attribute : null;
+        },
+        style: function(element) {
+          return element.style.cssText.toLowerCase();
+        },
+        title: function(element) {
+          return element.title;
+        }
+      }
+    }
+  };
+
+  Element._attributeTranslations.write = {
+    names: Object.extend({
+      cellpadding: 'cellPadding',
+      cellspacing: 'cellSpacing'
+    }, Element._attributeTranslations.read.names),
+    values: {
+      checked: function(element, value) {
+        element.checked = !!value;
+      },
+
+      style: function(element, value) {
+        element.style.cssText = value ? value : '';
+      }
+    }
+  };
+
+  Element._attributeTranslations.has = {};
+
+  $w('colSpan rowSpan vAlign dateTime accessKey tabIndex ' +
+      'encType maxLength readOnly longDesc').each(function(attr) {
+    Element._attributeTranslations.write.names[attr.toLowerCase()] = attr;
+    Element._attributeTranslations.has[attr.toLowerCase()] = attr;
+  });
+
+  (function(v) {
+    Object.extend(v, {
+      href:        v._getAttr,
+      src:         v._getAttr,
+      type:        v._getAttr,
+      action:      v._getAttrNode,
+      disabled:    v._flag,
+      checked:     v._flag,
+      readonly:    v._flag,
+      multiple:    v._flag,
+      onload:      v._getEv,
+      onunload:    v._getEv,
+      onclick:     v._getEv,
+      ondblclick:  v._getEv,
+      onmousedown: v._getEv,
+      onmouseup:   v._getEv,
+      onmouseover: v._getEv,
+      onmousemove: v._getEv,
+      onmouseout:  v._getEv,
+      onfocus:     v._getEv,
+      onblur:      v._getEv,
+      onkeypress:  v._getEv,
+      onkeydown:   v._getEv,
+      onkeyup:     v._getEv,
+      onsubmit:    v._getEv,
+      onreset:     v._getEv,
+      onselect:    v._getEv,
+      onchange:    v._getEv
+    });
+  })(Element._attributeTranslations.read.values);
+}
+
+else if (Prototype.Browser.Gecko && /rv:1\.8\.0/.test(navigator.userAgent)) {
+  Element.Methods.setOpacity = function(element, value) {
+    element = $(element);
+    element.style.opacity = (value == 1) ? 0.999999 :
+      (value === '') ? '' : (value < 0.00001) ? 0 : value;
+    return element;
+  };
+}
+
+else if (Prototype.Browser.WebKit) {
+  Element.Methods.setOpacity = function(element, value) {
+    element = $(element);
+    element.style.opacity = (value == 1 || value === '') ? '' :
+      (value < 0.00001) ? 0 : value;
+
+    if (value == 1)
+      if(element.tagName == 'IMG' && element.width) {
+        element.width++; element.width--;
+      } else try {
+        var n = document.createTextNode(' ');
+        element.appendChild(n);
+        element.removeChild(n);
+      } catch (e) { }
+
+    return element;
+  };
+
+  // Safari returns margins on body which is incorrect if the child is absolutely
+  // positioned.  For performance reasons, redefine Element#cumulativeOffset for
+  // KHTML/WebKit only.
+  Element.Methods.cumulativeOffset = function(element) {
+    var valueT = 0, valueL = 0;
+    do {
+      valueT += element.offsetTop  || 0;
+      valueL += element.offsetLeft || 0;
+      if (element.offsetParent == document.body)
+        if (Element.getStyle(element, 'position') == 'absolute') break;
+
+      element = element.offsetParent;
+    } while (element);
+
+    return Element._returnOffset(valueL, valueT);
+  };
+}
+
+if (Prototype.Browser.IE || Prototype.Browser.Opera) {
+  // IE and Opera are missing .innerHTML support for TABLE-related and SELECT elements
+  Element.Methods.update = function(element, content) {
+    element = $(element);
+
+    if (content && content.toElement) content = content.toElement();
+    if (Object.isElement(content)) return element.update().insert(content);
+
+    content = Object.toHTML(content);
+    var tagName = element.tagName.toUpperCase();
+
+    if (tagName in Element._insertionTranslations.tags) {
+      $A(element.childNodes).each(function(node) { element.removeChild(node) });
+      Element._getContentFromAnonymousElement(tagName, content.stripScripts())
+        .each(function(node) { element.appendChild(node) });
+    }
+    else element.innerHTML = content.stripScripts();
+
+    content.evalScripts.bind(content).defer();
+    return element;
+  };
+}
+
+if ('outerHTML' in document.createElement('div')) {
+  Element.Methods.replace = function(element, content) {
+    element = $(element);
+
+    if (content && content.toElement) content = content.toElement();
+    if (Object.isElement(content)) {
+      element.parentNode.replaceChild(content, element);
+      return element;
+    }
+
+    content = Object.toHTML(content);
+    var parent = element.parentNode, tagName = parent.tagName.toUpperCase();
+
+    if (Element._insertionTranslations.tags[tagName]) {
+      var nextSibling = element.next();
+      var fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
+      parent.removeChild(element);
+      if (nextSibling)
+        fragments.each(function(node) { parent.insertBefore(node, nextSibling) });
+      else
+        fragments.each(function(node) { parent.appendChild(node) });
+    }
+    else element.outerHTML = content.stripScripts();
+
+    content.evalScripts.bind(content).defer();
+    return element;
+  };
+}
+
+Element._returnOffset = function(l, t) {
+  var result = [l, t];
+  result.left = l;
+  result.top = t;
+  return result;
+};
+
+Element._getContentFromAnonymousElement = function(tagName, html) {
+  var div = new Element('div'), t = Element._insertionTranslations.tags[tagName];
+  if (t) {
+    div.innerHTML = t[0] + html + t[1];
+    t[2].times(function() { div = div.firstChild });
+  } else div.innerHTML = html;
+  return $A(div.childNodes);
+};
+
+Element._insertionTranslations = {
+  before: function(element, node) {
+    element.parentNode.insertBefore(node, element);
+  },
+  top: function(element, node) {
+    element.insertBefore(node, element.firstChild);
+  },
+  bottom: function(element, node) {
+    element.appendChild(node);
+  },
+  after: function(element, node) {
+    element.parentNode.insertBefore(node, element.nextSibling);
+  },
+  tags: {
+    TABLE:  ['<table>',                '</table>',                   1],
+    TBODY:  ['<table><tbody>',         '</tbody></table>',           2],
+    TR:     ['<table><tbody><tr>',     '</tr></tbody></table>',      3],
+    TD:     ['<table><tbody><tr><td>', '</td></tr></tbody></table>', 4],
+    SELECT: ['<select>',               '</select>',                  1]
+  }
+};
+
+(function() {
+  Object.extend(this.tags, {
+    THEAD: this.tags.TBODY,
+    TFOOT: this.tags.TBODY,
+    TH:    this.tags.TD
+  });
+}).call(Element._insertionTranslations);
+
+Element.Methods.Simulated = {
+  hasAttribute: function(element, attribute) {
+    attribute = Element._attributeTranslations.has[attribute] || attribute;
+    var node = $(element).getAttributeNode(attribute);
+    return node && node.specified;
+  }
+};
+
+Element.Methods.ByTag = { };
+
+Object.extend(Element, Element.Methods);
+
+if (!Prototype.BrowserFeatures.ElementExtensions &&
+    document.createElement('div').__proto__) {
+  window.HTMLElement = { };
+  window.HTMLElement.prototype = document.createElement('div').__proto__;
+  Prototype.BrowserFeatures.ElementExtensions = true;
+}
+
+Element.extend = (function() {
+  if (Prototype.BrowserFeatures.SpecificElementExtensions)
+    return Prototype.K;
+
+  var Methods = { }, ByTag = Element.Methods.ByTag;
+
+  var extend = Object.extend(function(element) {
+    if (!element || element._extendedByPrototype ||
+        element.nodeType != 1 || element == window) return element;
+
+    var methods = Object.clone(Methods),
+      tagName = element.tagName, property, value;
+
+    // extend methods for specific tags
+    if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]);
+
+    for (property in methods) {
+      value = methods[property];
+      if (Object.isFunction(value) && !(property in element))
+        element[property] = value.methodize();
+    }
+
+    element._extendedByPrototype = Prototype.emptyFunction;
+    return element;
+
+  }, {
+    refresh: function() {
+      // extend methods for all tags (Safari doesn't need this)
+      if (!Prototype.BrowserFeatures.ElementExtensions) {
+        Object.extend(Methods, Element.Methods);
+        Object.extend(Methods, Element.Methods.Simulated);
+      }
+    }
+  });
+
+  extend.refresh();
+  return extend;
+})();
+
+Element.hasAttribute = function(element, attribute) {
+  if (element.hasAttribute) return element.hasAttribute(attribute);
+  return Element.Methods.Simulated.hasAttribute(element, attribute);
+};
+
+Element.addMethods = function(methods) {
+  var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag;
+
+  if (!methods) {
+    Object.extend(Form, Form.Methods);
+    Object.extend(Form.Element, Form.Element.Methods);
+    Object.extend(Element.Methods.ByTag, {
+      "FORM":     Object.clone(Form.Methods),
+      "INPUT":    Object.clone(Form.Element.Methods),
+      "SELECT":   Object.clone(Form.Element.Methods),
+      "TEXTAREA": Object.clone(Form.Element.Methods)
+    });
+  }
+
+  if (arguments.length == 2) {
+    var tagName = methods;
+    methods = arguments[1];
+  }
+
+  if (!tagName) Object.extend(Element.Methods, methods || { });
+  else {
+    if (Object.isArray(tagName)) tagName.each(extend);
+    else extend(tagName);
+  }
+
+  function extend(tagName) {
+    tagName = tagName.toUpperCase();
+    if (!Element.Methods.ByTag[tagName])
+      Element.Methods.ByTag[tagName] = { };
+    Object.extend(Element.Methods.ByTag[tagName], methods);
+  }
+
+  function copy(methods, destination, onlyIfAbsent) {
+    onlyIfAbsent = onlyIfAbsent || false;
+    for (var property in methods) {
+      var value = methods[property];
+      if (!Object.isFunction(value)) continue;
+      if (!onlyIfAbsent || !(property in destination))
+        destination[property] = value.methodize();
+    }
+  }
+
+  function findDOMClass(tagName) {
+    var klass;
+    var trans = {
+      "OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph",
+      "FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList",
+      "DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading",
+      "H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote",
+      "INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION":
+      "TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD":
+      "TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR":
+      "TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET":
+      "FrameSet", "IFRAME": "IFrame"
+    };
+    if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element';
+    if (window[klass]) return window[klass];
+    klass = 'HTML' + tagName + 'Element';
+    if (window[klass]) return window[klass];
+    klass = 'HTML' + tagName.capitalize() + 'Element';
+    if (window[klass]) return window[klass];
+
+    window[klass] = { };
+    window[klass].prototype = document.createElement(tagName).__proto__;
+    return window[klass];
+  }
+
+  if (F.ElementExtensions) {
+    copy(Element.Methods, HTMLElement.prototype);
+    copy(Element.Methods.Simulated, HTMLElement.prototype, true);
+  }
+
+  if (F.SpecificElementExtensions) {
+    for (var tag in Element.Methods.ByTag) {
+      var klass = findDOMClass(tag);
+      if (Object.isUndefined(klass)) continue;
+      copy(T[tag], klass.prototype);
+    }
+  }
+
+  Object.extend(Element, Element.Methods);
+  delete Element.ByTag;
+
+  if (Element.extend.refresh) Element.extend.refresh();
+  Element.cache = { };
+};
+
+document.viewport = {
+  getDimensions: function() {
+    var dimensions = { };
+    var B = Prototype.Browser;
+    $w('width height').each(function(d) {
+      var D = d.capitalize();
+      dimensions[d] = (B.WebKit && !document.evaluate) ? self['inner' + D] :
+        (B.Opera) ? document.body['client' + D] : document.documentElement['client' + D];
+    });
+    return dimensions;
+  },
+
+  getWidth: function() {
+    return this.getDimensions().width;
+  },
+
+  getHeight: function() {
+    return this.getDimensions().height;
+  },
+
+  getScrollOffsets: function() {
+    return Element._returnOffset(
+      window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
+      window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
+  }
+};
+/* Portions of the Selector class are derived from Jack Slocum’s DomQuery,
+ * part of YUI-Ext version 0.40, distributed under the terms of an MIT-style
+ * license.  Please see http://www.yui-ext.com/ for more information. */
+
+var Selector = Class.create({
+  initialize: function(expression) {
+    this.expression = expression.strip();
+    this.compileMatcher();
+  },
+
+  shouldUseXPath: function() {
+    if (!Prototype.BrowserFeatures.XPath) return false;
+
+    var e = this.expression;
+
+    // Safari 3 chokes on :*-of-type and :empty
+    if (Prototype.Browser.WebKit &&
+     (e.include("-of-type") || e.include(":empty")))
+      return false;
+
+    // XPath can't do namespaced attributes, nor can it read
+    // the "checked" property from DOM nodes
+    if ((/(\[[\w-]*?:|:checked)/).test(this.expression))
+      return false;
+
+    return true;
+  },
+
+  compileMatcher: function() {
+    if (this.shouldUseXPath())
+      return this.compileXPathMatcher();
+
+    var e = this.expression, ps = Selector.patterns, h = Selector.handlers,
+        c = Selector.criteria, le, p, m;
+
+    if (Selector._cache[e]) {
+      this.matcher = Selector._cache[e];
+      return;
+    }
+
+    this.matcher = ["this.matcher = function(root) {",
+                    "var r = root, h = Selector.handlers, c = false, n;"];
+
+    while (e && le != e && (/\S/).test(e)) {
+      le = e;
+      for (var i in ps) {
+        p = ps[i];
+        if (m = e.match(p)) {
+          this.matcher.push(Object.isFunction(c[i]) ? c[i](m) :
+    	      new Template(c[i]).evaluate(m));
+          e = e.replace(m[0], '');
+          break;
+        }
+      }
+    }
+
+    this.matcher.push("return h.unique(n);\n}");
+    eval(this.matcher.join('\n'));
+    Selector._cache[this.expression] = this.matcher;
+  },
+
+  compileXPathMatcher: function() {
+    var e = this.expression, ps = Selector.patterns,
+        x = Selector.xpath, le, m;
+
+    if (Selector._cache[e]) {
+      this.xpath = Selector._cache[e]; return;
+    }
+
+    this.matcher = ['.//*'];
+    while (e && le != e && (/\S/).test(e)) {
+      le = e;
+      for (var i in ps) {
+        if (m = e.match(ps[i])) {
+          this.matcher.push(Object.isFunction(x[i]) ? x[i](m) :
+            new Template(x[i]).evaluate(m));
+          e = e.replace(m[0], '');
+          break;
+        }
+      }
+    }
+
+    this.xpath = this.matcher.join('');
+    Selector._cache[this.expression] = this.xpath;
+  },
+
+  findElements: function(root) {
+    root = root || document;
+    if (this.xpath) return document._getElementsByXPath(this.xpath, root);
+    return this.matcher(root);
+  },
+
+  match: function(element) {
+    this.tokens = [];
+
+    var e = this.expression, ps = Selector.patterns, as = Selector.assertions;
+    var le, p, m;
+
+    while (e && le !== e && (/\S/).test(e)) {
+      le = e;
+      for (var i in ps) {
+        p = ps[i];
+        if (m = e.match(p)) {
+          // use the Selector.assertions methods unless the selector
+          // is too complex.
+          if (as[i]) {
+            this.tokens.push([i, Object.clone(m)]);
+            e = e.replace(m[0], '');
+          } else {
+            // reluctantly do a document-wide search
+            // and look for a match in the array
+            return this.findElements(document).include(element);
+          }
+        }
+      }
+    }
+
+    var match = true, name, matches;
+    for (var i = 0, token; token = this.tokens[i]; i++) {
+      name = token[0], matches = token[1];
+      if (!Selector.assertions[name](element, matches)) {
+        match = false; break;
+      }
+    }
+
+    return match;
+  },
+
+  toString: function() {
+    return this.expression;
+  },
+
+  inspect: function() {
+    return "#<Selector:" + this.expression.inspect() + ">";
+  }
+});
+
+Object.extend(Selector, {
+  _cache: { },
+
+  xpath: {
+    descendant:   "//*",
+    child:        "/*",
+    adjacent:     "/following-sibling::*[1]",
+    laterSibling: '/following-sibling::*',
+    tagName:      function(m) {
+      if (m[1] == '*') return '';
+      return "[local-name()='" + m[1].toLowerCase() +
+             "' or local-name()='" + m[1].toUpperCase() + "']";
+    },
+    className:    "[contains(concat(' ', @class, ' '), ' #{1} ')]",
+    id:           "[@id='#{1}']",
+    attrPresence: function(m) {
+      m[1] = m[1].toLowerCase();
+      return new Template("[@#{1}]").evaluate(m);
+    },
+    attr: function(m) {
+      m[1] = m[1].toLowerCase();
+      m[3] = m[5] || m[6];
+      return new Template(Selector.xpath.operators[m[2]]).evaluate(m);
+    },
+    pseudo: function(m) {
+      var h = Selector.xpath.pseudos[m[1]];
+      if (!h) return '';
+      if (Object.isFunction(h)) return h(m);
+      return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m);
+    },
+    operators: {
+      '=':  "[@#{1}='#{3}']",
+      '!=': "[@#{1}!='#{3}']",
+      '^=': "[starts-with(@#{1}, '#{3}')]",
+      '$=': "[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']",
+      '*=': "[contains(@#{1}, '#{3}')]",
+      '~=': "[contains(concat(' ', @#{1}, ' '), ' #{3} ')]",
+      '|=': "[contains(concat('-', @#{1}, '-'), '-#{3}-')]"
+    },
+    pseudos: {
+      'first-child': '[not(preceding-sibling::*)]',
+      'last-child':  '[not(following-sibling::*)]',
+      'only-child':  '[not(preceding-sibling::* or following-sibling::*)]',
+      'empty':       "[count(*) = 0 and (count(text()) = 0 or translate(text(), ' \t\r\n', '') = '')]",
+      'checked':     "[@checked]",
+      'disabled':    "[@disabled]",
+      'enabled':     "[not(@disabled)]",
+      'not': function(m) {
+        var e = m[6], p = Selector.patterns,
+            x = Selector.xpath, le, v;
+
+        var exclusion = [];
+        while (e && le != e && (/\S/).test(e)) {
+          le = e;
+          for (var i in p) {
+            if (m = e.match(p[i])) {
+              v = Object.isFunction(x[i]) ? x[i](m) : new Template(x[i]).evaluate(m);
+              exclusion.push("(" + v.substring(1, v.length - 1) + ")");
+              e = e.replace(m[0], '');
+              break;
+            }
+          }
+        }
+        return "[not(" + exclusion.join(" and ") + ")]";
+      },
+      'nth-child':      function(m) {
+        return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ", m);
+      },
+      'nth-last-child': function(m) {
+        return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ", m);
+      },
+      'nth-of-type':    function(m) {
+        return Selector.xpath.pseudos.nth("position() ", m);
+      },
+      'nth-last-of-type': function(m) {
+        return Selector.xpath.pseudos.nth("(last() + 1 - position()) ", m);
+      },
+      'first-of-type':  function(m) {
+        m[6] = "1"; return Selector.xpath.pseudos['nth-of-type'](m);
+      },
+      'last-of-type':   function(m) {
+        m[6] = "1"; return Selector.xpath.pseudos['nth-last-of-type'](m);
+      },
+      'only-of-type':   function(m) {
+        var p = Selector.xpath.pseudos; return p['first-of-type'](m) + p['last-of-type'](m);
+      },
+      nth: function(fragment, m) {
+        var mm, formula = m[6], predicate;
+        if (formula == 'even') formula = '2n+0';
+        if (formula == 'odd')  formula = '2n+1';
+        if (mm = formula.match(/^(\d+)$/)) // digit only
+          return '[' + fragment + "= " + mm[1] + ']';
+        if (mm = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
+          if (mm[1] == "-") mm[1] = -1;
+          var a = mm[1] ? Number(mm[1]) : 1;
+          var b = mm[2] ? Number(mm[2]) : 0;
+          predicate = "[((#{fragment} - #{b}) mod #{a} = 0) and " +
+          "((#{fragment} - #{b}) div #{a} >= 0)]";
+          return new Template(predicate).evaluate({
+            fragment: fragment, a: a, b: b });
+        }
+      }
+    }
+  },
+
+  criteria: {
+    tagName:      'n = h.tagName(n, r, "#{1}", c);      c = false;',
+    className:    'n = h.className(n, r, "#{1}", c);    c = false;',
+    id:           'n = h.id(n, r, "#{1}", c);           c = false;',
+    attrPresence: 'n = h.attrPresence(n, r, "#{1}", c); c = false;',
+    attr: function(m) {
+      m[3] = (m[5] || m[6]);
+      return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}", c); c = false;').evaluate(m);
+    },
+    pseudo: function(m) {
+      if (m[6]) m[6] = m[6].replace(/"/g, '\\"');
+      return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m);
+    },
+    descendant:   'c = "descendant";',
+    child:        'c = "child";',
+    adjacent:     'c = "adjacent";',
+    laterSibling: 'c = "laterSibling";'
+  },
+
+  patterns: {
+    // combinators must be listed first
+    // (and descendant needs to be last combinator)
+    laterSibling: /^\s*~\s*/,
+    child:        /^\s*>\s*/,
+    adjacent:     /^\s*\+\s*/,
+    descendant:   /^\s/,
+
+    // selectors follow
+    tagName:      /^\s*(\*|[\w\-]+)(\b|$)?/,
+    id:           /^#([\w\-\*]+)(\b|$)/,
+    className:    /^\.([\w\-\*]+)(\b|$)/,
+    pseudo:
+/^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s|[:+~>]))/,
+    attrPresence: /^\[([\w]+)\]/,
+    attr:         /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/
+  },
+
+  // for Selector.match and Element#match
+  assertions: {
+    tagName: function(element, matches) {
+      return matches[1].toUpperCase() == element.tagName.toUpperCase();
+    },
+
+    className: function(element, matches) {
+      return Element.hasClassName(element, matches[1]);
+    },
+
+    id: function(element, matches) {
+      return element.id === matches[1];
+    },
+
+    attrPresence: function(element, matches) {
+      return Element.hasAttribute(element, matches[1]);
+    },
+
+    attr: function(element, matches) {
+      var nodeValue = Element.readAttribute(element, matches[1]);
+      return nodeValue && Selector.operators[matches[2]](nodeValue, matches[5] || matches[6]);
+    }
+  },
+
+  handlers: {
+    // UTILITY FUNCTIONS
+    // joins two collections
+    concat: function(a, b) {
+      for (var i = 0, node; node = b[i]; i++)
+        a.push(node);
+      return a;
+    },
+
+    // marks an array of nodes for counting
+    mark: function(nodes) {
+      var _true = Prototype.emptyFunction;
+      for (var i = 0, node; node = nodes[i]; i++)
+        node._countedByPrototype = _true;
+      return nodes;
+    },
+
+    unmark: function(nodes) {
+      for (var i = 0, node; node = nodes[i]; i++)
+        node._countedByPrototype = undefined;
+      return nodes;
+    },
+
+    // mark each child node with its position (for nth calls)
+    // "ofType" flag indicates whether we're indexing for nth-of-type
+    // rather than nth-child
+    index: function(parentNode, reverse, ofType) {
+      parentNode._countedByPrototype = Prototype.emptyFunction;
+      if (reverse) {
+        for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) {
+          var node = nodes[i];
+          if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
+        }
+      } else {
+        for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++)
+          if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
+      }
+    },
+
+    // filters out duplicates and extends all nodes
+    unique: function(nodes) {
+      if (nodes.length == 0) return nodes;
+      var results = [], n;
+      for (var i = 0, l = nodes.length; i < l; i++)
+        if (!(n = nodes[i])._countedByPrototype) {
+          n._countedByPrototype = Prototype.emptyFunction;
+          results.push(Element.extend(n));
+        }
+      return Selector.handlers.unmark(results);
+    },
+
+    // COMBINATOR FUNCTIONS
+    descendant: function(nodes) {
+      var h = Selector.handlers;
+      for (var i = 0, results = [], node; node = nodes[i]; i++)
+        h.concat(results, node.getElementsByTagName('*'));
+      return results;
+    },
+
+    child: function(nodes) {
+      var h = Selector.handlers;
+      for (var i = 0, results = [], node; node = nodes[i]; i++) {
+        for (var j = 0, child; child = node.childNodes[j]; j++)
+          if (child.nodeType == 1 && child.tagName != '!') results.push(child);
+      }
+      return results;
+    },
+
+    adjacent: function(nodes) {
+      for (var i = 0, results = [], node; node = nodes[i]; i++) {
+        var next = this.nextElementSibling(node);
+        if (next) results.push(next);
+      }
+      return results;
+    },
+
+    laterSibling: function(nodes) {
+      var h = Selector.handlers;
+      for (var i = 0, results = [], node; node = nodes[i]; i++)
+        h.concat(results, Element.nextSiblings(node));
+      return results;
+    },
+
+    nextElementSibling: function(node) {
+      while (node = node.nextSibling)
+	      if (node.nodeType == 1) return node;
+      return null;
+    },
+
+    previousElementSibling: function(node) {
+      while (node = node.previousSibling)
+        if (node.nodeType == 1) return node;
+      return null;
+    },
+
+    // TOKEN FUNCTIONS
+    tagName: function(nodes, root, tagName, combinator) {
+      var uTagName = tagName.toUpperCase();
+      var results = [], h = Selector.handlers;
+      if (nodes) {
+        if (combinator) {
+          // fastlane for ordinary descendant combinators
+          if (combinator == "descendant") {
+            for (var i = 0, node; node = nodes[i]; i++)
+              h.concat(results, node.getElementsByTagName(tagName));
+            return results;
+          } else nodes = this[combinator](nodes);
+          if (tagName == "*") return nodes;
+        }
+        for (var i = 0, node; node = nodes[i]; i++)
+          if (node.tagName.toUpperCase() === uTagName) results.push(node);
+        return results;
+      } else return root.getElementsByTagName(tagName);
+    },
+
+    id: function(nodes, root, id, combinator) {
+      var targetNode = $(id), h = Selector.handlers;
+      if (!targetNode) return [];
+      if (!nodes && root == document) return [targetNode];
+      if (nodes) {
+        if (combinator) {
+          if (combinator == 'child') {
+            for (var i = 0, node; node = nodes[i]; i++)
+              if (targetNode.parentNode == node) return [targetNode];
+          } else if (combinator == 'descendant') {
+            for (var i = 0, node; node = nodes[i]; i++)
+              if (Element.descendantOf(targetNode, node)) return [targetNode];
+          } else if (combinator == 'adjacent') {
+            for (var i = 0, node; node = nodes[i]; i++)
+              if (Selector.handlers.previousElementSibling(targetNode) == node)
+                return [targetNode];
+          } else nodes = h[combinator](nodes);
+        }
+        for (var i = 0, node; node = nodes[i]; i++)
+          if (node == targetNode) return [targetNode];
+        return [];
+      }
+      return (targetNode && Element.descendantOf(targetNode, root)) ? [targetNode] : [];
+    },
+
+    className: function(nodes, root, className, combinator) {
+      if (nodes && combinator) nodes = this[combinator](nodes);
+      return Selector.handlers.byClassName(nodes, root, className);
+    },
+
+    byClassName: function(nodes, root, className) {
+      if (!nodes) nodes = Selector.handlers.descendant([root]);
+      var needle = ' ' + className + ' ';
+      for (var i = 0, results = [], node, nodeClassName; node = nodes[i]; i++) {
+        nodeClassName = node.className;
+        if (nodeClassName.length == 0) continue;
+        if (nodeClassName == className || (' ' + nodeClassName + ' ').include(needle))
+          results.push(node);
+      }
+      return results;
+    },
+
+    attrPresence: function(nodes, root, attr, combinator) {
+      if (!nodes) nodes = root.getElementsByTagName("*");
+      if (nodes && combinator) nodes = this[combinator](nodes);
+      var results = [];
+      for (var i = 0, node; node = nodes[i]; i++)
+        if (Element.hasAttribute(node, attr)) results.push(node);
+      return results;
+    },
+
+    attr: function(nodes, root, attr, value, operator, combinator) {
+      if (!nodes) nodes = root.getElementsByTagName("*");
+      if (nodes && combinator) nodes = this[combinator](nodes);
+      var handler = Selector.operators[operator], results = [];
+      for (var i = 0, node; node = nodes[i]; i++) {
+        var nodeValue = Element.readAttribute(node, attr);
+        if (nodeValue === null) continue;
+        if (handler(nodeValue, value)) results.push(node);
+      }
+      return results;
+    },
+
+    pseudo: function(nodes, name, value, root, combinator) {
+      if (nodes && combinator) nodes = this[combinator](nodes);
+      if (!nodes) nodes = root.getElementsByTagName("*");
+      return Selector.pseudos[name](nodes, value, root);
+    }
+  },
+
+  pseudos: {
+    'first-child': function(nodes, value, root) {
+      for (var i = 0, results = [], node; node = nodes[i]; i++) {
+        if (Selector.handlers.previousElementSibling(node)) continue;
+          results.push(node);
+      }
+      return results;
+    },
+    'last-child': function(nodes, value, root) {
+      for (var i = 0, results = [], node; node = nodes[i]; i++) {
+        if (Selector.handlers.nextElementSibling(node)) continue;
+          results.push(node);
+      }
+      return results;
+    },
+    'only-child': function(nodes, value, root) {
+      var h = Selector.handlers;
+      for (var i = 0, results = [], node; node = nodes[i]; i++)
+        if (!h.previousElementSibling(node) && !h.nextElementSibling(node))
+          results.push(node);
+      return results;
+    },
+    'nth-child':        function(nodes, formula, root) {
+      return Selector.pseudos.nth(nodes, formula, root);
+    },
+    'nth-last-child':   function(nodes, formula, root) {
+      return Selector.pseudos.nth(nodes, formula, root, true);
+    },
+    'nth-of-type':      function(nodes, formula, root) {
+      return Selector.pseudos.nth(nodes, formula, root, false, true);
+    },
+    'nth-last-of-type': function(nodes, formula, root) {
+      return Selector.pseudos.nth(nodes, formula, root, true, true);
+    },
+    'first-of-type':    function(nodes, formula, root) {
+      return Selector.pseudos.nth(nodes, "1", root, false, true);
+    },
+    'last-of-type':     function(nodes, formula, root) {
+      return Selector.pseudos.nth(nodes, "1", root, true, true);
+    },
+    'only-of-type':     function(nodes, formula, root) {
+      var p = Selector.pseudos;
+      return p['last-of-type'](p['first-of-type'](nodes, formula, root), formula, root);
+    },
+
+    // handles the an+b logic
+    getIndices: function(a, b, total) {
+      if (a == 0) return b > 0 ? [b] : [];
+      return $R(1, total).inject([], function(memo, i) {
+        if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i);
+        return memo;
+      });
+    },
+
+    // handles nth(-last)-child, nth(-last)-of-type, and (first|last)-of-type
+    nth: function(nodes, formula, root, reverse, ofType) {
+      if (nodes.length == 0) return [];
+      if (formula == 'even') formula = '2n+0';
+      if (formula == 'odd')  formula = '2n+1';
+      var h = Selector.handlers, results = [], indexed = [], m;
+      h.mark(nodes);
+      for (var i = 0, node; node = nodes[i]; i++) {
+        if (!node.parentNode._countedByPrototype) {
+          h.index(node.parentNode, reverse, ofType);
+          indexed.push(node.parentNode);
+        }
+      }
+      if (formula.match(/^\d+$/)) { // just a number
+        formula = Number(formula);
+        for (var i = 0, node; node = nodes[i]; i++)
+          if (node.nodeIndex == formula) results.push(node);
+      } else if (m = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
+        if (m[1] == "-") m[1] = -1;
+        var a = m[1] ? Number(m[1]) : 1;
+        var b = m[2] ? Number(m[2]) : 0;
+        var indices = Selector.pseudos.getIndices(a, b, nodes.length);
+        for (var i = 0, node, l = indices.length; node = nodes[i]; i++) {
+          for (var j = 0; j < l; j++)
+            if (node.nodeIndex == indices[j]) results.push(node);
+        }
+      }
+      h.unmark(nodes);
+      h.unmark(indexed);
+      return results;
+    },
+
+    'empty': function(nodes, value, root) {
+      for (var i = 0, results = [], node; node = nodes[i]; i++) {
+        // IE treats comments as element nodes
+        if (node.tagName == '!' || (node.firstChild && !node.innerHTML.match(/^\s*$/))) continue;
+        results.push(node);
+      }
+      return results;
+    },
+
+    'not': function(nodes, selector, root) {
+      var h = Selector.handlers, selectorType, m;
+      var exclusions = new Selector(selector).findElements(root);
+      h.mark(exclusions);
+      for (var i = 0, results = [], node; node = nodes[i]; i++)
+        if (!node._countedByPrototype) results.push(node);
+      h.unmark(exclusions);
+      return results;
+    },
+
+    'enabled': function(nodes, value, root) {
+      for (var i = 0, results = [], node; node = nodes[i]; i++)
+        if (!node.disabled) results.push(node);
+      return results;
+    },
+
+    'disabled': function(nodes, value, root) {
+      for (var i = 0, results = [], node; node = nodes[i]; i++)
+        if (node.disabled) results.push(node);
+      return results;
+    },
+
+    'checked': function(nodes, value, root) {
+      for (var i = 0, results = [], node; node = nodes[i]; i++)
+        if (node.checked) results.push(node);
+      return results;
+    }
+  },
+
+  operators: {
+    '=':  function(nv, v) { return nv == v; },
+    '!=': function(nv, v) { return nv != v; },
+    '^=': function(nv, v) { return nv.startsWith(v); },
+    '$=': function(nv, v) { return nv.endsWith(v); },
+    '*=': function(nv, v) { return nv.include(v); },
+    '~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); },
+    '|=': function(nv, v) { return ('-' + nv.toUpperCase() + '-').include('-' + v.toUpperCase() + '-'); }
+  },
+
+  split: function(expression) {
+    var expressions = [];
+    expression.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) {
+      expressions.push(m[1].strip());
+    });
+    return expressions;
+  },
+
+  matchElements: function(elements, expression) {
+    var matches = $$(expression), h = Selector.handlers;
+    h.mark(matches);
+    for (var i = 0, results = [], element; element = elements[i]; i++)
+      if (element._countedByPrototype) results.push(element);
+    h.unmark(matches);
+    return results;
+  },
+
+  findElement: function(elements, expression, index) {
+    if (Object.isNumber(expression)) {
+      index = expression; expression = false;
+    }
+    return Selector.matchElements(elements, expression || '*')[index || 0];
+  },
+
+  findChildElements: function(element, expressions) {
+    expressions = Selector.split(expressions.join(','));
+    var results = [], h = Selector.handlers;
+    for (var i = 0, l = expressions.length, selector; i < l; i++) {
+      selector = new Selector(expressions[i].strip());
+      h.concat(results, selector.findElements(element));
+    }
+    return (l > 1) ? h.unique(results) : results;
+  }
+});
+
+if (Prototype.Browser.IE) {
+  Object.extend(Selector.handlers, {
+    // IE returns comment nodes on getElementsByTagName("*").
+    // Filter them out.
+    concat: function(a, b) {
+      for (var i = 0, node; node = b[i]; i++)
+        if (node.tagName !== "!") a.push(node);
+      return a;
+    },
+
+    // IE improperly serializes _countedByPrototype in (inner|outer)HTML.
+    unmark: function(nodes) {
+      for (var i = 0, node; node = nodes[i]; i++)
+        node.removeAttribute('_countedByPrototype');
+      return nodes;
+    }
+  });
+}
+
+function $$() {
+  return Selector.findChildElements(document, $A(arguments));
+}
+var Form = {
+  reset: function(form) {
+    $(form).reset();
+    return form;
+  },
+
+  serializeElements: function(elements, options) {
+    if (typeof options != 'object') options = { hash: !!options };
+    else if (Object.isUndefined(options.hash)) options.hash = true;
+    var key, value, submitted = false, submit = options.submit;
+
+    var data = elements.inject({ }, function(result, element) {
+      if (!element.disabled && element.name) {
+        key = element.name; value = $(element).getValue();
+        if (value != null && (element.type != 'submit' || (!submitted &&
+            submit !== false && (!submit || key == submit) && (submitted = true)))) {
+          if (key in result) {
+            // a key is already present; construct an array of values
+            if (!Object.isArray(result[key])) result[key] = [result[key]];
+            result[key].push(value);
+          }
+          else result[key] = value;
+        }
+      }
+      return result;
+    });
+
+    return options.hash ? data : Object.toQueryString(data);
+  }
+};
+
+Form.Methods = {
+  serialize: function(form, options) {
+    return Form.serializeElements(Form.getElements(form), options);
+  },
+
+  getElements: function(form) {
+    return $A($(form).getElementsByTagName('*')).inject([],
+      function(elements, child) {
+        if (Form.Element.Serializers[child.tagName.toLowerCase()])
+          elements.push(Element.extend(child));
+        return elements;
+      }
+    );
+  },
+
+  getInputs: function(form, typeName, name) {
+    form = $(form);
+    var inputs = form.getElementsByTagName('input');
+
+    if (!typeName && !name) return $A(inputs).map(Element.extend);
+
+    for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
+      var input = inputs[i];
+      if ((typeName && input.type != typeName) || (name && input.name != name))
+        continue;
+      matchingInputs.push(Element.extend(input));
+    }
+
+    return matchingInputs;
+  },
+
+  disable: function(form) {
+    form = $(form);
+    Form.getElements(form).invoke('disable');
+    return form;
+  },
+
+  enable: function(form) {
+    form = $(form);
+    Form.getElements(form).invoke('enable');
+    return form;
+  },
+
+  findFirstElement: function(form) {
+    var elements = $(form).getElements().findAll(function(element) {
+      return 'hidden' != element.type && !element.disabled;
+    });
+    var firstByIndex = elements.findAll(function(element) {
+      return element.hasAttribute('tabIndex') && element.tabIndex >= 0;
+    }).sortBy(function(element) { return element.tabIndex }).first();
+
+    return firstByIndex ? firstByIndex : elements.find(function(element) {
+      return ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
+    });
+  },
+
+  focusFirstElement: function(form) {
+    form = $(form);
+    form.findFirstElement().activate();
+    return form;
+  },
+
+  request: function(form, options) {
+    form = $(form), options = Object.clone(options || { });
+
+    var params = options.parameters, action = form.readAttribute('action') || '';
+    if (action.blank()) action = window.location.href;
+    options.parameters = form.serialize(true);
+
+    if (params) {
+      if (Object.isString(params)) params = params.toQueryParams();
+      Object.extend(options.parameters, params);
+    }
+
+    if (form.hasAttribute('method') && !options.method)
+      options.method = form.method;
+
+    return new Ajax.Request(action, options);
+  }
+};
+
+/*--------------------------------------------------------------------------*/
+
+Form.Element = {
+  focus: function(element) {
+    $(element).focus();
+    return element;
+  },
+
+  select: function(element) {
+    $(element).select();
+    return element;
+  }
+};
+
+Form.Element.Methods = {
+  serialize: function(element) {
+    element = $(element);
+    if (!element.disabled && element.name) {
+      var value = element.getValue();
+      if (value != undefined) {
+        var pair = { };
+        pair[element.name] = value;
+        return Object.toQueryString(pair);
+      }
+    }
+    return '';
+  },
+
+  getValue: function(element) {
+    element = $(element);
+    var method = element.tagName.toLowerCase();
+    return Form.Element.Serializers[method](element);
+  },
+
+  setValue: function(element, value) {
+    element = $(element);
+    var method = element.tagName.toLowerCase();
+    Form.Element.Serializers[method](element, value);
+    return element;
+  },
+
+  clear: function(element) {
+    $(element).value = '';
+    return element;
+  },
+
+  present: function(element) {
+    return $(element).value != '';
+  },
+
+  activate: function(element) {
+    element = $(element);
+    try {
+      element.focus();
+      if (element.select && (element.tagName.toLowerCase() != 'input' ||
+          !['button', 'reset', 'submit'].include(element.type)))
+        element.select();
+    } catch (e) { }
+    return element;
+  },
+
+  disable: function(element) {
+    element = $(element);
+    element.blur();
+    element.disabled = true;
+    return element;
+  },
+
+  enable: function(element) {
+    element = $(element);
+    element.disabled = false;
+    return element;
+  }
+};
+
+/*--------------------------------------------------------------------------*/
+
+var Field = Form.Element;
+var $F = Form.Element.Methods.getValue;
+
+/*--------------------------------------------------------------------------*/
+
+Form.Element.Serializers = {
+  input: function(element, value) {
+    switch (element.type.toLowerCase()) {
+      case 'checkbox':
+      case 'radio':
+        return Form.Element.Serializers.inputSelector(element, value);
+      default:
+        return Form.Element.Serializers.textarea(element, value);
+    }
+  },
+
+  inputSelector: function(element, value) {
+    if (Object.isUndefined(value)) return element.checked ? element.value : null;
+    else element.checked = !!value;
+  },
+
+  textarea: function(element, value) {
+    if (Object.isUndefined(value)) return element.value;
+    else element.value = value;
+  },
+
+  select: function(element, index) {
+    if (Object.isUndefined(index))
+      return this[element.type == 'select-one' ?
+        'selectOne' : 'selectMany'](element);
+    else {
+      var opt, value, single = !Object.isArray(index);
+      for (var i = 0, length = element.length; i < length; i++) {
+        opt = element.options[i];
+        value = this.optionValue(opt);
+        if (single) {
+          if (value == index) {
+            opt.selected = true;
+            return;
+          }
+        }
+        else opt.selected = index.include(value);
+      }
+    }
+  },
+
+  selectOne: function(element) {
+    var index = element.selectedIndex;
+    return index >= 0 ? this.optionValue(element.options[index]) : null;
+  },
+
+  selectMany: function(element) {
+    var values, length = element.length;
+    if (!length) return null;
+
+    for (var i = 0, values = []; i < length; i++) {
+      var opt = element.options[i];
+      if (opt.selected) values.push(this.optionValue(opt));
+    }
+    return values;
+  },
+
+  optionValue: function(opt) {
+    // extend element because hasAttribute may not be native
+    return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
+  }
+};
+
+/*--------------------------------------------------------------------------*/
+
+Abstract.TimedObserver = Class.create(PeriodicalExecuter, {
+  initialize: function($super, element, frequency, callback) {
+    $super(callback, frequency);
+    this.element   = $(element);
+    this.lastValue = this.getValue();
+  },
+
+  execute: function() {
+    var value = this.getValue();
+    if (Object.isString(this.lastValue) && Object.isString(value) ?
+        this.lastValue != value : String(this.lastValue) != String(value)) {
+      this.callback(this.element, value);
+      this.lastValue = value;
+    }
+  }
+});
+
+Form.Element.Observer = Class.create(Abstract.TimedObserver, {
+  getValue: function() {
+    return Form.Element.getValue(this.element);
+  }
+});
+
+Form.Observer = Class.create(Abstract.TimedObserver, {
+  getValue: function() {
+    return Form.serialize(this.element);
+  }
+});
+
+/*--------------------------------------------------------------------------*/
+
+Abstract.EventObserver = Class.create({
+  initialize: function(element, callback) {
+    this.element  = $(element);
+    this.callback = callback;
+
+    this.lastValue = this.getValue();
+    if (this.element.tagName.toLowerCase() == 'form')
+      this.registerFormCallbacks();
+    else
+      this.registerCallback(this.element);
+  },
+
+  onElementEvent: function() {
+    var value = this.getValue();
+    if (this.lastValue != value) {
+      this.callback(this.element, value);
+      this.lastValue = value;
+    }
+  },
+
+  registerFormCallbacks: function() {
+    Form.getElements(this.element).each(this.registerCallback, this);
+  },
+
+  registerCallback: function(element) {
+    if (element.type) {
+      switch (element.type.toLowerCase()) {
+        case 'checkbox':
+        case 'radio':
+          Event.observe(element, 'click', this.onElementEvent.bind(this));
+          break;
+        default:
+          Event.observe(element, 'change', this.onElementEvent.bind(this));
+          break;
+      }
+    }
+  }
+});
+
+Form.Element.EventObserver = Class.create(Abstract.EventObserver, {
+  getValue: function() {
+    return Form.Element.getValue(this.element);
+  }
+});
+
+Form.EventObserver = Class.create(Abstract.EventObserver, {
+  getValue: function() {
+    return Form.serialize(this.element);
+  }
+});
+if (!window.Event) var Event = { };
+
+Object.extend(Event, {
+  KEY_BACKSPACE: 8,
+  KEY_TAB:       9,
+  KEY_RETURN:   13,
+  KEY_ESC:      27,
+  KEY_LEFT:     37,
+  KEY_UP:       38,
+  KEY_RIGHT:    39,
+  KEY_DOWN:     40,
+  KEY_DELETE:   46,
+  KEY_HOME:     36,
+  KEY_END:      35,
+  KEY_PAGEUP:   33,
+  KEY_PAGEDOWN: 34,
+  KEY_INSERT:   45,
+
+  cache: { },
+
+  relatedTarget: function(event) {
+    var element;
+    switch(event.type) {
+      case 'mouseover': element = event.fromElement; break;
+      case 'mouseout':  element = event.toElement;   break;
+      default: return null;
+    }
+    return Element.extend(element);
+  }
+});
+
+Event.Methods = (function() {
+  var isButton;
+
+  if (Prototype.Browser.IE) {
+    var buttonMap = { 0: 1, 1: 4, 2: 2 };
+    isButton = function(event, code) {
+      return event.button == buttonMap[code];
+    };
+
+  } else if (Prototype.Browser.WebKit) {
+    isButton = function(event, code) {
+      switch (code) {
+        case 0: return event.which == 1 && !event.metaKey;
+        case 1: return event.which == 1 && event.metaKey;
+        default: return false;
+      }
+    };
+
+  } else {
+    isButton = function(event, code) {
+      return event.which ? (event.which === code + 1) : (event.button === code);
+    };
+  }
+
+  return {
+    isLeftClick:   function(event) { return isButton(event, 0) },
+    isMiddleClick: function(event) { return isButton(event, 1) },
+    isRightClick:  function(event) { return isButton(event, 2) },
+
+    element: function(event) {
+      var node = Event.extend(event).target;
+      return Element.extend(node.nodeType == Node.TEXT_NODE ? node.parentNode : node);
+    },
+
+    findElement: function(event, expression) {
+      var element = Event.element(event);
+      if (!expression) return element;
+      var elements = [element].concat(element.ancestors());
+      return Selector.findElement(elements, expression, 0);
+    },
+
+    pointer: function(event) {
+      return {
+        x: event.pageX || (event.clientX +
+          (document.documentElement.scrollLeft || document.body.scrollLeft)),
+        y: event.pageY || (event.clientY +
+          (document.documentElement.scrollTop || document.body.scrollTop))
+      };
+    },
+
+    pointerX: function(event) { return Event.pointer(event).x },
+    pointerY: function(event) { return Event.pointer(event).y },
+
+    stop: function(event) {
+      Event.extend(event);
+      event.preventDefault();
+      event.stopPropagation();
+      event.stopped = true;
+    }
+  };
+})();
+
+Event.extend = (function() {
+  var methods = Object.keys(Event.Methods).inject({ }, function(m, name) {
+    m[name] = Event.Methods[name].methodize();
+    return m;
+  });
+
+  if (Prototype.Browser.IE) {
+    Object.extend(methods, {
+      stopPropagation: function() { this.cancelBubble = true },
+      preventDefault:  function() { this.returnValue = false },
+      inspect: function() { return "[object Event]" }
+    });
+
+    return function(event) {
+      if (!event) return false;
+      if (event._extendedByPrototype) return event;
+
+      event._extendedByPrototype = Prototype.emptyFunction;
+      var pointer = Event.pointer(event);
+      Object.extend(event, {
+        target: event.srcElement,
+        relatedTarget: Event.relatedTarget(event),
+        pageX:  pointer.x,
+        pageY:  pointer.y
+      });
+      return Object.extend(event, methods);
+    };
+
+  } else {
+    Event.prototype = Event.prototype || document.createEvent("HTMLEvents").__proto__;
+    Object.extend(Event.prototype, methods);
+    return Prototype.K;
+  }
+})();
+
+Object.extend(Event, (function() {
+  var cache = Event.cache;
+
+  function getEventID(element) {
+    if (element._prototypeEventID) return element._prototypeEventID[0];
+    arguments.callee.id = arguments.callee.id || 1;
+    return element._prototypeEventID = [++arguments.callee.id];
+  }
+
+  function getDOMEventName(eventName) {
+    if (eventName && eventName.include(':')) return "dataavailable";
+    return eventName;
+  }
+
+  function getCacheForID(id) {
+    return cache[id] = cache[id] || { };
+  }
+
+  function getWrappersForEventName(id, eventName) {
+    var c = getCacheForID(id);
+    return c[eventName] = c[eventName] || [];
+  }
+
+  function createWrapper(element, eventName, handler) {
+    var id = getEventID(element);
+    var c = getWrappersForEventName(id, eventName);
+    if (c.pluck("handler").include(handler)) return false;
+
+    var wrapper = function(event) {
+      if (!Event || !Event.extend ||
+        (event.eventName && event.eventName != eventName))
+          return false;
+
+      Event.extend(event);
+      handler.call(element, event);
+    };
+
+    wrapper.handler = handler;
+    c.push(wrapper);
+    return wrapper;
+  }
+
+  function findWrapper(id, eventName, handler) {
+    var c = getWrappersForEventName(id, eventName);
+    return c.find(function(wrapper) { return wrapper.handler == handler });
+  }
+
+  function destroyWrapper(id, eventName, handler) {
+    var c = getCacheForID(id);
+    if (!c[eventName]) return false;
+    c[eventName] = c[eventName].without(findWrapper(id, eventName, handler));
+  }
+
+  function destroyCache() {
+    for (var id in cache)
+      for (var eventName in cache[id])
+        cache[id][eventName] = null;
+  }
+
+  if (window.attachEvent) {
+    window.attachEvent("onunload", destroyCache);
+  }
+
+  return {
+    observe: function(element, eventName, handler) {
+      element = $(element);
+      var name = getDOMEventName(eventName);
+
+      var wrapper = createWrapper(element, eventName, handler);
+      if (!wrapper) return element;
+
+      if (element.addEventListener) {
+        element.addEventListener(name, wrapper, false);
+      } else {
+        element.attachEvent("on" + name, wrapper);
+      }
+
+      return element;
+    },
+
+    stopObserving: function(element, eventName, handler) {
+      element = $(element);
+      var id = getEventID(element), name = getDOMEventName(eventName);
+
+      if (!handler && eventName) {
+        getWrappersForEventName(id, eventName).each(function(wrapper) {
+          element.stopObserving(eventName, wrapper.handler);
+        });
+        return element;
+
+      } else if (!eventName) {
+        Object.keys(getCacheForID(id)).each(function(eventName) {
+          element.stopObserving(eventName);
+        });
+        return element;
+      }
+
+      var wrapper = findWrapper(id, eventName, handler);
+      if (!wrapper) return element;
+
+      if (element.removeEventListener) {
+        element.removeEventListener(name, wrapper, false);
+      } else {
+        element.detachEvent("on" + name, wrapper);
+      }
+
+      destroyWrapper(id, eventName, handler);
+
+      return element;
+    },
+
+    fire: function(element, eventName, memo) {
+      element = $(element);
+      if (element == document && document.createEvent && !element.dispatchEvent)
+        element = document.documentElement;
+
+      var event;
+      if (document.createEvent) {
+        event = document.createEvent("HTMLEvents");
+        event.initEvent("dataavailable", true, true);
+      } else {
+        event = document.createEventObject();
+        event.eventType = "ondataavailable";
+      }
+
+      event.eventName = eventName;
+      event.memo = memo || { };
+
+      if (document.createEvent) {
+        element.dispatchEvent(event);
+      } else {
+        element.fireEvent(event.eventType, event);
+      }
+
+      return Event.extend(event);
+    }
+  };
+})());
+
+Object.extend(Event, Event.Methods);
+
+Element.addMethods({
+  fire:          Event.fire,
+  observe:       Event.observe,
+  stopObserving: Event.stopObserving
+});
+
+Object.extend(document, {
+  fire:          Element.Methods.fire.methodize(),
+  observe:       Element.Methods.observe.methodize(),
+  stopObserving: Element.Methods.stopObserving.methodize(),
+  loaded:        false
+});
+
+(function() {
+  /* Support for the DOMContentLoaded event is based on work by Dan Webb,
+     Matthias Miller, Dean Edwards and John Resig. */
+
+  var timer;
+
+  function fireContentLoadedEvent() {
+    if (document.loaded) return;
+    if (timer) window.clearInterval(timer);
+    document.fire("dom:loaded");
+    document.loaded = true;
+  }
+
+  if (document.addEventListener) {
+    if (Prototype.Browser.WebKit) {
+      timer = window.setInterval(function() {
+        if (/loaded|complete/.test(document.readyState))
+          fireContentLoadedEvent();
+      }, 0);
+
+      Event.observe(window, "load", fireContentLoadedEvent);
+
+    } else {
+      document.addEventListener("DOMContentLoaded",
+        fireContentLoadedEvent, false);
+    }
+
+  } else {
+    document.write("<script id=__onDOMContentLoaded defer src=//:><\/script>");
+    $("__onDOMContentLoaded").onreadystatechange = function() {
+      if (this.readyState == "complete") {
+        this.onreadystatechange = null;
+        fireContentLoadedEvent();
+      }
+    };
+  }
+})();
+/*------------------------------- DEPRECATED -------------------------------*/
+
+Hash.toQueryString = Object.toQueryString;
+
+var Toggle = { display: Element.toggle };
+
+Element.Methods.childOf = Element.Methods.descendantOf;
+
+var Insertion = {
+  Before: function(element, content) {
+    return Element.insert(element, {before:content});
+  },
+
+  Top: function(element, content) {
+    return Element.insert(element, {top:content});
+  },
+
+  Bottom: function(element, content) {
+    return Element.insert(element, {bottom:content});
+  },
+
+  After: function(element, content) {
+    return Element.insert(element, {after:content});
+  }
+};
+
+var $continue = new Error('"throw $continue" is deprecated, use "return" instead');
+
+// This should be moved to script.aculo.us; notice the deprecated methods
+// further below, that map to the newer Element methods.
+var Position = {
+  // set to true if needed, warning: firefox performance problems
+  // NOT neeeded for page scrolling, only if draggable contained in
+  // scrollable elements
+  includeScrollOffsets: false,
+
+  // must be called before calling withinIncludingScrolloffset, every time the
+  // page is scrolled
+  prepare: function() {
+    this.deltaX =  window.pageXOffset
+                || document.documentElement.scrollLeft
+                || document.body.scrollLeft
+                || 0;
+    this.deltaY =  window.pageYOffset
+                || document.documentElement.scrollTop
+                || document.body.scrollTop
+                || 0;
+  },
+
+  // caches x/y coordinate pair to use with overlap
+  within: function(element, x, y) {
+    if (this.includeScrollOffsets)
+      return this.withinIncludingScrolloffsets(element, x, y);
+    this.xcomp = x;
+    this.ycomp = y;
+    this.offset = Element.cumulativeOffset(element);
+
+    return (y >= this.offset[1] &&
+            y <  this.offset[1] + element.offsetHeight &&
+            x >= this.offset[0] &&
+            x <  this.offset[0] + element.offsetWidth);
+  },
+
+  withinIncludingScrolloffsets: function(element, x, y) {
+    var offsetcache = Element.cumulativeScrollOffset(element);
+
+    this.xcomp = x + offsetcache[0] - this.deltaX;
+    this.ycomp = y + offsetcache[1] - this.deltaY;
+    this.offset = Element.cumulativeOffset(element);
+
+    return (this.ycomp >= this.offset[1] &&
+            this.ycomp <  this.offset[1] + element.offsetHeight &&
+            this.xcomp >= this.offset[0] &&
+            this.xcomp <  this.offset[0] + element.offsetWidth);
+  },
+
+  // within must be called directly before
+  overlap: function(mode, element) {
+    if (!mode) return 0;
+    if (mode == 'vertical')
+      return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
+        element.offsetHeight;
+    if (mode == 'horizontal')
+      return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
+        element.offsetWidth;
+  },
+
+  // Deprecation layer -- use newer Element methods now (1.5.2).
+
+  cumulativeOffset: Element.Methods.cumulativeOffset,
+
+  positionedOffset: Element.Methods.positionedOffset,
+
+  absolutize: function(element) {
+    Position.prepare();
+    return Element.absolutize(element);
+  },
+
+  relativize: function(element) {
+    Position.prepare();
+    return Element.relativize(element);
+  },
+
+  realOffset: Element.Methods.cumulativeScrollOffset,
+
+  offsetParent: Element.Methods.getOffsetParent,
+
+  page: Element.Methods.viewportOffset,
+
+  clone: function(source, target, options) {
+    options = options || { };
+    return Element.clonePosition(target, source, options);
+  }
+};
+
+/*--------------------------------------------------------------------------*/
+
+if (!document.getElementsByClassName) document.getElementsByClassName = function(instanceMethods){
+  function iter(name) {
+    return name.blank() ? null : "[contains(concat(' ', @class, ' '), ' " + name + " ')]";
+  }
+
+  instanceMethods.getElementsByClassName = Prototype.BrowserFeatures.XPath ?
+  function(element, className) {
+    className = className.toString().strip();
+    var cond = /\s/.test(className) ? $w(className).map(iter).join('') : iter(className);
+    return cond ? document._getElementsByXPath('.//*' + cond, element) : [];
+  } : function(element, className) {
+    className = className.toString().strip();
+    var elements = [], classNames = (/\s/.test(className) ? $w(className) : null);
+    if (!classNames && !className) return elements;
+
+    var nodes = $(element).getElementsByTagName('*');
+    className = ' ' + className + ' ';
+
+    for (var i = 0, child, cn; child = nodes[i]; i++) {
+      if (child.className && (cn = ' ' + child.className + ' ') && (cn.include(className) ||
+          (classNames && classNames.all(function(name) {
+            return !name.toString().blank() && cn.include(' ' + name + ' ');
+          }))))
+        elements.push(Element.extend(child));
+    }
+    return elements;
+  };
+
+  return function(className, parentElement) {
+    return $(parentElement || document.body).getElementsByClassName(className);
+  };
+}(Element.Methods);
+
+/*--------------------------------------------------------------------------*/
+
+Element.ClassNames = Class.create();
+Element.ClassNames.prototype = {
+  initialize: function(element) {
+    this.element = $(element);
+  },
+
+  _each: function(iterator) {
+    this.element.className.split(/\s+/).select(function(name) {
+      return name.length > 0;
+    })._each(iterator);
+  },
+
+  set: function(className) {
+    this.element.className = className;
+  },
+
+  add: function(classNameToAdd) {
+    if (this.include(classNameToAdd)) return;
+    this.set($A(this).concat(classNameToAdd).join(' '));
+  },
+
+  remove: function(classNameToRemove) {
+    if (!this.include(classNameToRemove)) return;
+    this.set($A(this).without(classNameToRemove).join(' '));
+  },
+
+  toString: function() {
+    return $A(this).join(' ');
+  }
+};
+
+Object.extend(Element.ClassNames.prototype, Enumerable);
+
+/*--------------------------------------------------------------------------*/
+
+Element.addMethods();
Index: /package_tags/invirt-web/0.1.5/code/static/style.css
===================================================================
--- /package_tags/invirt-web/0.1.5/code/static/style.css	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/code/static/style.css	(revision 2955)
@@ -0,0 +1,117 @@
+/*
+  Good style ideas stolen from Debathena.
+  Hey, we use some different fonts.
+  And the colors are unmistakably different.
+*/
+
+/* Basic fonts and sizes. */
+html {
+    font-size: 87.5%;
+}
+body {
+    font-family: Tahoma, Sans, sans-serif;
+}
+pre, code, samp, kbd, tt {
+    font-family: "Bitstream Vera Sans Mono", "Luxi Mono", "Courier New", monospace;
+    font-size: 100%;
+}
+
+/* Blue headings. */
+h1, h2, h3, h4, h5, h6 {
+    color: #13a;
+}
+
+/* Dividing line under the header. */
+h1 {
+    border-bottom: 1px solid black;
+    margin-top: 0;
+    overflow: auto;
+}
+
+pre {
+    background: #f6f6f6;
+    border: 1px solid #ddd;
+    padding: .125em;
+}
+a:link, a:visited {
+    text-decoration: none;
+}
+a:link:hover, a:visited:hover {
+    text-decoration: underline;
+}
+
+/* Keep help-popup links unbolded in e.g. table headings. */
+.helplink {
+  font-weight: normal;
+}
+
+/* Highlight error messages in bright red. */
+.error {
+  color: #FF0000;
+  padding: 0.25em;
+}
+td.error {
+  border: 1px solid red;
+}
+
+/* Navigation bar. */
+.navigation {
+  padding: 0em 1em;
+  font-size: 125%;
+  font-weight: bold;
+  font-family: "Trebuchet MS", Trebuchet, Sans, sans-serif;
+}
+.navigation li {
+  display: inline;
+  padding: .2em;
+}
+
+/* Logged-in welcome message. */
+.loggedin {
+  float: right;
+}
+.loggedin .name {
+  font-weight: bold;
+}
+
+/* Machine list power buttons */
+.power {
+  width: 32px;
+  height: 32px;
+  background-color: transparent;
+  background-position: 0 0;
+  margin: 0;
+  border: 0;
+  text-indent: 64px;
+  line-height: 128px;
+  cursor: pointer;
+}
+.power:hover {
+  background-position: 0 32px;
+}
+.power.on {
+  background-image: url(power_button_on.png);
+}
+.power.off {
+  background-image: url(power_button_off.png);
+}
+
+/* Striping applied (by JavaScript) to every other row in /list. */
+tr.stripedrow {
+  background-color: #e8e8ff;
+}
+
+#machinelist td, #machinelist th {
+  padding: 0.1em 0.5em;
+}
+
+form {
+    display: inline;
+}
+
+/* styling for the results box */
+.result {
+    background-color: #e8e8ff;
+    border: 1px black solid;
+    padding: 1ex;
+}
Index: /package_tags/invirt-web/0.1.5/code/templates/command.mako
===================================================================
--- /package_tags/invirt-web/0.1.5/code/templates/command.mako	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/code/templates/command.mako	(revision 2955)
@@ -0,0 +1,9 @@
+<%page expression_filter="h" />
+<%inherit file="skeleton.mako" />
+
+<%def name="title()">
+$command ${machine.name}
+</%def>
+
+<p>${command} ${machine.name} was successful.</p>
+<p><a href="list">Return</a></p>
Index: /package_tags/invirt-web/0.1.5/code/templates/error.mako
===================================================================
--- /package_tags/invirt-web/0.1.5/code/templates/error.mako	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/code/templates/error.mako	(revision 2955)
@@ -0,0 +1,18 @@
+<%page expression_filter="h"/>
+<%inherit file="skeleton.mako" />
+
+<%def name="title()">
+ERROR!
+</%def>
+
+<p>Uh-oh!  We experienced an error.  Sorry about that.  We've gotten
+mail about it.</p>
+
+<p>Feel free to poke us at <tt>${config.contact}</tt> if this bug is
+consistently biting you and we don't seem to be fixing it.</p>
+
+<p>In case you're curious, the gory details are below.</p>
+
+<pre>
+${details}
+</pre>
Index: /package_tags/invirt-web/0.1.5/code/templates/error_raw.mako
===================================================================
--- /package_tags/invirt-web/0.1.5/code/templates/error_raw.mako	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/code/templates/error_raw.mako	(revision 2955)
@@ -0,0 +1,12 @@
+Error on operation ${op} for user ${user}: ${errorMessage}
+
+Fields:
+%for f in fields:
+${f}=${fields[f]}
+%endfor
+
+Error output:
+${stderr}\
+---- end error output
+
+${traceback}
Index: /package_tags/invirt-web/0.1.5/code/templates/functions.mako
===================================================================
--- /package_tags/invirt-web/0.1.5/code/templates/functions.mako	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/code/templates/functions.mako	(revision 2955)
@@ -0,0 +1,54 @@
+<%page expression_filter="h"/>
+<%def name="databaseList(lst, default, onchange, name, id, valueattr, descattr)">
+<select name="${name}" id="${id}" \
+% if onchange:
+onchange="${onchange}"\
+% endif
+>
+  <option ${'' if default else 'selected'} value="">None</option>
+  %for item in lst:
+  <option ${'selected' if default == getattr(item, valueattr) else ''} value="${getattr(item, valueattr)}">
+    ${getattr(item, descattr)}
+  </option>
+  % endfor
+</select>
+</%def>
+
+<%def name="cdromList(default='', onchange=None)">
+${databaseList(sorted(database.CDROM.query(), key=lambda x: x.description),
+               default, onchange, 'cdrom', 'cdromlist', 'cdrom_id', 'description')|n}
+</%def>
+
+<%def name="autoList(default='', onchange=None)">
+${databaseList(sorted(database.Autoinstall.query(), key=lambda x: x.description),
+               default, onchange, 'autoinstall', 'autoinstalllist', 'autoinstall_id', 'description')|n}
+</%def>
+
+<%def name="vmTypeList(default=None)">
+% for vmtype in (('linux-hvm', 'HVM'), ('linux', 'ParaVM'), ):
+<label>
+   <input ${'checked="checked"' if default == vmtype[0] else '' | n} type="radio" name="vmtype" id="vmtype-${vmtype[0]}" value="${vmtype[0]}" />${vmtype[1]}
+</label>
+% endfor
+</%def>
+
+<%def name="errorRow(value, err)">
+% if err and err.err_field == value:
+<tr>
+<td class="error" colspan="2">${str(err)}</td>
+</tr>
+% endif
+</%def>
+
+<%!
+def jquote(string):
+    return "'" + string.replace('\\', '\\\\').replace("'", "\\'").replace('\n', '\\n') + "'"
+
+def nl2br(string):
+    return string.replace('\n', '<br/>')
+%>
+
+<%def name="helppopup(subj)">
+## Return HTML code for a (?) link to a specified help topic
+<span class="helplink"><a href="help?simple=true;subject=${subj | u}" target="_blank" onclick="return helppopup(${subj | u,jquote})">(?)</a></span>
+</%def>
Index: /package_tags/invirt-web/0.1.5/code/templates/helloworld.mako
===================================================================
--- /package_tags/invirt-web/0.1.5/code/templates/helloworld.mako	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/code/templates/helloworld.mako	(revision 2955)
@@ -0,0 +1,19 @@
+<%page expression_filter="h"/>
+<%inherit file="skeleton.mako" />
+
+<p>Hello world!</p>
+
+<p>kwargs:</p>
+<pre style="white-space: pre-wrap">
+${repr(kwargs)}
+</pre>
+
+<p>Your request:</p>
+
+<pre style="white-space: pre-wrap">
+${repr(dir(request))}
+</pre>
+
+<%def name="title()">
+helloworld
+</%def>
Index: /package_tags/invirt-web/0.1.5/code/templates/help.mako
===================================================================
--- /package_tags/invirt-web/0.1.5/code/templates/help.mako	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/code/templates/help.mako	(revision 2955)
@@ -0,0 +1,37 @@
+<%page expression_filter="h"/>
+<%inherit file="skeleton.mako" />
+
+<%!
+	pageclass = 'help'
+%>
+
+<%def name="title()">
+% if len(subjects) == 1:
+Help on ${subjects[0]}
+% else:
+Help
+% endif
+</%def>
+
+% if not simple:
+<p>Topics: 
+% for key in sorted(mapping):
+<a href="help?subject=${key}">${key}</a>
+% endfor
+</p>
+<p>
+See also <a href="trac/wiki/tips">tips and HOWTOs on the wiki</a>.
+</p>
+% endif
+
+% for subject in subjects:
+% if subject in mapping:
+<h2>${subject}</h2>
+<p>${mapping[subject]|n}</p>
+% else:
+<p>Unknown subject '${subject}'.</p>
+% endif
+% endfor
+% if simple:
+<a href="javascript:window.close();">Close</a>
+% endif
Index: /package_tags/invirt-web/0.1.5/code/templates/info.mako
===================================================================
--- /package_tags/invirt-web/0.1.5/code/templates/info.mako	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/code/templates/info.mako	(revision 2955)
@@ -0,0 +1,102 @@
+<%page expression_filter="h"/>
+<%inherit file="skeleton.mako" />
+
+<%def name="title()">
+Info on ${machine.name}
+</%def>
+
+<%def name="infoTable()">
+<h2>Info</h2>
+<table>
+  % for key, value in fields:
+  <tr><td>${key}:</td><td>${value}</td></tr>
+  % endfor
+</table>
+</%def>
+
+<%def name="commands()">
+% if on:
+ % if not machine.type.hvm:
+  Console access: type
+  <tt>ssh ${machine.name}@${config.console.hostname}</tt>
+  on Athena. <a href="https://xvm.scripts.mit.edu/wiki/SerialConsole">(more info)</a>
+ % elif has_vnc:
+  <strong><a href="machine/${machine.machine_id}/vnc">Get Console</a></strong>
+ % else:
+  VNC console not enabled; still booting?
+ % endif
+% endif
+<%def name="command_button(title, value, cdrom=False, extra='')">
+<form action="machine/${machine.machine_id}/command/${value}" method="POST">
+  <input type="hidden" name="back" value="info" />
+  <input type="submit" class="button" name="action" value="${title}" ${extra | n}/>
+% if cdrom:
+  Boot CD: ${self.fn.cdromList()}
+% endif
+</form>
+</%def>
+  <div>
+	% if on:
+	${command_button("Power off", "destroy")}
+	${command_button("Shutdown", "shutdown")}
+	${command_button("Reboot", "reboot", cdrom=True)}
+	% else:
+	${command_button("Power on", "create", cdrom=True)}
+	% endif
+  </div>
+  <div>
+	${command_button("Delete VM", "delete", extra='''onclick="return confirm('Are you sure that you want to delete this VM?');"''')}
+  </div>
+</%def>
+
+<%def name="modifyForm()">
+% if err:
+<p class="error">We had a problem with your request:</p>
+% elif new_machine:
+<p>Successfully modified.</p>
+% endif
+% if on:
+(To edit ram, disk size, or machine name, turn off the machine first.)
+% endif
+<form action="machine/${machine.machine_id}/modify" method="POST">
+  <table>
+    <tr><td>Description:</td><td colspan="2"><textarea name="description" rows="4" cols="60">${defaults.description}</textarea></td></tr>
+    <tr><td>Owner${self.fn.helppopup("Owner")}:</td><td><input type="text" name="owner", value="${defaults.owner}"/></td></tr>
+${self.fn.errorRow('owner', err)}
+    <tr><td>Administrator${self.fn.helppopup("Administrator")}:</td><td><input type="text" name="admin", value="${defaults.administrator}"/></td></tr>
+${self.fn.errorRow('administrator', err)}
+    <tr><td>Contact email:</td><td><input type="text" name="contact" value="${defaults.contact}"/></td></tr>
+${self.fn.errorRow('contact', err)}
+% if not on:
+    <tr><td>Machine Name:</td><td><input type="text" name="name" value="${defaults.name}"/>.${config.dns.domains[0]}</td></tr>
+${self.fn.errorRow('name', err)}
+    <tr>
+      <td>HVM/ParaVM${self.fn.helppopup('HVM/ParaVM')}</td>
+      <td>${self.fn.vmTypeList(defaults.type)}</td>
+    </tr>
+    <tr><td>Ram:</td><td><input type="text" size=3 name="memory" value="${defaults.memory}"/>MiB (max ${max_mem})</td></tr>
+${self.fn.errorRow('memory', err)}
+    <tr><td>Disk:</td><td><input type="text" size=3 name="disksize" value="${defaults.disk}"/>GiB (max ${max_disk})</td><td>WARNING: Modifying disk size may corrupt your data.</td></tr>
+${self.fn.errorRow('disk', err)}
+% else:
+${self.fn.errorRow('name', err)}
+${self.fn.errorRow('memory', err)}
+${self.fn.errorRow('disk', err)}
+% endif
+    <tr><td><input type="submit" class="button" name="action" value="Change"/></td></tr>
+  </table>
+</form>
+</%def>
+
+<div id="info">
+  ${infoTable()}
+</div>
+
+<h2>Commands</h2>
+<div id="commands">
+  ${commands()}
+</div>
+<h2>Settings</h2>
+<div id="modify">
+  ${modifyForm()}
+</div>
Index: /package_tags/invirt-web/0.1.5/code/templates/invalid.mako
===================================================================
--- /package_tags/invirt-web/0.1.5/code/templates/invalid.mako	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/code/templates/invalid.mako	(revision 2955)
@@ -0,0 +1,16 @@
+<%page expression_filter="h"/>
+<%inherit file="skeleton.mako" />
+
+<%def name="title()">
+Invalid Input
+</%def>
+
+<p>Your input was bad:</p>
+<table>
+<tr><td>Field</td><td>value</td><td>reason</td></tr>
+<tr><td>${err_field}</td><td>${err_value}</td><td>${errorMessage}</td></tr>
+%if stderr:
+<p>Printed to standard error:</p>
+<pre>${stderr}</pre>
+%endif
+</table>
Index: /package_tags/invirt-web/0.1.5/code/templates/list.mako
===================================================================
--- /package_tags/invirt-web/0.1.5/code/templates/list.mako	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/code/templates/list.mako	(revision 2955)
@@ -0,0 +1,171 @@
+<%page expression_filter="h"/>
+<%inherit file="skeleton.mako" />
+<%!
+	import datetime
+%>
+
+
+<%def name="title()">
+VM List
+</%def>
+
+%if os.path.exists("/etc/invirt/motd.html"):
+<div class="result">
+<p class="error">${open('/etc/invirt/motd.html').read()|n}</p>
+</div>
+%endif
+
+<%def name="createForm()">
+% if cant_add_vm:
+<p>${cant_add_vm}</p>
+% else:
+<h2>Create a new VM</h2>
+% if err:
+<p class="error">We had a problem with your request:</p>
+% elif new_machine:
+<p>Congratulations! You successfully created a new VM called ${new_machine}.</p>
+% endif
+
+    <form action="create" method="POST">
+    <input type="hidden" name="back" value="list"/>
+      <table>
+	${self.fn.errorRow('create', err)}
+	<tr>
+	  <td>Name</td>
+	  <td><input type="text" name="name" value="${defaults.name}"/>.${config.dns.domains[0]}</td>
+	</tr>
+	${self.fn.errorRow('name', err)}
+	<tr>
+	  <td>Description</td>
+	  <td><textarea name="description" rows="4" cols="60">${defaults.description}</textarea></td>
+	</tr>
+	${self.fn.errorRow('description', err)}
+	<tr>
+	  <td>Memory</td>
+	  <td><input type="text" name="memory" value="${defaults.memory}" size=3/> MiB (${max_memory} max)</td>
+	</tr>
+	${self.fn.errorRow('memory', err)}
+	<tr>
+	  <td>Disk</td>
+	  <td><input type="text" name="disksize" value="${defaults.disk}" size=3/> GiB (${"%0.1f" % (max_disk-0.05)} max)</td>
+	</tr>
+	${self.fn.errorRow('disk', err)}
+        <tr>
+          <td>HVM/ParaVM${self.fn.helppopup('HVM/ParaVM')}</td>
+          <td>
+	  ${self.fn.vmTypeList(defaults.type)}
+	  </td>
+        </tr>
+	${self.fn.errorRow('vmtype', err)}
+	${self.fn.errorRow('autoinstall', err)}
+	<tr>
+	  <td>Autoinstall${self.fn.helppopup('Autoinstalls')}</td>
+	  <td><label><input type="radio" name="cd_or_auto" id="cd_or_auto_auto"
+                 onchange="$('cdromlist').value = ''; $('vmtype-linux').checked = true" />
+${self.fn.autoList(defaults.cdrom, "$('cd_or_auto_auto').checked = true;$('cdromlist').value = '';$('vmtype-linux').checked = true")}
+	      (experimental; 2-3 minutes, and you have a machine with empty root password.)
+</label></td>
+	</tr>
+	<tr>
+	  <td>Boot CD</td>
+	  <td><label><input type="radio" name="cd_or_auto" id="cd_or_auto_cd" checked="checked"
+                onchange="$('autoinstalllist').value = ''; $('vmtype-linux-hvm').checked = true" />
+${self.fn.cdromList(defaults.cdrom, "$('cd_or_auto_cd').checked = true;$('autoinstalllist').value = '';$('vmtype-linux-hvm').checked = true")}
+</label></td>
+	</tr>
+	${self.fn.errorRow('cdrom', err)}
+	${self.fn.errorRow('cdrom', err)}
+	<tr>
+	  <td>Owner</td>
+	  <td><input type="text" name="owner" value="${defaults.owner}"/></td>
+	</tr>
+	${self.fn.errorRow('owner', err)}
+      </table>
+      <input type="submit" class="button" value="Create it!"/><br />
+      Windows notes: ${self.fn.helppopup('Windows')}
+    </form>
+% endif
+</%def>
+
+<%def name="machineRow(machine, dark)">
+      <tr\
+% if dark:
+ class="stripedrow" \
+% endif
+> 
+	<td rowspan="2">
+	% if machine.uptime and installing[machine]:
+	<img src="static/power_installing.png" alt="Installing..." />
+	% else:
+	  <form action="machine/${machine.machine_id}/command/${'shutdown' if machine.uptime else 'create'}" method="post">
+	    <input type="hidden" name="back" value="list"/>
+	    <input type="hidden" name="machine_id"
+		   value="${machine.machine_id}"/>
+<input type="submit" class="power ${'on' if machine.uptime else 'off'}" name="action" value="${'Shutdown' if machine.uptime else 'Power on'}"\
+% if machine.uptime:
+ onclick="return confirm('Are you sure you want to power off this VM?');"
+% endif
+/>
+	  </form>
+	  % endif
+	</td>
+	<td><a href="machine/${machine.machine_id}">${machine.name}</a></td>
+	<td>${machine.memory}M</td>
+	<td>${machine.owner}</td>
+	<td>${machine.administrator}</td>
+% if machine.nics:
+	<td>${', '.join(nic.ip for nic in machine.nics)}</td>
+% else:
+	<td></td>
+% endif
+<td>\
+% if machine.uptime:
+${datetime.timedelta(seconds=int(machine.uptime))}\
+% endif
+</td>
+	<td>\
+% if has_vnc[machine] == True:
+<a href="machine/${machine.machine_id}/vnc">Console</a>\
+% elif has_vnc[machine] == 'ParaVM':
+ParaVM${self.fn.helppopup("ParaVM Console")}
+% elif has_vnc[machine] != 'Off':
+${has_vnc[machine]}
+% endif
+</td>
+      </tr>
+      <tr\
+% if dark:
+ class="stripedrow" \
+% endif
+>
+        <td colspan="7" style="padding-left: 1em; color: #666">${machine.description|self.fn.module.nl2br}</td>
+      </tr>
+</%def>
+
+<%def name="machineList(machines)">
+    <table cellspacing="0" cellpadding="2">
+      <tr>
+	<th></th>
+	<th>Name</th>
+	<th>Memory</th>
+	<th>Owner${self.fn.helppopup('Owner')}</th>
+        <th>Administrator${self.fn.helppopup('Administrator')}</th>
+	<th>IP</th>
+	<th>Uptime</th>
+	<th>VNC</th>
+      </tr>
+% for n, machine in enumerate(machines):
+	${machineRow(machine, (n%2)==0)}
+% endfor
+    </table>
+</%def>
+
+<p style="font-size: 125%;"><a href="http://${config.web.hostname}">What is XVM?</a></p>
+% if not machines:
+<p>You don't currently control any VMs.</p>   
+% endif
+    <p><a href="list">refresh</a></p>
+    <div id="machinelist">
+    ${machineList(machines)}
+    </div>
+${createForm()}
Index: /package_tags/invirt-web/0.1.5/code/templates/skeleton.mako
===================================================================
--- /package_tags/invirt-web/0.1.5/code/templates/skeleton.mako	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/code/templates/skeleton.mako	(revision 2955)
@@ -0,0 +1,89 @@
+<%page expression_filter="h"/>
+<%namespace name="fn" file="functions.mako" inheritable="True"/>
+<!DOCTYPE html
+PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html>
+<head><title>${self.title()} &mdash; XVM</title>
+  <base href="${cherrypy.request.base}${"/admin/" if cherrypy.request.state.isadmin else ""}" />
+  <link href="/static/favicon.ico" type="image/x-icon" rel="shortcut icon">
+  <link rel="stylesheet" href="/static/style.css" type="text/css" />
+  <link rel="stylesheet" href="/static/layout.css" type="text/css" media="screen" />
+  <script type="text/javascript" src="/static/prototype.js"></script>
+  <script type="text/javascript">
+var helpWin = null;
+function closeWin(){
+	if (helpWin != null){
+		if(!helpWin.closed)
+			helpWin.close();
+	}
+}
+
+function helppopup(name){
+   closeWin()
+   helpWin = window.open("help?simple=true&subject="+encodeURIComponent(name), "Help",
+"status, height = 300, width = 400");
+   if (window.focus){helpWin.focus();}
+   return false;
+}
+</script>
+</head>
+<body id="body"
+% if hasattr(self.attr, 'pageclass'):
+  class="${self.attr.pageclass}"
+% endif
+  >
+
+% if False:
+<div>
+<p>We are in the process of modifying the service.  Things likely will not work.</p>
+</div>
+% endif
+
+% if error_text is not UNDEFINED:
+<div id="err">
+<p>STDERR:</p><pre>${error_text}</pre>
+</div>
+% endif
+
+% if not simple:
+% if cherrypy.request.login:
+<p class="loggedin">Welcome, <span class="name">${cherrypy.request.login}</span>.
+% if cherrypy.request.state.isadmin:
+You are currently authenticated as an administrator.
+% endif
+</p>
+% endif
+
+<ul class="navigation">
+<li><a href="list">List</a></li>
+% if machine:
+<li><a href="machine/${machine.machine_id}">Info</a></li>
+<li><a href="machine/${machine.machine_id}/vnc">Console</a></li>
+% endif
+<li><a href="help">Help</a></li>
+</ul>
+
+% endif
+
+% if not simple:
+<h1>${self.title()} &mdash; XVM</h1>
+% endif
+
+% if result:
+<div id="result" class="result">
+${result}
+</div>
+% endif
+
+${next.body()}
+% if not simple:
+<hr />
+Questions? Contact <a href="mailto:xvm@mit.edu">xvm@mit.edu</a>.
+% endif
+</body>
+</html>
+
+<%def name="title()">
+XVM
+</%def>
Index: /package_tags/invirt-web/0.1.5/code/templates/unauth.mako
===================================================================
--- /package_tags/invirt-web/0.1.5/code/templates/unauth.mako	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/code/templates/unauth.mako	(revision 2955)
@@ -0,0 +1,65 @@
+<%page expression_filter="h"/>
+<%inherit file="skeleton.mako" />
+
+<%def name="title()">
+Intro
+</%def>
+
+<h1>XVM &mdash; Virtual Servers for MIT </h1>
+
+<p><strong>xvm.mit.edu</strong> is a virtualization service for the
+MIT community.  We offer <strong>virtual machines</strong>&mdash;your
+own complete system on which you can start from our <strong>three-minute
+Debian or Ubuntu install</strong> or install the <strong>operating
+system of your choice</strong>.  The service is <strong>free</strong>
+to any Athena account holder.</p>
+
+%if os.path.exists("/etc/invirt/motd.html"):
+<div class="result">
+<p class="error">${open('/etc/invirt/motd.html').read()|n}</p>
+</div>
+%endif
+
+<p>MIT users:</p>
+<blockquote><big><a
+href="https://${config.web.hostname}/"><strong><font color="green">&rarr;</font> Log in to XVM using MIT certificates</strong>
+</a></big></blockquote>
+<blockquote><big><a
+href="https://${config.web.hostname}:442/"><strong><font color="green">&rarr;</font> Log in to XVM using Kerberos Tickets</strong>
+</a></big></blockquote>
+
+<p>In order to log in, you'll need to obtain <a href="http://ca.mit.edu/">MIT certificates</a></p>
+
+<h2>XVM features:</h2>
+<ul>
+<li>Online management of virtual machines</li>
+<li>A wide selection of bootable CD-ROM images and installers</li>
+<li>An automated Debian and Ubuntu installer</li>
+<li>Secure VNC console access via a Java applet</li>
+<li>Secure serial console access over SSH</li>
+<li>Ownership and access control through Athena lockers and groups</li>
+</ul>
+
+<h2>XVM does not feature:</h2>
+<ul>
+<li>backups of VM disk images; images are on a RAID, but you should
+    arrange your own backups for data that is important to you.</li>
+<li>guarantees of uptime or security; we are a best-effort volunteer
+    service, though we follow security and reliability best practices
+    shared by production SIPB services.</li>
+</ul>
+
+<p>The XVM code base is a <strong>free software</strong> project under
+development, licensed under GPLv2+. If you're interested in using it,
+we'd be happy to help you set it up in your environment. Our Subversion
+repository is</p> <blockquote><a
+href="https://xvm.mit.edu:1111/">https://xvm.mit.edu:1111/</a></blockquote>
+
+<p>xvm.mit.edu is provided by <a href="http://sipb.mit.edu/">SIPB</a>,
+the student computing group at MIT, with generous funding from <a
+href="http://web.mit.edu/ist/">IS&amp;T</a>.  Like all SIPB projects, we
+are independently run by our own team of volunteers, and we welcome new
+contributors.</p>
+
+<p>Questions and feedback welcome at <a
+href="mailto:xvm@mit.edu">xvm@mit.edu</a>.</p>
Index: /package_tags/invirt-web/0.1.5/code/templates/vnc.mako
===================================================================
--- /package_tags/invirt-web/0.1.5/code/templates/vnc.mako	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/code/templates/vnc.mako	(revision 2955)
@@ -0,0 +1,23 @@
+<%page expression_filter="h" />
+<%inherit file="skeleton.mako" />
+
+<%def name="title()">
+Console to ${machine.name}
+</%def>
+
+<style type='text/css'>body { max-width: none }</style>
+% if not on:
+<p> Your machine appears to be off.</p>
+% elif not has_vnc:
+<p> Your machine appears to not be accepting VNC connections. Perhaps you have a ParaVM machine?</p>
+% endif
+
+<p>See <a href="help?subject=Console" target="_blank">tips</a> about framebuffer and other issues.</p>
+<applet code="VncViewer.class" archive="https://${hostname}:446/static/VncViewer.jar"
+        width="100%" height="1000">
+<param name="PORT" value="${port}">
+<param name="HOST" value="${hostname}">
+<param name="VMNAME" value="${machine.name}">
+<param name="AUTHTOKEN" value="${authtoken}">
+<param name="SocketFactory" value="VNCProxyConnectSocketFactory">
+</applet>
Index: /package_tags/invirt-web/0.1.5/code/unauth.fcgi
===================================================================
--- /package_tags/invirt-web/0.1.5/code/unauth.fcgi	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/code/unauth.fcgi	(revision 2955)
@@ -0,0 +1,3 @@
+#!/bin/sh
+
+exec ./invirt.fcgi unauth "$@"
Index: /package_tags/invirt-web/0.1.5/code/validation.py
===================================================================
--- /package_tags/invirt-web/0.1.5/code/validation.py	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/code/validation.py	(revision 2955)
@@ -0,0 +1,311 @@
+#!/usr/bin/python
+
+import cache_acls
+import getafsgroups
+import re
+import string
+import dns.resolver
+from invirt.database import Machine, NIC, Type, Disk, CDROM, Autoinstall, Owner
+from invirt.config import structs as config
+from invirt.common import InvalidInput, CodeError
+
+MIN_MEMORY_SINGLE = 16
+MIN_DISK_SINGLE = 0.1
+
+class Validate:
+    def __init__(self, username, state, machine_id=None, name=None, description=None, owner=None,
+                 admin=None, contact=None, memory=None, disksize=None,
+                 vmtype=None, cdrom=None, autoinstall=None, strict=False):
+        # XXX Successive quota checks aren't a good idea, since you
+        # can't necessarily change the locker and disk size at the
+        # same time.
+        created_new = (machine_id is None)
+
+        if strict:
+            if name is None:
+                raise InvalidInput('name', name, "You must provide a machine name.")
+            if description is None:
+                raise InvalidInput('description', description, "You must provide a description.")
+            if memory is None:
+                raise InvalidInput('memory', memory, "You must provide a memory size.")
+            if disksize is None:
+                raise InvalidInput('disk', disksize, "You must provide a disk size.")
+
+        if machine_id is not None:
+            self.machine = testMachineId(username, state, machine_id)
+        machine = getattr(self, 'machine', None)
+
+        owner = testOwner(username, owner, machine)
+        if owner is not None:
+            self.owner = owner
+        self.admin = testAdmin(username, admin, machine)
+        contact = testContact(username, contact, machine)
+        if contact is not None:
+            self.contact = contact
+        name = testName(username, name, machine)
+        if name is not None:
+            self.name = name
+        description = testDescription(username, description, machine)
+        if description is not None:
+            self.description = description
+        if memory is not None:
+            self.memory = validMemory(self.owner, state, memory, machine,
+                                      on=not created_new)
+        if disksize is not None:
+            self.disksize = validDisk(self.owner, state, disksize, machine)
+        if vmtype is not None:
+            self.vmtype = validVmType(vmtype)
+        if cdrom is not None:
+            if not CDROM.query().get(cdrom):
+                raise CodeError("Invalid cdrom type '%s'" % cdrom)
+            self.cdrom = cdrom
+        if autoinstall is not None:
+            #raise InvalidInput('autoinstall', 'install',
+            #                   "The autoinstaller has been temporarily disabled")
+            self.autoinstall = Autoinstall.query().get(autoinstall)
+
+
+def getMachinesByOwner(owner, machine=None):
+    """Return the machines owned by the same as a machine.
+
+    If the machine is None, return the machines owned by the same
+    user.
+    """
+    if machine:
+        owner = machine.owner
+    return Machine.query().filter_by(owner=owner)
+
+def maxMemory(owner, g, machine=None, on=True):
+    """Return the maximum memory for a machine or a user.
+
+    If machine is None, return the memory available for a new
+    machine.  Else, return the maximum that machine can have.
+
+    on is whether the machine should be turned on.  If false, the max
+    memory for the machine to change to, if it is left off, is
+    returned.
+    """
+    (quota_total, quota_single) = Owner.getMemoryQuotas(machine.owner if machine else owner)
+
+    if not on:
+        return quota_single
+    machines = getMachinesByOwner(owner, machine)
+    active_machines = [m for m in machines if m.name in g.xmlist_raw]
+    mem_usage = sum([x.memory for x in active_machines if x != machine])
+    return min(quota_single, quota_total-mem_usage)
+
+def maxDisk(owner, machine=None):
+    """Return the maximum disk that a machine can reach.
+
+    If machine is None, the maximum disk for a new machine. Otherwise,
+    return the maximum that a given machine can be changed to.
+    """
+    (quota_total, quota_single) = Owner.getDiskQuotas(machine.owner if machine else owner)
+
+    if machine is not None:
+        machine_id = machine.machine_id
+    else:
+        machine_id = None
+    disk_usage = Disk.query().filter(Disk.c.machine_id != machine_id).\
+                     join('machine').\
+                     filter_by(owner=owner).sum(Disk.c.size) or 0
+    return min(quota_single, quota_total-disk_usage/1024.)
+
+def cantAddVm(owner, g):
+    machines = getMachinesByOwner(owner)
+    active_machines = [m for m in machines if m.name in g.xmlist_raw]
+    (quota_total, quota_active) = Owner.getVMQuotas(owner)
+    if machines.count() >= quota_total:
+        return 'You have too many VMs to create a new one.'
+    if len(active_machines) >= quota_active:
+        return ('You already have the maximum number of VMs turned on.  '
+                'To create more, turn one off.')
+    return False
+
+def haveAccess(user, state, machine):
+    """Return whether a user has administrative access to a machine"""
+    return (user in cache_acls.accessList(machine)
+            or (machine.adminable and state.isadmin))
+
+def owns(user, machine):
+    """Return whether a user owns a machine"""
+    return user in expandLocker(machine.owner)
+
+def validMachineName(name):
+    """Check that name is valid for a machine name"""
+    if not name:
+        return False
+    charset = string.lowercase + string.digits + '-'
+    if '-' in (name[0], name[-1]) or len(name) > 63:
+        return False
+    for x in name:
+        if x not in charset:
+            return False
+    return True
+
+def validMemory(owner, g, memory, machine=None, on=True):
+    """Parse and validate limits for memory for a given owner and machine.
+
+    on is whether the memory must be valid after the machine is
+    switched on.
+    """
+    try:
+        memory = int(memory)
+        if memory < MIN_MEMORY_SINGLE:
+            raise ValueError
+    except ValueError:
+        raise InvalidInput('memory', memory,
+                           "Minimum %s MiB" % MIN_MEMORY_SINGLE)
+    max_val = maxMemory(owner, g, machine, on)
+    if not g.isadmin and memory > max_val:
+        raise InvalidInput('memory', memory,
+                           'Maximum %s MiB for %s' % (max_val, owner))
+    return memory
+
+def validDisk(owner, g, disk, machine=None):
+    """Parse and validate limits for disk for a given owner and machine."""
+    try:
+        disk = float(disk)
+        if not g.isadmin and disk > maxDisk(owner, machine):
+            raise InvalidInput('disk', disk,
+                               "Maximum %s G" % maxDisk(owner, machine))
+        disk = int(disk * 1024)
+        if disk < MIN_DISK_SINGLE * 1024:
+            raise ValueError
+    except ValueError:
+        raise InvalidInput('disk', disk,
+                           "Minimum %s GiB" % MIN_DISK_SINGLE)
+    return disk
+
+def validVmType(vm_type):
+    if vm_type is None:
+        return None
+    t = Type.query().get(vm_type)
+    if t is None:
+        raise CodeError("Invalid vm type '%s'"  % vm_type)
+    return t
+
+def testMachineId(user, state, machine_id, exists=True):
+    """Parse, validate and check authorization for a given user and machine.
+
+    If exists is False, don't check that it exists.
+    """
+    if machine_id is None:
+        raise InvalidInput('machine_id', machine_id,
+                           "Must specify a machine ID.")
+    try:
+        machine_id = int(machine_id)
+    except ValueError:
+        raise InvalidInput('machine_id', machine_id, "Must be an integer.")
+    machine = Machine.query().get(machine_id)
+    if exists and machine is None:
+        raise InvalidInput('machine_id', machine_id, "Does not exist.")
+    if machine is not None and not haveAccess(user, state, machine):
+        raise InvalidInput('machine_id', machine_id,
+                           "You do not have access to this machine.")
+    return machine
+
+def testAdmin(user, admin, machine):
+    """Determine whether a user can set the admin of a machine to this value.
+
+    Return the value to set the admin field to (possibly 'system:' +
+    admin).  XXX is modifying this a good idea?
+    """
+    if admin is None:
+        return None
+    if machine is not None and admin == machine.administrator:
+        return admin
+    if admin == user:
+        return admin
+    if ':' not in admin:
+        if cache_acls.isUser(admin):
+            return admin
+        admin = 'system:' + admin
+    try:
+        if user in getafsgroups.getAfsGroupMembers(admin, config.authz.afs.cells[0].cell):
+            return admin
+    except getafsgroups.AfsProcessError, e:
+        errmsg = str(e)
+        if errmsg.startswith("pts: User or group doesn't exist"):
+            errmsg = 'The group "%s" does not exist.' % admin
+        raise InvalidInput('administrator', admin, errmsg)
+    #XXX Should we require that user is in the admin group?
+    return admin
+
+def testOwner(user, owner, machine=None):
+    """Determine whether a user can set the owner of a machine to this value.
+
+    If machine is None, this is the owner of a new machine.
+    """
+    if machine is not None and owner in (machine.owner, None):
+        return machine.owner
+    if owner is None:
+        raise InvalidInput('owner', owner, "Owner must be specified")
+    if '@' in owner:
+        raise InvalidInput('owner', owner, "No cross-realm Hesiod lockers allowed")
+    try:
+        if user not in cache_acls.expandLocker(owner):
+            raise InvalidInput('owner', owner, 'You do not have access to the '
+                               + owner + ' locker')
+    except getafsgroups.AfsProcessError, e:
+        raise InvalidInput('owner', owner, str(e))
+    return owner
+
+def testContact(user, contact, machine=None):
+    if contact is None or (machine is not None and contact == machine.contact):
+        return None
+    if not re.match("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$", contact, re.I):
+        raise InvalidInput('contact', contact, "Not a valid email.")
+    return contact
+
+def testName(user, name, machine=None):
+    if name is None:
+        return None
+    name = name.lower()
+    if machine is not None and name == machine.name:
+        return None
+    try:
+        hostname = '%s.%s.' % (name, config.dns.domains[0])
+        resolver = dns.resolver.Resolver()
+        resolver.nameservers = ['127.0.0.1']
+        try:
+            resolver.query(hostname, 'A')
+        except dns.resolver.NoAnswer, e:
+            # If we can get the TXT record, then we can verify it's
+            # reserved. If this lookup fails, let it bubble up and be
+            # dealt with
+            answer = resolver.query(hostname, 'TXT')
+            txt = answer[0].strings[0]
+            if txt.startswith('reserved'):
+                raise InvalidInput('name', name, 'The name you have requested has been %s. For more information, contact us at %s' % (txt, config.dns.contact))
+
+        # If the hostname didn't exist, it would have thrown an
+        # exception by now - error out
+        raise InvalidInput('name', name, 'Name is already taken.')
+    except dns.resolver.NXDOMAIN, e:
+        if not validMachineName(name):
+            raise InvalidInput('name', name, 'You must provide a machine name.  Max 63 chars, alnum plus \'-\', does not begin or end with \'-\'.')
+        return name
+    except InvalidInput:
+        raise
+    except:
+        # Any other error is a validation failure
+        raise InvalidInput('name', name, 'We were unable to verify that this name is available. If you believe this is in error, please contact us at %s' % config.dns.contact)
+
+def testDescription(user, description, machine=None):
+    if description is None or description.strip() == '':
+        return None
+    return description.strip()
+
+def testHostname(user, hostname, machine):
+    for nic in machine.nics:
+        if hostname == nic.hostname:
+            return hostname
+    # check if doesn't already exist
+    if NIC.select_by(hostname=hostname):
+        raise InvalidInput('hostname', hostname,
+                           "Already exists")
+    if not re.match("^[A-Z0-9-]{1,22}$", hostname, re.I):
+        raise InvalidInput('hostname', hostname, "Not a valid hostname; "
+                           "must only use number, letters, and dashes.")
+    return hostname
Index: /package_tags/invirt-web/0.1.5/code/view.py
===================================================================
--- /package_tags/invirt-web/0.1.5/code/view.py	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/code/view.py	(revision 2955)
@@ -0,0 +1,168 @@
+import os, sys
+
+import cherrypy
+from mako.template import Template
+from mako.lookup import TemplateLookup
+import simplejson
+import datetime, decimal
+from StringIO import StringIO
+from invirt.config import structs as config
+from webcommon import State
+
+
+class MakoHandler(cherrypy.dispatch.LateParamPageHandler):
+    """Callable which processes a dictionary, returning the rendered body."""
+    
+    def __init__(self, template, next_handler,
+                 content_type='text/html; charset=utf-8'):
+        self.template = template
+        self.next_handler = next_handler
+        self.content_type = content_type
+    
+    def __call__(self):
+        env = globals().copy()
+        env.update(self.next_handler())
+        cherrypy.response.headers['Content-Type'] = self.content_type
+        return self.template.render(**env)
+        
+
+class MakoLoader(object):
+    
+    def __init__(self):
+        self.lookups = {}
+
+    def get_lookup(self, directories, module_directory=None,
+                     collection_size=-1, imports=[], **kwargs):
+        # Find the appropriate template lookup.
+        key = (tuple(directories), module_directory)
+        try:
+            lookup = self.lookups[key]
+        except KeyError:
+            lookup = TemplateLookup(directories=directories,
+                                    module_directory=module_directory,
+                                    collection_size=collection_size,
+                                    default_filters=['decode.utf8'],
+                                    input_encoding='utf-8',
+                                    output_encoding='utf-8',
+                                    imports=imports,
+                                    )
+            self.lookups[key] = lookup
+        return lookup
+
+    def __call__(self, filename, directories, module_directory=None,
+                 collection_size=-1, content_type='text/html; charset=utf-8',
+                 imports=[]):
+        cherrypy.request.lookup = lookup = self.get_lookup(
+            directories, module_directory, collection_size, imports)
+        cherrypy.request.template = t = lookup.get_template(filename)
+        cherrypy.request.handler = MakoHandler(
+            t, cherrypy.request.handler, content_type)
+
+cherrypy.tools.mako = cherrypy.Tool('on_start_resource', MakoLoader())
+
+
+def revertStandardError():
+    """Move stderr to stdout, and return the contents of the old stderr."""
+    errio = sys.stderr
+    if not isinstance(errio, StringIO):
+        return ''
+    sys.stderr = sys.stdout
+    errio.seek(0)
+    return errio.read()
+
+
+def catchStderr():
+    old_handler = cherrypy.request.handler
+    def wrapper(*args, **kwargs):
+        sys.stderr = StringIO()
+        ret = old_handler(*args, **kwargs)
+        e = revertStandardError()
+        if e:
+            if isinstance(ret, dict):
+                ret["error_text"] = e
+        return ret
+    if old_handler:
+        cherrypy.request.handler = wrapper
+
+cherrypy.tools.catch_stderr = cherrypy.Tool('before_handler', catchStderr)
+
+
+class JSONEncoder(simplejson.JSONEncoder):
+	def default(self, obj):
+		if isinstance(obj, datetime.datetime):
+			return str(obj)
+		elif isinstance(obj, decimal.Decimal):
+			return float(obj)
+		else:
+			return simplejson.JSONEncoder.default(self, obj)
+
+
+def jsonify_tool_callback(*args, **kwargs):
+    if not cherrypy.request.cached:
+        response = cherrypy.response
+        response.headers['Content-Type'] = 'text/javascript'
+        response.body = JSONEncoder().iterencode(response.body)
+
+cherrypy.tools.jsonify = cherrypy.Tool('before_finalize',
+                                       jsonify_tool_callback, priority=30)
+
+
+def require_login():
+    """If the user isn't logged in, raise 403 with an error."""
+    if cherrypy.request.login is False:
+        raise cherrypy.HTTPError(403,
+            "You are not authorized to access that resource")
+
+cherrypy.tools.require_login = cherrypy.Tool('on_start_resource',
+                                             require_login, priority=150)
+
+
+def require_POST():
+    """If the request isn't a POST request, raise 405 Method Not Allowed"""
+    if cherrypy.request.method != "POST":
+        raise cherrypy.HTTPError(405,
+                                 "You must submit this request with POST")
+
+cherrypy.tools.require_POST = cherrypy.Tool('on_start_resource',
+                                            require_POST, priority=150)
+
+
+def remote_user_login():
+    """Get remote user from SSL or GSSAPI, and store in request object.
+
+Get the current user based on environment variables set by SSL or
+GSSAPI, and store it in the attribute cherrpy.request.login.
+
+Per the CherryPy API (http://www.cherrypy.org/wiki/RequestObject#login),
+the attribute is set to the username on successful login, to False on
+failed login, and is left at None if the user attempted no authentication.
+"""
+    environ = cherrypy.request.wsgi_environ
+    user = environ.get('REMOTE_USER')
+    if user is None:
+        return
+    if environ.get('AUTH_TYPE') == 'Negotiate':
+        # Convert the krb5 principal into a krb4 username
+        if not user.endswith('@%s' % config.kerberos.realm):
+            cherrypy.request.login = False # failed to log in
+        else:
+            cherrypy.request.login = user.split('@')[0].replace('/', '.')
+    else:
+        cherrypy.request.login = user
+
+cherrypy.tools.remote_user_login = cherrypy.Tool('on_start_resource',
+                                                 remote_user_login, priority=50)
+
+
+def invirtwebstate_init():
+    """Initialize the cherrypy.request.state object from Invirt"""
+    if not hasattr(cherrypy.request, "state"):
+        cherrypy.request.state = State(cherrypy.request.login)
+
+cherrypy.tools.invirtwebstate = cherrypy.Tool('on_start_resource',
+                                              invirtwebstate_init, priority=100)
+
+
+class View(object):
+    _cp_config = {'tools.mako.directories':
+                      [os.path.join(os.path.dirname(__file__),'templates')]}
Index: /package_tags/invirt-web/0.1.5/code/webcommon.py
===================================================================
--- /package_tags/invirt-web/0.1.5/code/webcommon.py	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/code/webcommon.py	(revision 2955)
@@ -0,0 +1,43 @@
+"""Exceptions for the web interface."""
+
+import time
+from invirt import database
+from invirt.database import Machine, MachineAccess
+
+import controls
+
+def cachedproperty(func):
+    name = '__cache_' + func.__name__ + '_' + str(id(func))
+    def getter(self):
+        try:
+            return getattr(self, name)
+        except AttributeError:
+            value = func(self)
+            setattr(self, name, value)
+            return value
+    return property(getter)
+
+class State(object):
+    """State for a request"""
+    def __init__(self, user, isadmin=False):
+        self.username = user
+        self.isadmin = isadmin
+
+    def getMachines(self):
+        if self.isadmin:
+            return Machine.query().all()
+        else:
+            return Machine.query().join('acl').filter_by(user=self.username)
+
+    machines = cachedproperty(getMachines)
+    xmlist_raw = cachedproperty(lambda self: controls.getList())
+    xmlist = cachedproperty(lambda self:
+                                dict((m, self.xmlist_raw[m.name])
+                                     for m in self.machines
+                                     if m.name in self.xmlist_raw))
+
+    def clear(self):
+        """Clear the state so future accesses reload it."""
+        for attr in list(self.__dict__):
+            if attr.startswith('__cache_'):
+                delattr(self, attr)
Index: /package_tags/invirt-web/0.1.5/code/xen-ips
===================================================================
--- /package_tags/invirt-web/0.1.5/code/xen-ips	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/code/xen-ips	(revision 2955)
@@ -0,0 +1,56 @@
+#!/usr/bin/python
+import random
+from invirt import database
+import sqlalchemy.exceptions
+import sys
+
+# stolen directly from xend/server/netif.py
+def randomMAC():
+    """Generate a random MAC address.
+
+    Uses OUI (Organizationally Unique Identifier) 00-16-3E, allocated to
+    Xensource, Inc. The OUI list is available at
+    http://standards.ieee.org/regauth/oui/oui.txt.
+
+    The remaining 3 fields are random, with the first bit of the first
+    random field set 0.
+
+    @return: MAC address string
+    """
+    mac = [ 0x00, 0x16, 0x3e,
+            random.randint(0x00, 0x7f),
+            random.randint(0x00, 0xff),
+            random.randint(0x00, 0xff) ]
+    return ':'.join(map(lambda x: "%02x" % x, mac))
+
+# ... and stolen from xend/uuid.py
+def randomUUID():
+    """Generate a random UUID."""
+
+    return [ random.randint(0, 255) for _ in range(0, 16) ]
+
+def uuidToString(u):
+    return "-".join(["%02x" * 4, "%02x" * 2, "%02x" * 2, "%02x" * 2,
+                     "%02x" * 6]) % tuple(u)
+
+
+def usage():
+    print >> sys.stderr, "USAGE: " + sys.argv[0] + " <ip>"
+
+def addip(ip):
+    try:
+        n = database.NIC(machine=None, mac_addr=randomMAC(), ip=ip, hostname=None)
+        database.session.save(n)
+        database.session.flush()
+    except sqlalchemy.exceptions.IntegrityError:
+        pass
+
+
+if __name__ == '__main__':
+    if len(sys.argv) == 2:
+        ip = sys.argv[1]
+    else:
+        usage()
+        sys.exit(1)
+    database.connect()
+    addip(ip)
Index: /package_tags/invirt-web/0.1.5/config.todo
===================================================================
--- /package_tags/invirt-web/0.1.5/config.todo	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/config.todo	(revision 2955)
@@ -0,0 +1,19 @@
+# will differ dev/prod
+code/Makefile: base URI
+
+# may differ dev/prod?
+files/etc/apache2/sites-available/default: assumes trac
+files/etc/init.d/apache2.invirt: afs cell (for svn)
+code/templates/error.tmpl: xvm@mit.edu
+code/templates/help.tmpl: assumes trac
+code/templates/list.tmpl: XVM
+code/templates/skeleton.tmpl: XVM (twice)
+code/templates/skeleton.tmpl: xvm@mit.edu
+code/templates/unauth.tmpl: tons of text
+code/templates/unauth.tmpl: https://xvm.mit.edu
+
+# will take real code to generalize
+code/getafsgroups.py: lockers, /mit
+code/getafsgroups.py: use of pts for authz
+code/main.py: lockers, pts, in help text
+code/templates/info.tmpl: "Athena" in help text; really we need to separate code/skin/messages
Index: /package_tags/invirt-web/0.1.5/debian/changelog
===================================================================
--- /package_tags/invirt-web/0.1.5/debian/changelog	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/debian/changelog	(revision 2955)
@@ -0,0 +1,389 @@
+invirt-web (0.1.5) unstable; urgency=low
+
+  * Removed nonexistance makefile target and redundant ch{mod,gp}ing
+
+ -- Greg Brockman <gdb@mit.edu>  Tue, 19 Jan 2010 01:31:46 -0500
+
+invirt-web (0.1.4) unstable; urgency=low
+
+  * Merge invirt-web-iptables into invirt-web and use the new
+    invirt-iptables interface.
+
+ -- Evan Broder <broder@mit.edu>  Sun, 03 Jan 2010 16:36:47 -0500
+
+invirt-web (0.1.3) unstable; urgency=low
+
+  * Add some more user-friendly error handling for common errors. (LP:
+    #307296)
+
+ -- Evan Broder <broder@mit.edu>  Mon, 28 Dec 2009 13:03:00 -0600
+
+invirt-web (0.1.2) unstable; urgency=low
+
+  * Do some quick config cleanup.
+
+ -- Evan Broder <broder@mit.edu>  Mon, 21 Dec 2009 12:10:41 -0600
+
+invirt-web (0.1.1) unstable; urgency=low
+
+  * Use a different Mako template cache for auth.fcgi and unauth.fcgi
+  * Use shell scripts for the auth.fcgi and unauth.fcgi so that Apache
+    will not think they are the same script.
+
+ -- Quentin Smith <quentin@mit.edu>  Sun, 20 Dec 2009 23:53:17 -0500
+
+invirt-web (0.1.0) unstable; urgency=low
+
+  [Quentin Smith]
+  * Switch to CherryPy in place of our home-grown web framework.
+  * Switch from the Cheetah templating engine to the Mako templating engine.
+  * New URI scheme: /machine/<numeric-id>/<operation>
+    rather than /<operation>?machine_id=<numeric-id> .
+  * Fix power-on/power-off/reboot buttons for IE <=8.
+  * Move some bits of presentation code from Python into templates.
+  * Clarify that Windows licenses are available from MIT for staff.
+
+  [Evan Broder]
+  * Show newlines from descriptions in list page.
+  * Only aklog to a cell if encryption is actually needed.
+  * Re-arrange the authz configuration.
+
+ -- Greg Price <price@mit.edu>  Sat, 19 Dec 2009 21:53:40 -0500
+
+invirt-web (0.0.24) unstable; urgency=low
+
+  * Update authorization code for new config structure.
+
+ -- Evan Broder <broder@mit.edu>  Wed, 16 Dec 2009 11:47:13 -0600
+
+invirt-web (0.0.23) unstable; urgency=low
+
+  * Revert 0.0.22, since running VMs still have a password set.
+
+ -- Evan Broder <broder@mit.edu>  Mon, 28 Sep 2009 23:24:00 -0400
+
+invirt-web (0.0.22) unstable; urgency=low
+
+  * Don't supply a password to the VNC server, since one is no longer
+    required.
+
+ -- Evan Broder <broder@mit.edu>  Mon, 28 Sep 2009 21:24:06 -0400
+
+invirt-web (0.0.21) unstable; urgency=low
+
+  [ Quentin Smith ]
+  * Don't reuse IP addresses that are special in some way.
+
+  [ Evan Broder ]
+  * Cache the membership of the adminacl in addition to the ACLs for
+    machines.
+
+ -- Evan Broder <broder@mit.edu>  Fri, 27 Feb 2009 21:06:55 -0500
+
+invirt-web (0.0.20) unstable; urgency=low
+
+  * Don't confuse MB with MiB, or GB with GiB.
+
+ -- Anders Kaseorg <andersk@mit.edu>  Tue, 17 Feb 2009 04:54:54 -0500
+
+invirt-web (0.0.19) unstable; urgency=low
+
+  * modified quota checking to refer to invirt.database.Owner for quotas and defaults
+
+ -- Peter A. Iannucci <iannucci@mit.edu>  Tue, 17 Feb 2009 01:31:01 -0500
+
+invirt-web (0.0.18) unstable; urgency=low
+
+  * depend on apache2, libapache2-mod-auth-sslcert, python-dnspython
+  * enable Apache modules we need
+  * get mitCAclient.pem from debathena-ssl-certificates
+  * organize our 24 dependencies a bit
+
+ -- Greg Price <price@mit.edu>  Sat, 31 Jan 2009 14:59:14 -0500
+
+invirt-web (0.0.17) unstable; urgency=low
+
+  * Add Provides and Conflicts lines to debian/control for
+    config-package-dev
+
+ -- Evan Broder <broder@mit.edu>  Sat, 24 Jan 2009 20:15:29 -0500
+
+invirt-web (0.0.16) unstable; urgency=low
+
+  * Fix a security vulnerability: traditional `pts mem` is in cleartext
+    and could be spoofed.  Use new -encrypt option, which needs tokens.
+
+  * make initscript stop command not leave apache2 processes lying around
+    (so that restart works)
+  * Depend on mail-transport-agent, not postfix.
+
+ -- Greg Price <price@mit.edu>  Tue, 30 Dec 2008 17:43:41 -0500
+
+invirt-web (0.0.15) unstable; urgency=low
+
+  * config.{authn[0] => kerberos}.realm
+
+ -- Evan Broder <broder@mit.edu>  Wed, 10 Dec 2008 23:30:46 -0500
+
+invirt-web (0.0.14) unstable; urgency=low
+
+  * Depend on invirt-web-iptables
+
+ -- Evan Broder <broder@mit.edu>  Sun, 07 Dec 2008 09:12:45 -0500
+
+invirt-web (0.0.13) unstable; urgency=low
+
+  * Add cron dependency
+
+ -- Evan Broder <broder@mit.edu>  Thu, 20 Nov 2008 11:01:12 -0500
+
+invirt-web (0.0.12) unstable; urgency=low
+
+  * Whoops - forgot to drop an option to k5start
+
+ -- Evan Broder <broder@mit.edu>  Mon, 17 Nov 2008 04:59:31 -0500
+
+invirt-web (0.0.11) unstable; urgency=low
+
+  * Use daemon/$HOSTNAME for the svn repository instead of the first
+    principal in the keytab
+
+ -- Evan Broder <broder@mit.edu>  Mon, 17 Nov 2008 04:56:36 -0500
+
+invirt-web (0.0.10) unstable; urgency=low
+
+  * Make /etc/apache2/sites-available/default a mako template
+  * Fix a mistyped variable
+
+ -- Evan Broder <broder@mit.edu>  Sat, 15 Nov 2008 23:27:56 -0500
+
+invirt-web (0.0.9) unstable; urgency=low
+
+  * Move trac off-site - redirect somewhere else
+
+ -- Evan Broder <broder@mit.edu>  Sat, 15 Nov 2008 23:12:57 -0500
+
+invirt-web (0.0.8) unstable; urgency=low
+
+  * Don't depend on invirt-mail-config
+
+ -- Evan Broder <broder@mit.edu>  Thu, 06 Nov 2008 22:50:00 -0500
+
+invirt-web (0.0.7) unstable; urgency=low
+
+  * Query against the local nameserver to be sure there's no caching of
+    deleted hosts
+  * Depend on invirt-dns to be sure that a nameserver is running locally
+  * Depend on invirt-mail-config
+
+ -- Evan Broder <broder@mit.edu>  Thu, 06 Nov 2008 21:47:37 -0500
+
+invirt-web (0.0.6) unstable; urgency=low
+
+  * The web server needs a working AFS; make sure OpenAFS modules are
+    installed
+
+ -- Evan Broder <broder@mit.edu>  Mon, 03 Nov 2008 03:40:51 -0500
+
+invirt-web (0.0.5) unstable; urgency=low
+
+  * Add new dependency on python-dns
+
+ -- Evan Broder <broder@mit.edu>  Fri, 31 Oct 2008 22:57:41 -0400
+
+invirt-web (0.0.4) unstable; urgency=low
+
+  * sipb-xen-base -> invirt-base
+
+ -- Evan Broder <broder@mit.edu>  Tue, 28 Oct 2008 04:23:35 -0400
+
+invirt-web (0.0.3) unstable; urgency=low
+
+  * sipb-xen-vnc-client -> invirt-vnc-client
+
+ -- Evan Broder <broder@mit.edu>  Sun, 26 Oct 2008 17:28:51 -0400
+
+invirt-web (0.0.2) unstable; urgency=low
+
+  * /sipb-xen -> /invirt in apt repo URI
+
+ -- Greg Price <price@mit.edu>  Sun, 26 Oct 2008 04:56:21 -0400
+
+invirt-web (0.0.1) unstable; urgency=low
+
+  * sipb-xen-www -> invirt-web
+
+ -- Greg Price <price@mit.edu>  Sat, 25 Oct 2008 22:09:29 -0400
+
+sipb-xen-www (3.18) unstable; urgency=low
+
+  * sipb-xen-database-common -> invirt-database
+
+ -- Evan Broder <broder@mit.edu>  Sat, 25 Oct 2008 21:04:09 -0400
+
+sipb-xen-www (3.17) unstable; urgency=low
+
+  [ Quentin Smith ]
+  * Add Kerberos-authenticated web interface on port 442
+
+  [ Evan Broder ]
+  * Add config-package-dev to the build dependencies
+
+ -- Evan Broder <broder@mit.edu>  Fri, 24 Oct 2008 15:32:34 -0400
+
+sipb-xen-www (3.16) unstable; urgency=low
+
+  * Shorten initscript with spiffy new library from sipb-xen-base
+  * Fix comment copy-paste error in initscript, now that it's mostly comments
+
+ -- Greg Price <price@mit.edu>  Fri, 24 Oct 2008 07:19:13 -0400
+
+sipb-xen-www (3.15) unstable; urgency=low
+
+  * Use /etc/invirt/keytab instead of a separate keytab for apache
+
+ -- Evan Broder <broder@mit.edu>  Sun, 19 Oct 2008 19:56:04 -0400
+
+sipb-xen-www (3.14.4) unstable; urgency=low
+
+  * allow '*' wildcard in config.errormail_exclude
+
+ -- Greg Price <price@mit.edu>  Sat, 11 Oct 2008 17:32:42 -0700
+
+sipb-xen-www (3.14.3) unstable; urgency=low
+
+  * Actually stop Apache on shutdown
+
+ -- Evan Broder <broder@mit.edu>  Sun, 05 Oct 2008 00:24:40 -0400
+
+sipb-xen-www (3.14.2) unstable; urgency=low
+
+  * Be a good debian package and undo what you did on uninstall
+
+ -- Evan Broder <broder@mit.edu>  Sun, 05 Oct 2008 00:06:30 -0400
+
+sipb-xen-www (3.14.1) unstable; urgency=low
+
+  * Try again, now that I actually understand what the problem is
+
+ -- Evan Broder <broder@mit.edu>  Sat, 04 Oct 2008 23:58:46 -0400
+
+sipb-xen-www (3.14) unstable; urgency=low
+
+  * Try to fix startup ordering problem by specifying that the new startup
+    script depends on $remote_fs
+
+ -- Evan Broder <broder@mit.edu>  Sat, 04 Oct 2008 23:32:14 -0400
+
+sipb-xen-www (3.13.1) unstable; urgency=low
+
+  * Don't add another Listen 443 directive - apache gets angry
+  * And this, kids, is why you should always test your code before
+    committing
+
+ -- Evan broder <broder@mit.edu>  Fri, 03 Oct 2008 22:01:22 -0400
+
+sipb-xen-www (3.13) unstable; urgency=low
+
+  * Make sure we're listening on all the necessary ports
+
+ -- Evan Broder <broder@mit.edu>  Fri, 03 Oct 2008 21:40:47 -0400
+
+sipb-xen-www (3.12) unstable; urgency=low
+
+  * invirt-confiscate the SVN checkout
+
+ -- Evan Broder <broder@mit.edu>  Fri, 03 Oct 2008 21:01:33 -0400
+
+sipb-xen-www (3.11) unstable; urgency=low
+
+  * fix distribution
+
+ -- Greg Price <price@mit.edu>  Tue, 30 Sep 2008 23:48:37 -0400
+
+sipb-xen-www (3.10) hardy; urgency=low
+
+  * depend on debathena-afs-config and python-flup
+
+ -- Greg Price <price@mit.edu>  Mon, 29 Sep 2008 05:58:01 +0000
+
+sipb-xen-www (3.9) unstable; urgency=low
+
+  * further integration of invirt.config
+
+ -- Yang Zhang <y_z@mit.edu>  Fri,  8 Aug 2008 02:39:15 -0400
+
+sipb-xen-www (3.8) unstable; urgency=low
+
+  * sipb_xen_database -> invirt.database in cache_acls.py
+
+ -- Yang Zhang <y_z@mit.edu>  Sun,  3 Aug 2008 19:45:19 -0400
+
+sipb-xen-www (3.7) unstable; urgency=low
+
+  uncommitted changes in /etc/apache2 on xvm.mit.edu:
+  * rewrite static/ uris for admin mode
+  * allow ~ uris
+
+  * take instance from keytab in k5start apache2.init wrapper
+
+ -- Greg Price <price@mit.edu>  Mon,  4 Aug 2008 01:22:47 -0400
+
+sipb-xen-www (3.6) unstable; urgency=low
+
+  * Add Anders' kstart-using apache2 init script.
+  * Add some dependencies the svn site needs.
+  * Use daemon/xvm-2.mit.edu for svn site, as it's on xvm-2 now
+
+ -- Greg Price <price@mit.edu>  Fri,  1 Aug 2008 20:23:50 -0400
+
+sipb-xen-www (3.5) unstable; urgency=low
+
+  * Use FCGI.
+  * Lengthen timeouts to let the autoinstaller work.
+
+ -- Greg Price <price@mit.edu>  Sun, 15 Jun 2008 21:51:59 -0400
+
+sipb-xen-www (3.4) unstable; urgency=low
+
+  * xvm.mit.edu rather than sipb-xen-dev.mit.edu
+
+ -- Greg Price <price@mit.edu>  Sun, 11 May 2008 00:49:58 -0400
+
+sipb-xen-www (3.3) unstable; urgency=low
+
+  * Fix the SVN server to point to the new AFS mountpoint
+
+ -- Evan Broder <broder@mit.edu>  Fri,  9 May 2008 02:37:21 -0400
+
+sipb-xen-www (3.2) unstable; urgency=low
+
+  * Check in (part of?) the Apache config.
+  * Modify it to allow an informative front page without certs.
+  * Add that front page.
+
+ -- Greg Price <price@mit.edu>  Fri,  9 May 2008 02:11:04 -0400
+
+sipb-xen-www (3.1) unstable; urgency=low
+
+  * Fixed the crontab definition
+
+ -- SIPB Xen Project <sipb-xen@mit.edu>  Mon, 31 Mar 2008 05:49:32 -0400
+
+sipb-xen-www (3) unstable; urgency=low
+
+  * Refresh the ACL cache every 5 minutes
+
+ -- SIPB Xen Project <sipb-xen@mit.edu>  Mon, 31 Mar 2008 05:38:16 -0400
+
+sipb-xen-www (2) unstable; urgency=low
+
+  * Create sipb-xen group in preinst script.
+
+ -- Eric Price <ecprice@sipb-xen-dev.mit.edu>  Sat, 29 Mar 2008 18:45:02 -0400
+
+sipb-xen-www (1) unstable; urgency=low
+
+  * Initial Release.
+ -- SIPB Xen Project <sipb-xen@mit.edu>  Fri, 28 Mar 2008 22:43:12 -0500
+
Index: /package_tags/invirt-web/0.1.5/debian/compat
===================================================================
--- /package_tags/invirt-web/0.1.5/debian/compat	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/debian/compat	(revision 2955)
@@ -0,0 +1,1 @@
+4
Index: /package_tags/invirt-web/0.1.5/debian/control
===================================================================
--- /package_tags/invirt-web/0.1.5/debian/control	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/debian/control	(revision 2955)
@@ -0,0 +1,30 @@
+Source: invirt-web
+Section: base
+Priority: extra
+Maintainer: Invirt project <invirt@mit.edu>
+Build-Depends: cdbs (>= 0.4.23-1.1), debhelper (>= 4.1.0), config-package-dev, subversion, invirt-base
+Standards-Version: 3.7.2
+
+Package: invirt-web
+Architecture: all
+Depends: ${misc:Depends},
+# other Invirt
+ invirt-base, invirt-database,
+ invirt-dns, invirt-vnc-client, invirt-iptables,
+# web server
+ apache2, libapache2-mod-fcgid, libapache2-svn,
+ libapache2-mod-auth-sslcert, libapache2-mod-auth-kerb,
+ debathena-ssl-certificates,
+# python libraries
+ python-flup, python-simplejson,
+ python-dns, python-dnspython, python-cherrypy3,
+ python-mako,
+# misc
+ kstart,
+ debathena-afs-config, openafs-modules-xen,
+ mail-transport-agent, subversion, zephyr-clients,
+ cron,
+Provides: ${diverted-files}
+Conflicts: ${diverted-files}
+Replaces: invirt-web-iptables (<= 0.0.2)
+Description: the Invirt web interface
Index: /package_tags/invirt-web/0.1.5/debian/copyright
===================================================================
--- /package_tags/invirt-web/0.1.5/debian/copyright	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/debian/copyright	(revision 2955)
@@ -0,0 +1,21 @@
+This software was written as part of the Invirt project <invirt@mit.edu>.
+
+Copyright :
+
+  This program is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 2 of the License, or
+  (at your option) any later version.
+
+  This program is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+On Debian systems, the complete text of the GNU General Public License
+can be found in the file /usr/share/common-licenses/GPL.
+
+The file "code/static/power_installing.png" is from the Human-O2 icon
+set by Oliver Scholtz and is released under the "GNU/GPL" (source:
+http://www.iconfinder.net/icondetails/24350/128/ -
+http://schollidesign.deviantart.com/art/Human-O2-Iconset-105344123)
Index: /package_tags/invirt-web/0.1.5/debian/invirt-web.cron.d
===================================================================
--- /package_tags/invirt-web/0.1.5/debian/invirt-web.cron.d	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/debian/invirt-web.cron.d	(revision 2955)
@@ -0,0 +1,8 @@
+#
+# cron-jobs for invirt-web
+# Refresh the ACL cache
+#
+
+MAILTO=root
+
+*/5 * * * * www-data invirt-cache-acls
Index: /package_tags/invirt-web/0.1.5/debian/invirt-web.init
===================================================================
--- /package_tags/invirt-web/0.1.5/debian/invirt-web.init	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/debian/invirt-web.init	(revision 2955)
@@ -0,0 +1,17 @@
+#!/bin/bash
+### BEGIN INIT INFO
+# Provides:          invirt-web
+# Required-Start:    $local_fs $remote_fs
+# Required-Stop:     $local_fs $remote_fs
+# Default-Start:     2 3 4 5
+# Default-Stop:      0 1 6
+# Short-Description: Invirt web server
+# Description:
+### END INIT INFO 
+
+PACKAGE=invirt-web
+PARENTPACKAGE=apache2
+GEN_FILES=(/etc/apache2/sites-available/{default,ssl,svn} /etc/invirt-iptables/rules.d/50-invirt-web)
+
+. /lib/init/config-init.sh
+config_init "$1"
Index: /package_tags/invirt-web/0.1.5/debian/invirt-web.install
===================================================================
--- /package_tags/invirt-web/0.1.5/debian/invirt-web.install	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/debian/invirt-web.install	(revision 2955)
@@ -0,0 +1,2 @@
+files/* .
+invirt-cache-acls /usr/bin/
Index: /package_tags/invirt-web/0.1.5/debian/invirt-web.postinst
===================================================================
--- /package_tags/invirt-web/0.1.5/debian/invirt-web.postinst	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/debian/invirt-web.postinst	(revision 2955)
@@ -0,0 +1,51 @@
+#!/bin/sh
+# postinst script for #PACKAGE#
+#
+# see: dh_installdeb(1)
+
+set -e
+
+# summary of how this script can be called:
+#        * <postinst> `configure' <most-recently-configured-version>
+#        * <old-postinst> `abort-upgrade' <new version>
+#        * <conflictor's-postinst> `abort-remove' `in-favour' <package>
+#          <new-version>
+#        * <postinst> `abort-remove'
+#        * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
+#          <failed-install-package> <version> `removing'
+#          <conflicting-package> <version>
+# for details, see http://www.debian.org/doc/debian-policy/ or
+# the debian-policy package
+
+
+case "$1" in
+    configure)
+	cd /var/www/invirt-web
+	make all
+
+	a2enmod rewrite
+	a2enmod ssl
+	a2enmod auth_sslcert
+        
+        # Our init script proxies all requests to Apache's, so Apache's
+        # running is just a NOP
+        update-rc.d -f apache2 remove
+    ;;
+
+    abort-upgrade|abort-remove|abort-deconfigure)
+    ;;
+
+    *)
+        echo "postinst called with unknown argument \`$1'" >&2
+        exit 1
+    ;;
+esac
+
+# dh_installdeb will replace this with shell code automatically
+# generated by other debhelper scripts.
+
+#DEBHELPER#
+
+exit 0
+
+
Index: /package_tags/invirt-web/0.1.5/debian/invirt-web.preinst
===================================================================
--- /package_tags/invirt-web/0.1.5/debian/invirt-web.preinst	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/debian/invirt-web.preinst	(revision 2955)
@@ -0,0 +1,40 @@
+#!/bin/sh
+# preinst script for #PACKAGE#
+#
+# see: dh_installdeb(1)
+
+set -e
+
+# summary of how this script can be called:
+#        * <new-preinst> `install'
+#        * <new-preinst> `install' <old-version>
+#        * <new-preinst> `upgrade' <old-version>
+#        * <old-preinst> `abort-upgrade' <new-version>
+# for details, see http://www.debian.org/doc/debian-policy/ or
+# the debian-policy package
+
+
+case "$1" in
+    install|upgrade)
+	if ! getent group invirt > /dev/null; then
+	    addgroup --system invirt
+	fi
+    ;;
+
+    abort-upgrade)
+    ;;
+
+    *)
+        echo "preinst called with unknown argument \`$1'" >&2
+        exit 1
+    ;;
+esac
+
+# dh_installdeb will replace this with shell code automatically
+# generated by other debhelper scripts.
+
+#DEBHELPER#
+
+exit 0
+
+
Index: /package_tags/invirt-web/0.1.5/debian/invirt-web.prerm
===================================================================
--- /package_tags/invirt-web/0.1.5/debian/invirt-web.prerm	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/debian/invirt-web.prerm	(revision 2955)
@@ -0,0 +1,41 @@
+#!/bin/sh
+# prerm script for invirt-web
+#
+# see: dh_installdeb(1)
+
+set -e
+
+# summary of how this script can be called:
+#        * <prerm> `remove'
+#        * <old-prerm> `upgrade' <new-version>
+#        * <new-prerm> `failed-upgrade' <old-version>
+#        * <conflictor's-prerm> `remove' `in-favour' <package> <new-version>
+#        * <deconfigured's-prerm> `deconfigure' `in-favour'
+#          <package-being-installed> <version> `removing'
+#          <conflicting-package> <version>
+# for details, see http://www.debian.org/doc/debian-policy/ or
+# the debian-policy package
+
+
+case "$1" in
+    remove|upgrade|deconfigure)
+        update-rc.d apache2 defaults 91 9
+    ;;
+
+    failed-upgrade)
+    ;;
+
+    *)
+        echo "prerm called with unknown argument \`$1'" >&2
+        exit 1
+    ;;
+esac
+
+# dh_installdeb will replace this with shell code automatically
+# generated by other debhelper scripts.
+
+#DEBHELPER#
+
+exit 0
+
+
Index: /package_tags/invirt-web/0.1.5/debian/rules
===================================================================
--- /package_tags/invirt-web/0.1.5/debian/rules	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/debian/rules	(revision 2955)
@@ -0,0 +1,13 @@
+#!/usr/bin/make -f
+
+DEB_DIVERT_EXTENSION = .invirt
+DEB_DIVERT_FILES_invirt-web += \
+    /etc/init.d/apache2
+
+include /usr/share/cdbs/1/rules/debhelper.mk
+include /usr/share/cdbs/1/rules/config-package.mk
+
+DEB_UPDATE_RCD_PARAMS_invirt-web += defaults 91 9
+
+binary-fixup/invirt-web::
+	svn co $$(invirt-getconf svn.uri)/trunk/packages/invirt-web/code/ $(DEB_DESTDIR)/var/www/invirt-web
Index: /package_tags/invirt-web/0.1.5/files/etc/apache2/conf.d/invirt-repository
===================================================================
--- /package_tags/invirt-web/0.1.5/files/etc/apache2/conf.d/invirt-repository	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/files/etc/apache2/conf.d/invirt-repository	(revision 2955)
@@ -0,0 +1,8 @@
+Alias /invirt /srv/repository
+
+<Directory /srv/repository>
+		Options Indexes FollowSymLinks MultiViews
+		AllowOverride None
+		Order allow,deny
+		allow from all
+</Directory>
Index: /package_tags/invirt-web/0.1.5/files/etc/apache2/conf.d/invirt-web
===================================================================
--- /package_tags/invirt-web/0.1.5/files/etc/apache2/conf.d/invirt-web	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/files/etc/apache2/conf.d/invirt-web	(revision 2955)
@@ -0,0 +1,4 @@
+<IfModule mod_fcgid.c>
+  IPCConnectTimeout 600
+  IPCCommTimeout 600
+</IfModule>
Index: /package_tags/invirt-web/0.1.5/files/etc/apache2/sites-available/default.mako
===================================================================
--- /package_tags/invirt-web/0.1.5/files/etc/apache2/sites-available/default.mako	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/files/etc/apache2/sites-available/default.mako	(revision 2955)
@@ -0,0 +1,35 @@
+<%
+from invirt.config import structs as cfg
+hostname = cfg.web.hostname
+errmail  = cfg.web.errormail
+tracuri  = cfg.trac.uri
+%>
+NameVirtualHost *:80
+<VirtualHost *:80>
+	ServerAdmin ${errmail}
+        ServerName ${hostname}:80
+	
+	DocumentRoot /var/www/invirt-web
+	<Directory /var/www/invirt-web>
+		Options Indexes FollowSymLinks MultiViews ExecCGI
+		AllowOverride None
+		Order allow,deny
+		allow from all
+	</Directory>
+
+	RewriteEngine On
+	RewriteRule ^/static(.*) - [L]
+	RewriteRule ^/admin/static(.*) /static/$1 [L]
+	RewriteRule ^/trac(.*) ${tracuri}$1 [R,L]
+	RewriteRule ^/invirt - [L]
+	RewriteRule ^/(.*) /var/www/invirt-web/unauth.fcgi/$1 [L]
+
+	ErrorLog /var/log/apache2/error.log
+
+	# Possible values include: debug, info, notice, warn, error, crit,
+	# alert, emerg.
+	LogLevel notice
+
+	CustomLog /var/log/apache2/access.log combined
+	ServerSignature On
+</VirtualHost>
Index: /package_tags/invirt-web/0.1.5/files/etc/apache2/sites-available/ssl.mako
===================================================================
--- /package_tags/invirt-web/0.1.5/files/etc/apache2/sites-available/ssl.mako	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/files/etc/apache2/sites-available/ssl.mako	(revision 2955)
@@ -0,0 +1,114 @@
+<%
+from invirt.config import structs as cfg
+hostname = cfg.web.hostname
+errmail  = cfg.web.errormail
+tracuri  = cfg.trac.uri
+%>
+Listen 442
+Listen 446
+
+<%def name="invirt_webinterface()">
+	DocumentRoot /var/www/invirt-web
+	<Directory /var/www/invirt-web>
+		Options Indexes FollowSymLinks MultiViews ExecCGI
+		AllowOverride None
+		Order allow,deny
+		allow from all
+	</Directory>
+	<Location />
+${caller.body()}
+	</Location>
+
+	RewriteEngine On
+	RewriteRule ^/favicon.ico - [L]
+	RewriteRule ^/static(.*) - [L]
+	RewriteRule ^/overlord/static(.*) /static/$1 [L]
+	RewriteRule ^/admin/static(.*) /static/$1 [L]
+	RewriteRule ^/trac(.*) ${tracuri}$1 [R,L]
+	RewriteRule ^/(.*) /var/www/invirt-web/auth.fcgi/$1 [L]
+
+	RewriteLog /var/log/apache2/rewrite.log
+	RewriteLogLevel 0 
+
+	ErrorLog /var/log/apache2/error.log
+
+	# Possible values include: debug, info, notice, warn, error, crit,
+	# alert, emerg.
+	LogLevel warn
+
+	CustomLog /var/log/apache2/ssl_access.log combined
+	ServerSignature On
+
+	SSLEngine on
+
+	SSLCertificateFile ssl/server.crt
+	SSLCertificateKeyFile ssl/server.key
+	
+	SSLCACertificateFile /etc/ssl/certs/mitCAclient.pem
+	SSLVerifyDepth 10
+
+	SSLOptions +StdEnvVars
+	
+	SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0
+
+	Redirect /wiki ${tracuri}	
+</%def>
+<VirtualHost *:443>
+	ServerAdmin ${errmail}
+	ServerName ${hostname}:443
+	<%call expr="invirt_webinterface()">
+		Require valid-user
+		AuthType SSLCert
+		AuthSSLCertVar SSL_CLIENT_S_DN_Email
+		AuthSSLCertStripSuffix "@MIT.EDU"
+	</%call>
+	SSLVerifyClient require
+</VirtualHost>
+<VirtualHost *:442>
+	ServerAdmin ${errmail}
+	ServerName ${hostname}:442
+	<%call expr="invirt_webinterface()">
+		Require valid-user
+		AuthType Kerberos
+		KrbMethodNegotiate on
+		KrbMethodK5Passwd off
+		KrbAuthoritative off
+		KrbAuthRealms ${cfg.kerberos.realm}
+		Krb5Keytab /etc/invirt/keytab
+		KrbSaveCredentials off
+	</%call>
+	SSLVerifyClient optional
+</VirtualHost>
+
+<VirtualHost *:446>
+	ServerAdmin ${errmail}
+	ServerName ${hostname}:446
+	
+	DocumentRoot /var/www/invirt-web
+	<Directory />
+		Options Indexes FollowSymLinks MultiViews ExecCGI
+		AllowOverride None
+		Order allow,deny
+		allow from all
+	</Directory>
+
+	ErrorLog /var/log/apache2/error.log
+
+	# Possible values include: debug, info, notice, warn, error, crit,
+	# alert, emerg.
+	LogLevel warn
+
+	CustomLog /var/log/apache2/ssl_nocert_access.log combined
+	ServerSignature On
+
+	SSLEngine on
+
+	SSLCertificateFile ssl/server.crt
+	SSLCertificateKeyFile ssl/server.key
+	
+	SSLVerifyClient none
+
+	SSLOptions +StdEnvVars
+	
+	SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0	
+</VirtualHost>
Index: /package_tags/invirt-web/0.1.5/files/etc/apache2/sites-available/svn.mako
===================================================================
--- /package_tags/invirt-web/0.1.5/files/etc/apache2/sites-available/svn.mako	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/files/etc/apache2/sites-available/svn.mako	(revision 2955)
@@ -0,0 +1,40 @@
+<%
+from invirt.config import structs as cfg
+hostname = cfg.web.hostname
+errmail  = cfg.web.errormail
+svnpath  = cfg.svn.repopath
+%>
+Listen 1111
+<VirtualHost *:1111>
+	ServerAdmin ${errmail}
+	ServerName ${hostname}:1111
+	
+	<Directory />
+		Options FollowSymLinks
+		AllowOverride None
+	</Directory>
+	<Location />
+		DAV svn
+		SVNPath ${svnpath}
+		AuthType Basic
+		AuthName "xvm.mit.edu subversion repository"
+		AuthUserFile /etc/apache2/dav_svn.passwd
+		<LimitExcept GET PROPFIND OPTIONS REPORT>
+			Require valid-user
+		</LimitExcept>
+	</Location>
+
+	ErrorLog /var/log/apache2/error.log
+
+	# Possible values include: debug, info, notice, warn, error, crit,
+	# alert, emerg.
+	LogLevel warn
+
+	CustomLog /var/log/apache2/svn_access.log combined
+	ServerSignature On
+
+	SSLEngine on
+
+	SSLCertificateFile ssl/server.crt
+	SSLCertificateKeyFile ssl/server.key
+</VirtualHost>
Index: /package_tags/invirt-web/0.1.5/files/etc/apache2/sites-enabled/000-default
===================================================================
--- /package_tags/invirt-web/0.1.5/files/etc/apache2/sites-enabled/000-default	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/files/etc/apache2/sites-enabled/000-default	(revision 2955)
@@ -0,0 +1,1 @@
+link ../sites-available/default
Index: /package_tags/invirt-web/0.1.5/files/etc/apache2/sites-enabled/ssl
===================================================================
--- /package_tags/invirt-web/0.1.5/files/etc/apache2/sites-enabled/ssl	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/files/etc/apache2/sites-enabled/ssl	(revision 2955)
@@ -0,0 +1,1 @@
+link ../sites-available/ssl
Index: /package_tags/invirt-web/0.1.5/files/etc/apache2/sites-enabled/svn
===================================================================
--- /package_tags/invirt-web/0.1.5/files/etc/apache2/sites-enabled/svn	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/files/etc/apache2/sites-enabled/svn	(revision 2955)
@@ -0,0 +1,1 @@
+link ../sites-available/svn
Index: /package_tags/invirt-web/0.1.5/files/etc/init.d/apache2.invirt
===================================================================
--- /package_tags/invirt-web/0.1.5/files/etc/init.d/apache2.invirt	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/files/etc/init.d/apache2.invirt	(revision 2955)
@@ -0,0 +1,67 @@
+#!/usr/bin/pagsh -e
+### BEGIN INIT INFO
+# Provides:          apache2
+# Required-Start:    $local_fs $remote_fs $network $syslog openafs-client
+# Required-Stop:     $local_fs $remote_fs $network $syslog openafs-client
+# Default-Start:     2 3 4 5
+# Default-Stop:      0 1 6
+# Short-Description: Start/stop apache2 web server
+### END INIT INFO
+#
+# Apache kstart wrapper by anders.
+#
+
+SCRIPT=/etc/init.d/apache2.invirt-orig
+KSTART_PIDFILE=/var/run/k5start-apache2.pid
+KSTART_KEYTAB=/etc/invirt/keytab
+
+export AFSCELL=sipb.mit.edu
+
+kstart_start () {
+    TMP_PIDFILE=$(mktemp /tmp/k5start-apache2.pid-XXXXXX)
+    chown www-data "$TMP_PIDFILE"
+    export KRB5CCNAME=$(mktemp /tmp/krb5cc_33.kstart-XXXXXX)
+    chown www-data $KRB5CCNAME
+    /sbin/start-stop-daemon --start --pidfile "$TMP_PIDFILE" -c www-data \
+	--exec /usr/bin/k5start -- -b -p "$TMP_PIDFILE" \
+	-f "$KSTART_KEYTAB" -K10 -S afs -I "$AFSCELL" -t \
+        "daemon/$(hostname -f)"
+    cat "$TMP_PIDFILE" >|"$KSTART_PIDFILE"
+    rm -f "$TMP_PIDFILE"
+}
+kstart_stop () {
+    if [ -e $KSTART_PIDFILE ]; then
+	/sbin/start-stop-daemon --stop --pidfile $KSTART_PIDFILE
+        pgrep apache2 >/dev/null && sleep 1 \
+         && pgrep apache2 >/dev/null && sleep 1 \
+         && pgrep apache2 >/dev/null && sleep 1 \
+         && pgrep apache2 >/dev/null && sleep 1 \
+         && pkill -9 apache2
+	rm -f $KSTART_PIDFILE
+    else
+	echo -n " ... no kstart pidfile"
+    fi
+}
+
+case "$1" in
+  start)
+    echo -n "Starting kstart for Apache2: k5start"
+    kstart_start
+    echo "."
+    exec "$SCRIPT" start
+    ;;
+  stop)
+    "$SCRIPT" stop
+    echo -n "Stopping kstart for Apache2: k5start"
+    kstart_stop
+    echo "."
+    ;;
+  restart|force-reload)
+    "$0" stop
+    sleep 1
+    "$0" start
+    ;;
+  *)
+    exec "$SCRIPT" "$@"
+    ;;
+esac
Index: /package_tags/invirt-web/0.1.5/files/etc/invirt-iptables/rules.d/50-invirt-web.mako
===================================================================
--- /package_tags/invirt-web/0.1.5/files/etc/invirt-iptables/rules.d/50-invirt-web.mako	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/files/etc/invirt-iptables/rules.d/50-invirt-web.mako	(revision 2955)
@@ -0,0 +1,26 @@
+<%
+
+from invirt.config import structs as cfg
+host_port = cfg.vnc.base_port
+server_port = host_port
+
+%>\
+*nat
+:PREROUTING ACCEPT [5:300]
+:POSTROUTING ACCEPT [8:674]
+:OUTPUT ACCEPT [8:674]
+% for h in cfg.hosts:
+-A PREROUTING -s ! ${h.ip} -i eth0 -p tcp -m tcp --dport ${server_port} -j DNAT --to-destination ${h.ip}:${host_port}
+-A POSTROUTING -d ${h.ip} -o eth0 -p tcp -m tcp --dport ${host_port} -j SNAT --to-source ${cfg.vnc.proxy_ip}
+<% server_port += 1 %>\
+% endfor
+COMMIT
+
+*filter
+:INPUT ACCEPT [366:44912]
+:FORWARD ACCEPT [0:0]
+:OUTPUT ACCEPT [292:53151]
+% for h in cfg.hosts:
+-A FORWARD -d ${h.ip} -i eth0 -o eth0 -p tcp -m tcp --dport ${host_port} -j ACCEPT 
+% endfor
+COMMIT
Index: /package_tags/invirt-web/0.1.5/invirt-cache-acls
===================================================================
--- /package_tags/invirt-web/0.1.5/invirt-cache-acls	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/invirt-cache-acls	(revision 2955)
@@ -0,0 +1,9 @@
+#!/bin/sh
+cells () {
+  for i in $(invirt-getconf -l authz.afs.cells); do
+    invirt-getconf authz.afs.cells.$i.cell
+  done
+}
+kinit -k -t /etc/invirt/keytab daemon/$(hostname -f)
+aklog $(cells)
+python /var/www/invirt-web/cache_acls.py
Index: /package_tags/invirt-web/0.1.5/power.svg
===================================================================
--- /package_tags/invirt-web/0.1.5/power.svg	(revision 2955)
+++ /package_tags/invirt-web/0.1.5/power.svg	(revision 2955)
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<svg xmlns="http://www.w3.org/2000/svg" version="1.0" x="0" y="0" width="240" height="240">
+  <defs>
+    <filter id="glow">
+      <feGaussianBlur stdDeviation="10" />
+    </filter>
+  </defs>
+  <g style="fill:none;opacity:.5;stroke:#00ff00;stroke-width:50;stroke-linecap:round;filter:url(#glow)" transform="translate(120,132.65)">
+    <path d="M -54,-48.7 C -65.6,-35.8 -72.7,-18.7 -72.7,0 C -72.7,40.1 -40.2,72.7 0,72.7 C 40.1,72.7 72.7,40.2 72.7,0 C 72.7,-18.7 65.6,-35.8 54,-48.7" />
+    <line x1="0" y1="-98" x2="0" y2="0" />
+  </g>
+  <g style="fill:none;stroke:#000000;stroke-width:30;stroke-linecap:round" transform="translate(120,132.65)">
+    <path d="M -54,-48.7 C -65.6,-35.8 -72.7,-18.7 -72.7,0 C -72.7,40.1 -40.2,72.7 0,72.7 C 40.1,72.7 72.7,40.2 72.7,0 C 72.7,-18.7 65.6,-35.8 54,-48.7" />
+    <line x1="0" y1="-98" x2="0" y2="0" />
+  </g>
+  <g style="fill:none;stroke:#99ff99;stroke-width:26.25;stroke-linecap:round" transform="translate(120,132.65)">
+    <path d="M -54,-48.7 C -65.6,-35.8 -72.7,-18.7 -72.7,0 C -72.7,40.1 -40.2,72.7 0,72.7 C 40.1,72.7 72.7,40.2 72.7,0 C 72.7,-18.7 65.6,-35.8 54,-48.7" />
+    <line x1="0" y1="-98" x2="0" y2="0" />
+  </g>
+</svg>
