Index: /package_tags/sipb-xen-www/3.12/code/Makefile
===================================================================
--- /package_tags/sipb-xen-www/3.12/code/Makefile	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/code/Makefile	(revision 1024)
@@ -0,0 +1,20 @@
+DIRS = templates
+
+all: kill chmod compile
+
+chmod:
+	chgrp -R sipb-xen . 2>/dev/null || true
+	chmod -R g+w . 2>/dev/null || true
+
+kill:
+	wget http://xvm.mit.edu/kill.cgi -O /dev/null -nv
+
+compile:
+	for dir in $(DIRS); do \
+		(cd $$dir; $(MAKE) all); \
+	done
+
+clean:
+	for dir in $(DIRS); do \
+		(cd $$dir; $(MAKE) clean); \
+	done
Index: /package_tags/sipb-xen-www/3.12/code/cache_acls.py
===================================================================
--- /package_tags/sipb-xen-www/3.12/code/cache_acls.py	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/code/cache_acls.py	(revision 1024)
@@ -0,0 +1,72 @@
+#!/usr/bin/python
+from invirt.database import *
+from invirt.config import structs as config
+import sys
+import getafsgroups
+import subprocess
+
+def expandLocker(name):
+    groups = getafsgroups.getLockerAcl(name)
+    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[0].cell)
+    except getafsgroups.AfsProcessError:
+        return []
+
+def accessList(m):
+    people = set()
+    people.update(expandLocker(m.owner))
+    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.select()
+        for m in machines:
+            refreshMachine(m)
+        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/sipb-xen-www/3.12/code/controls.py
===================================================================
--- /package_tags/sipb-xen-www/3.12/code/controls.py	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/code/controls.py	(revision 1024)
@@ -0,0 +1,291 @@
+"""
+Functions to perform remctls.
+"""
+
+import validation
+from webcommon import CodeError, InvalidInput
+import random
+import subprocess
+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
+
+# ... 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 kinit():
+    """Kinit with a given username and keytab"""
+    p = subprocess.Popen(['kinit', "-k", "-t", '/etc/invirt/keytab',
+                          'daemon/'+config.web.hostname],
+                         stderr=subprocess.PIPE)
+    e = p.wait()
+    if e:
+        raise CodeError("Error %s in kinit: %s" % (e, p.stderr.read()))
+
+def checkKinit():
+    """If we lack tickets, kinit."""
+    p = subprocess.Popen(['klist', '-s'])
+    if p.wait():
+        kinit()
+
+def remctl(*args, **kws):
+    """Perform a remctl and return the output.
+
+    kinits if necessary, and outputs errors to stderr.
+    """
+    checkKinit()
+    p = subprocess.Popen(['remctl', config.remote.hostname]
+                         + list(args),
+                         stdout=subprocess.PIPE,
+                         stderr=subprocess.PIPE)
+    v = p.wait()
+    if kws.get('err'):
+        return p.stdout.read(), p.stderr.read()
+    if v:
+        print >> sys.stderr, 'Error', v, 'on remctl', args, ':'
+        print >> sys.stderr, p.stderr.read()
+        raise CodeError('ERROR on remctl')
+    return p.stdout.read()
+
+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
+    imagesize = disksize - getswap(disksize, memsize)
+    ip = machine.nics[0].ip
+    remctl('web', 'install', machine.name, autoinstall.distribution,
+           autoinstall.mirror, str(imagesize), ip)
+
+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 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 = owner
+        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).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)
+        session.commit()
+    except:
+        session.rollback()
+        raise
+    makeDisks(machine)
+    if autoinstall:
+        lvinstall(machine, autoinstall)
+    # tell it to boot with cdrom
+    bootMachine(machine, cdrom)
+    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 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, fields):
+    start_time = 0
+    machine = validation.Validate(username, state, machine_id=fields.getfirst('machine_id')).machine
+    action = fields.getfirst('action')
+    cdrom = fields.getfirst('cdrom')
+    if cdrom is not None and not CDROM.get(cdrom):
+        raise CodeError("Invalid cdrom type '%s'" % cdrom)    
+    if action not in ('Reboot', 'Power on', 'Power off', 'Shutdown', 
+                      'Delete VM'):
+        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 == 'Power on':
+        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 == 'Power off':
+        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 VM':
+        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/sipb-xen-www/3.12/code/getafsgroups.py
===================================================================
--- /package_tags/sipb-xen-www/3.12/code/getafsgroups.py	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/code/getafsgroups.py	(revision 1024)
@@ -0,0 +1,96 @@
+#!/usr/bin/python
+import pprint
+import subprocess
+
+# 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):
+    p = subprocess.Popen(["pts", "membership", "-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
+        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/sipb-xen-www/3.12/code/kill.cgi
===================================================================
--- /package_tags/sipb-xen-www/3.12/code/kill.cgi	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/code/kill.cgi	(revision 1024)
@@ -0,0 +1,5 @@
+#!/bin/sh
+pkill main.fcgi
+echo "Content-Type: text/plain"
+echo
+echo "Killed."
Index: /package_tags/sipb-xen-www/3.12/code/main.fcgi
===================================================================
--- /package_tags/sipb-xen-www/3.12/code/main.fcgi	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/code/main.fcgi	(revision 1024)
@@ -0,0 +1,3 @@
+#!/usr/bin/python
+import main
+main.main()
Index: /package_tags/sipb-xen-www/3.12/code/main.py
===================================================================
--- /package_tags/sipb-xen-www/3.12/code/main.py	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/code/main.py	(revision 1024)
@@ -0,0 +1,748 @@
+#!/usr/bin/python
+"""Main CGI script for web interface"""
+
+import base64
+import cPickle
+import cgi
+import datetime
+import hmac
+import random
+import sha
+import simplejson
+import sys
+import time
+import urllib
+from StringIO import StringIO
+
+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 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 templates
+from Cheetah.Template import Template
+import validation
+import cache_acls
+from webcommon import InvalidInput, CodeError, 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
+
+def pathSplit(path):
+    if path.startswith('/'):
+        path = path[1:]
+    i = path.find('/')
+    if i == -1:
+        i = len(path)
+    return path[:i], path[i:]
+
+class Checkpoint:
+    def __init__(self):
+        self.start_time = time.time()
+        self.checkpoints = []
+
+    def checkpoint(self, s):
+        self.checkpoints.append((s, time.time()))
+
+    def __str__(self):
+        return ('Timing info:\n%s\n' %
+                '\n'.join(['%s: %s' % (d, t - self.start_time) for
+                           (d, t) in self.checkpoints]))
+
+checkpoint = Checkpoint()
+
+def jquote(string):
+    return "'" + string.replace('\\', '\\\\').replace("'", "\\'").replace('\n', '\\n') + "'"
+
+def helppopup(subj):
+    """Return HTML code for a (?) link to a specified help topic"""
+    return ('<span class="helplink"><a href="help?' +
+            cgi.escape(urllib.urlencode(dict(subject=subj, simple='true')))
+            +'" target="_blank" ' +
+            'onclick="return helppopup(' + cgi.escape(jquote(subj)) + ')">(?)</a></span>')
+
+def makeErrorPre(old, addition):
+    if addition is None:
+        return
+    if old:
+        return old[:-6]  + '\n----\n' + str(addition) + '</pre>'
+    else:
+        return '<p>STDERR:</p><pre>' + str(addition) + '</pre>'
+
+Template.database = database
+Template.config = config
+Template.helppopup = staticmethod(helppopup)
+Template.err = None
+
+class JsonDict:
+    """Class to store a dictionary that will be converted to JSON"""
+    def __init__(self, **kws):
+        self.data = kws
+        if 'err' in kws:
+            err = kws['err']
+            del kws['err']
+            self.addError(err)
+
+    def __str__(self):
+        return simplejson.dumps(self.data)
+
+    def addError(self, text):
+        """Add stderr text to be displayed on the website."""
+        self.data['err'] = \
+            makeErrorPre(self.data.get('err'), text)
+
+class Defaults:
+    """Class to store default values for fields."""
+    memory = 256
+    disk = 4.0
+    cdrom = ''
+    autoinstall = ''
+    name = ''
+    description = ''
+    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.max_disk = min(self.disk, max_disk)
+        for key in kws:
+            setattr(self, key, kws[key])
+
+
+
+DEFAULT_HEADERS = {'Content-Type': 'text/html'}
+
+def invalidInput(op, username, fields, err, emsg):
+    """Print an error page when an InvalidInput exception occurs"""
+    d = dict(op=op, user=username, err_field=err.err_field,
+             err_value=str(err.err_value), stderr=emsg,
+             errorMessage=str(err))
+    return templates.invalid(searchList=[d])
+
+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 parseCreate(username, state, fields):
+    kws = dict([(kw, fields.getfirst(kw)) for kw in 'name description owner memory disksize vmtype cdrom autoinstall'.split()])
+    validate = validation.Validate(username, state, strict=True, **kws)
+    return dict(contact=username, name=validate.name, description=validate.description, memory=validate.memory,
+                disksize=validate.disksize, owner=validate.owner, machine_type=validate.vmtype,
+                cdrom=getattr(validate, 'cdrom', None),
+                autoinstall=getattr(validate, 'autoinstall', None))
+
+def create(username, state, path, fields):
+    """Handler for create requests."""
+    try:
+        parsed_fields = parseCreate(username, state, fields)
+        machine = controls.createVm(username, state, **parsed_fields)
+    except InvalidInput, err:
+        pass
+    else:
+        err = None
+    state.clear() #Changed global state
+    d = getListDict(username, state)
+    d['err'] = err
+    if err:
+        for field in fields.keys():
+            setattr(d['defaults'], field, fields.getfirst(field))
+    else:
+        d['new_machine'] = parsed_fields['name']
+    return templates.list(searchList=[d])
+
+
+def getListDict(username, state):
+    """Gets the list of local variables used by list.tmpl."""
+    checkpoint.checkpoint('Starting')
+    machines = state.machines
+    checkpoint.checkpoint('Got my machines')
+    on = {}
+    has_vnc = {}
+    xmlist = state.xmlist
+    checkpoint.checkpoint('Got uptimes')
+    can_clone = 'ice3' not in state.xmlist_raw
+    for m in machines:
+        if m not in xmlist:
+            has_vnc[m] = 'Off'
+            m.uptime = None
+        else:
+            m.uptime = xmlist[m]['uptime']
+            if xmlist[m]['console']:
+                has_vnc[m] = True
+            elif m.type.hvm:
+                has_vnc[m] = "WTF?"
+            else:
+                has_vnc[m] = "ParaVM"+helppopup("ParaVM Console")
+    max_memory = validation.maxMemory(username, state)
+    max_disk = validation.maxDisk(username)
+    checkpoint.checkpoint('Got max mem/disk')
+    defaults = Defaults(max_memory=max_memory,
+                        max_disk=max_disk,
+                        owner=username,
+                        cdrom='gutsy-i386')
+    checkpoint.checkpoint('Got defaults')
+    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,
+             can_clone=can_clone)
+    return d
+
+def listVms(username, state, path, fields):
+    """Handler for list requests."""
+    checkpoint.checkpoint('Getting list dict')
+    d = getListDict(username, state)
+    checkpoint.checkpoint('Got list dict')
+    return templates.list(searchList=[d])
+
+def vnc(username, state, path, fields):
+    """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(username, state, machine_id=fields.getfirst('machine_id')).machine
+
+    TOKEN_KEY = "0M6W0U1IXexThi5idy8mnkqPKEq1LtEnlK/pZSn0cDrN"
+
+    data = {}
+    data["user"] = username
+    data["machine"] = machine.name
+    data["expires"] = time.time()+(5*60)
+    pickled_data = cPickle.dumps(data)
+    m = hmac.new(TOKEN_KEY, digestmod=sha)
+    m.update(pickled_data)
+    token = {'data': pickled_data, 'digest': m.digest()}
+    token = cPickle.dumps(token)
+    token = base64.urlsafe_b64encode(token)
+    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(user=username,
+             on=status,
+             has_vnc=has_vnc,
+             machine=machine,
+             hostname=state.environ.get('SERVER_NAME', 'localhost'),
+             port=port,
+             authtoken=token)
+    return templates.vnc(searchList=[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 and '.' in nic.hostname:
+        return nic.hostname
+    elif nic.machine:
+        return nic.machine.name + '.' + config.dns.domains[0]
+    else:
+        return None
+
+
+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])
+        if not i:
+            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 command(username, state, path, fields):
+    """Handler for running commands like boot and delete on a VM."""
+    back = fields.getfirst('back')
+    try:
+        d = controls.commandResult(username, state, fields)
+        if d['command'] == 'Delete VM':
+            back = 'list'
+    except InvalidInput, err:
+        if not back:
+            raise
+        print >> sys.stderr, err
+        result = err
+    else:
+        result = 'Success!'
+        if not back:
+            return templates.command(searchList=[d])
+    if back == 'list':
+        state.clear() #Changed global state
+        d = getListDict(username, state)
+        d['result'] = result
+        return templates.list(searchList=[d])
+    elif back == 'info':
+        machine = validation.Validate(username, state, machine_id=fields.getfirst('machine_id')).machine
+        return ({'Status': '303 See Other',
+                 'Location': 'info?machine_id=%d' % machine.machine_id},
+                "You shouldn't see this message.")
+    else:
+        raise InvalidInput('back', back, 'Not a known back page.')
+
+def modifyDict(username, state, fields):
+    """Modify a machine as specified by CGI arguments.
+
+    Return a list of local variables for modify.tmpl.
+    """
+    olddisk = {}
+    session.begin()
+    try:
+        kws = dict([(kw, fields.getfirst(kw)) for kw in 'machine_id owner admin contact name description memory vmtype disksize'.split()])
+        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
+        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:
+            print >> sys.stderr, machine, machine.administrator
+            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(user=username,
+                command="modify",
+                machine=machine)
+
+def modify(username, state, path, fields):
+    """Handler for modifying attributes of a machine."""
+    try:
+        modify_dict = modifyDict(username, state, fields)
+    except InvalidInput, err:
+        result = None
+        machine = validation.Validate(username, state, machine_id=fields.getfirst('machine_id')).machine
+    else:
+        machine = modify_dict['machine']
+        result = 'Success!'
+        err = None
+    info_dict = infoDict(username, state, machine)
+    info_dict['err'] = err
+    if err:
+        for field in fields.keys():
+            setattr(info_dict['defaults'], field, fields.getfirst(field))
+    info_dict['result'] = result
+    return templates.info(searchList=[info_dict])
+
+
+def helpHandler(username, state, path, fields):
+    """Handler for help messages."""
+    simple = fields.getfirst('simple')
+    subjects = fields.getlist('subject')
+
+    help_mapping = {'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 console.%s, using the name of the machine as your
+username.""" % config.dns.domains[0],
+                    'HVM/ParaVM': """
+HVM machines use the virtualization features of the processor, while
+ParaVM machines use Xen's emulation of virtualization features.  You
+want an HVM virtualized machine.""",
+                    '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 megabytes of active ram, 50 gigabytes 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 req	uires 512 MB RAM and at least 7.5 GB disk space (15 GB 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.
+"""
+                    }
+
+    if not subjects:
+        subjects = sorted(help_mapping.keys())
+
+    d = dict(user=username,
+             simple=simple,
+             subjects=subjects,
+             mapping=help_mapping)
+
+    return templates.help(searchList=[d])
+
+
+def badOperation(u, s, p, e):
+    """Function called when accessing an unknown URI."""
+    return ({'Status': '404 Not Found'}, 'Invalid operation.')
+
+def infoDict(username, state, machine):
+    """Get the variables used by info.tmpl."""
+    status = controls.statusInfo(machine)
+    checkpoint.checkpoint('Getting status info')
+    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))
+    checkpoint.checkpoint('Status')
+    display_fields = """name uptime memory state cpu_weight on_reboot 
+     on_poweroff on_crash on_xend_start on_xend_stop bootloader""".split()
+    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)'),
+                      ('cpu_weight', 'CPU weight'+helppopup('CPU Weight')),
+                      ('on_reboot', 'Action on VM reboot'),
+                      ('on_poweroff', 'Action on VM poweroff'),
+                      ('on_crash', 'Action on VM crash'),
+                      ('on_xend_start', 'Action on Xen start'),
+                      ('on_xend_stop', 'Action on Xen stop'),
+                      ('bootloader', 'Bootloader options'),
+                      ]
+    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))
+
+    checkpoint.checkpoint('Got fields')
+
+
+    max_mem = validation.maxMemory(machine.owner, state, machine, False)
+    checkpoint.checkpoint('Got mem')
+    max_disk = validation.maxDisk(machine.owner, machine)
+    defaults = Defaults()
+    for name in 'machine_id name description administrator owner memory contact'.split():
+        setattr(defaults, name, getattr(machine, name))
+    defaults.type = machine.type.type_id
+    defaults.disk = "%0.2f" % (machine.disks[0].size/1024.)
+    checkpoint.checkpoint('Got defaults')
+    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,
+             owner_help=helppopup("Owner"),
+             fields = fields)
+    return d
+
+def info(username, state, path, fields):
+    """Handler for info on a single VM."""
+    machine = validation.Validate(username, state, machine_id=fields.getfirst('machine_id')).machine
+    d = infoDict(username, state, machine)
+    checkpoint.checkpoint('Got infodict')
+    return templates.info(searchList=[d])
+
+def unauthFront(_, _2, _3, fields):
+    """Information for unauth'd users."""
+    return templates.unauth(searchList=[{'simple' : True}])
+
+def admin(username, state, path, fields):
+    if path == '':
+        return ({'Status': '303 See Other',
+                 'Location': 'admin/'},
+                "You shouldn't see this message.")
+    if not username in getAfsGroupMembers(config.web.adminacl, 'athena.mit.edu'):
+        raise InvalidInput('username', username,
+                           'Not in admin group %s.' % config.web.adminacl)
+    newstate = State(username, isadmin=True)
+    newstate.environ = state.environ
+    return handler(username, newstate, path, fields)
+
+def throwError(_, __, ___, ____):
+    """Throw an error, to test the error-tracing mechanisms."""
+    raise RuntimeError("test of the emergency broadcast system")
+
+mapping = dict(list=listVms,
+               vnc=vnc,
+               command=command,
+               modify=modify,
+               info=info,
+               create=create,
+               help=helpHandler,
+               unauth=unauthFront,
+               admin=admin,
+               overlord=admin,
+               errortest=throwError)
+
+def printHeaders(headers):
+    """Print a dictionary as HTTP headers."""
+    for key, value in headers.iteritems():
+        print '%s: %s' % (key, value)
+    print
+
+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', to], stdin=subprocess.PIPE)
+    p.stdin.write(mail)
+    p.stdin.close()
+    p.wait()
+
+def show_error(op, username, fields, err, emsg, traceback):
+    """Print an error page when an exception occurs"""
+    d = dict(op=op, user=username, fields=fields,
+             errorMessage=str(err), stderr=emsg, traceback=traceback)
+    details = templates.error_raw(searchList=[d])
+    if False: #username not in config.web.errormail_exclude:
+        send_error_mail('xvm error on %s for %s: %s' % (op, username, err),
+                        details)
+    d['details'] = details
+    return templates.error(searchList=[d])
+
+def getUser(environ):
+    """Return the current user based on the SSL environment variables"""
+    return environ.get('REMOTE_USER', None)
+
+def handler(username, state, path, fields):
+    operation, path = pathSplit(path)
+    if not operation:
+        operation = 'list'
+    print 'Starting', operation
+    fun = mapping.get(operation, badOperation)
+    return fun(username, state, path, fields)
+
+class App:
+    def __init__(self, environ, start_response):
+        self.environ = environ
+        self.start = start_response
+
+        self.username = getUser(environ)
+        self.state = State(self.username)
+        self.state.environ = environ
+
+        random.seed() #sigh
+
+    def __iter__(self):
+        start_time = time.time()
+        database.clear_cache()
+        sys.stderr = StringIO()
+        fields = cgi.FieldStorage(fp=self.environ['wsgi.input'], environ=self.environ)
+        operation = self.environ.get('PATH_INFO', '')
+        if not operation:
+            self.start("301 Moved Permanently", [('Location', './')])
+            return
+        if self.username is None:
+            operation = 'unauth'
+
+        try:
+            checkpoint.checkpoint('Before')
+            output = handler(self.username, self.state, operation, fields)
+            checkpoint.checkpoint('After')
+
+            headers = dict(DEFAULT_HEADERS)
+            if isinstance(output, tuple):
+                new_headers, output = output
+                headers.update(new_headers)
+            e = revertStandardError()
+            if e:
+                if hasattr(output, 'addError'):
+                    output.addError(e)
+                else:
+                    # This only happens on redirects, so it'd be a pain to get
+                    # the message to the user.  Maybe in the response is useful.
+                    output = output + '\n\nstderr:\n' + e
+            output_string =  str(output)
+            checkpoint.checkpoint('output as a string')
+        except Exception, err:
+            if not fields.has_key('js'):
+                if isinstance(err, InvalidInput):
+                    self.start('200 OK', [('Content-Type', 'text/html')])
+                    e = revertStandardError()
+                    yield str(invalidInput(operation, self.username, fields,
+                                           err, e))
+                    return
+            import traceback
+            self.start('500 Internal Server Error',
+                       [('Content-Type', 'text/html')])
+            e = revertStandardError()
+            s = show_error(operation, self.username, fields,
+                           err, e, traceback.format_exc())
+            yield str(s)
+            return
+        status = headers.setdefault('Status', '200 OK')
+        del headers['Status']
+        self.start(status, headers.items())
+        yield output_string
+        if fields.has_key('timedebug'):
+            yield '<pre>%s</pre>' % cgi.escape(str(checkpoint))
+
+def constructor():
+    connect()
+    return App
+
+def main():
+    from flup.server.fcgi_fork import WSGIServer
+    WSGIServer(constructor()).run()
+
+if __name__ == '__main__':
+    main()
Index: /package_tags/sipb-xen-www/3.12/code/static/VncViewer.jar
===================================================================
--- /package_tags/sipb-xen-www/3.12/code/static/VncViewer.jar	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/code/static/VncViewer.jar	(revision 1024)
@@ -0,0 +1,1 @@
+link /usr/local/lib/sipb-xen-vnc-client/VncViewer.jar
Index: /package_tags/sipb-xen-www/3.12/code/static/about.html
===================================================================
--- /package_tags/sipb-xen-www/3.12/code/static/about.html	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/code/static/about.html	(revision 1024)
@@ -0,0 +1,32 @@
+<!DOCTYPE html
+PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html>
+<head><title>About SIPB Virtual Servers</title>
+  <link href="favicon.ico" type="image/x-icon" rel="shortcut icon">
+  <link rel="stylesheet" href="style.css" type="text/css" />
+  <link rel="stylesheet" href="layout.css" type="text/css" media="screen" />
+  <script type="text/javascript" src="prototype.js"></script>
+</head>
+<body id="body">
+
+<h1>About SIPB Virtual Servers</h1>
+
+SIPB Virtual Servers is an experimental service from the <a href="http://sipb.mit.edu/">Student Information Processing Board</a> which attempts to provide members of the MIT community with an easy way to create virtual machines which they can remotely administer.
+
+<h2>SIPB Virtual Servers is an Alpha Service</h2>
+
+Lots of services claim to be beta when they're really almost release-worthy. SIPB Virtual Servers is an alpha service in the true sense of the word. This means that we make almost no promises. Specifically, we make <strong>no promises</strong> about:
+
+<ul>
+<li><strong>Security</strong>: All of the current developers of SIPB Virtual Servers have root access to black-mesa, the host machine for all of the virtual machines, through both root and null instances.</li>
+<li><strong>Uptime</strong>: The SIPB Virtual Servers developers reserve the right to bring down both black-mesa and its VMs without warning or notification.</li>
+<li><strong>Data integrity</strong>: We do not back up data on SIPB Virtual Servers VMs.</li>
+</ul>
+
+<p>If you're OK with this, we hope you enjoy using and helping us test <a href="/">SIPB Virtual Servers</a>.</p>
+
+<hr />
+Questions? Contact <a href="mailto:xvm@mit.edu">xvm@mit.edu</a>.
+</body>
+</html>
Index: /package_tags/sipb-xen-www/3.12/code/static/layout.css
===================================================================
--- /package_tags/sipb-xen-www/3.12/code/static/layout.css	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/code/static/layout.css	(revision 1024)
@@ -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/sipb-xen-www/3.12/code/static/msca-email.txt
===================================================================
--- /package_tags/sipb-xen-www/3.12/code/static/msca-email.txt	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/code/static/msca-email.txt	(revision 1024)
@@ -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/sipb-xen-www/3.12/code/static/prototype.js
===================================================================
--- /package_tags/sipb-xen-www/3.12/code/static/prototype.js	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/code/static/prototype.js	(revision 1024)
@@ -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/sipb-xen-www/3.12/code/static/stripe.js
===================================================================
--- /package_tags/sipb-xen-www/3.12/code/static/stripe.js	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/code/static/stripe.js	(revision 1024)
@@ -0,0 +1,18 @@
+/*
+ * The general idea is from the following A List Apart article:
+ * http://www.alistapart.com/articles/zebratables/
+ *
+ * The structure is inspired by the code fragment they supply, but the
+ * code here is significantly cleaner. It also colors every two lines
+ * rather than every line, since XVM uses two rows for each item.
+ */
+
+function stripe(table, darkClass, lightClass) {
+    for (var i = 0; i < table.rows.length; i++ ) {
+        /* The header row should be light; the next two are dark. */
+        if (i%4 == 1 || i%4 == 2)
+            table.rows[i].className += ' ' + darkClass;
+        else if (lightClass)
+            table.rows[i].className += ' ' + lightClass;
+    }
+}
Index: /package_tags/sipb-xen-www/3.12/code/static/style.css
===================================================================
--- /package_tags/sipb-xen-www/3.12/code/static/style.css	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/code/static/style.css	(revision 1024)
@@ -0,0 +1,106 @@
+/*
+  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;
+}
Index: /package_tags/sipb-xen-www/3.12/code/templates/Makefile
===================================================================
--- /package_tags/sipb-xen-www/3.12/code/templates/Makefile	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/code/templates/Makefile	(revision 1024)
@@ -0,0 +1,13 @@
+TEMPLATES=$(wildcard *.tmpl)
+OUTPUTS=$(TEMPLATES:.tmpl=.py)
+
+all: ${OUTPUTS}
+
+%.py: %.tmpl
+	cheetah compile $<
+
+#${OUTPUTS}:${TEMPLATES}
+#	cheetah compile $^
+
+clean:
+	@rm -f ${OUTPUTS} *.pyo *.pyc *.py.bak
Index: /package_tags/sipb-xen-www/3.12/code/templates/__init__.py
===================================================================
--- /package_tags/sipb-xen-www/3.12/code/templates/__init__.py	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/code/templates/__init__.py	(revision 1024)
@@ -0,0 +1,9 @@
+__all__ = 'info command error error_raw help invalid list unauth vnc'.split()
+for _name in __all__:
+    try:
+        _module = __import__(_name, globals(), {}, [_name])
+        globals()[_name] = getattr(_module, _name)
+    except ImportError, e:
+        import sys
+        print >> sys.stderr, 'Importing template "%s" raised error: %s' % (_name, e)
+        
Index: /package_tags/sipb-xen-www/3.12/code/templates/command.tmpl
===================================================================
--- /package_tags/sipb-xen-www/3.12/code/templates/command.tmpl	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/code/templates/command.tmpl	(revision 1024)
@@ -0,0 +1,16 @@
+#from skeleton import skeleton
+#extends skeleton
+
+#def title
+$command $machine.name
+#end def
+
+
+#def body
+<p>$command ${machine.name} was successful.</p>
+#if $command == "Delete VM" or True
+<p><a href="list">Return</a></p>
+#else
+<p><a href="info?machine_id=${machine.machine_id}">Return</a></p>
+#end if
+#end def
Index: /package_tags/sipb-xen-www/3.12/code/templates/create.tmpl
===================================================================
--- /package_tags/sipb-xen-www/3.12/code/templates/create.tmpl	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/code/templates/create.tmpl	(revision 1024)
@@ -0,0 +1,15 @@
+#from skeleton import skeleton
+#extends skeleton
+
+#def title
+Created!
+#end def
+
+#def body
+#if $machine
+<p>Congratulations!  You have a new machine named ${machine.name}.</p>
+#else
+<p>Odd... no error, but no machine.</p>
+#end if
+<p><a href="list">Return</a></p>
+#end def
Index: /package_tags/sipb-xen-www/3.12/code/templates/error.tmpl
===================================================================
--- /package_tags/sipb-xen-www/3.12/code/templates/error.tmpl	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/code/templates/error.tmpl	(revision 1024)
@@ -0,0 +1,20 @@
+#from skeleton import skeleton
+#extends skeleton
+
+#def title
+ERROR!
+#end def
+
+#def body
+<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>xvm@mit.edu</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>
+#end def
Index: /package_tags/sipb-xen-www/3.12/code/templates/error_raw.tmpl
===================================================================
--- /package_tags/sipb-xen-www/3.12/code/templates/error_raw.tmpl	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/code/templates/error_raw.tmpl	(revision 1024)
@@ -0,0 +1,12 @@
+Error on operation $op for user $user: $errorMessage
+
+Fields:
+#for $f in $fields:
+$f=$fields[$f].value
+#end for
+
+Error output:
+$stderr#slurp
+---- end error output
+
+$traceback
Index: /package_tags/sipb-xen-www/3.12/code/templates/functions.tmpl
===================================================================
--- /package_tags/sipb-xen-www/3.12/code/templates/functions.tmpl	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/code/templates/functions.tmpl	(revision 1024)
@@ -0,0 +1,63 @@
+#filter WebSafe
+#def databaseList($lst, $default, $onchange, $name, $id, $valueattr, $descattr)
+<select name="$name" id="$id"#slurp
+#if $onchange is not None
+onchange="$onchange"#slurp
+#end if
+>
+  <option #slurp
+#if $default then '' else 'selected'
+ value="">None</option>
+  #for $item in $lst
+  <option #slurp
+#if $default == getattr(item, valueattr) then 'selected' else ''
+ value="${getattr(item, valueattr)}">
+    ${getattr(item, descattr)}
+  </option>
+  #end for
+</select>
+#end def
+
+#def cdromList($default="", $onchange=None)
+#filter None
+$databaseList(sorted($database.CDROM.query(), key=lambda x: x.description),
+              default, onchange, 'cdrom', 'cdromlist', 'cdrom_id', 'description')
+#end filter
+#end def
+
+#def autoList($default="", $onchange=None)
+#filter None
+$databaseList(sorted($database.Autoinstall.query(), key=lambda x: x.description),
+              default, onchange, 'autoinstall', 'autoinstalllist', 'autoinstall_id', 'description')
+#end filter
+#end def
+
+#def vmTypeList($default=None)
+#for $vmtype in (('linux-hvm', 'HVM'), ('linux', 'ParaVM'), )
+<label>
+   <input #slurp
+#if $default == $vmtype[0] then 'checked' else ''
+ type="radio" name="vmtype" value="${vmtype[0]}">${vmtype[1]}</input>
+</label>
+#end for
+#end def
+
+#def addError(txt)
+#if $varExists('txt')
+#set global $error_text = $error_text + '----\n' + $txt
+#else
+#set global $error_text = $txt
+#end if
+#end def
+
+#def errorRow($value, $err)
+#if $err and $err.err_field == $value
+<tr>
+<td class="error" colspan="2">${str($err)}</td>
+</tr>
+#end if
+#end def
+#filter None
+$full_body
+#end filter
+#end filter
Index: /package_tags/sipb-xen-www/3.12/code/templates/help.tmpl
===================================================================
--- /package_tags/sipb-xen-www/3.12/code/templates/help.tmpl	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/code/templates/help.tmpl	(revision 1024)
@@ -0,0 +1,39 @@
+#from skeleton import skeleton
+#extends skeleton
+
+#attr pageclass = 'help'
+
+#def title
+#if len($subjects) == 1
+Help on $subjects[0]
+#else
+Help
+#end if
+#end def
+
+
+#def body
+#if not $simple
+<p>Topics: 
+#for $key in sorted($mapping)
+<a href="help?subject=$key">$key</a>
+#end for
+</p>
+<p>
+See also <a href="trac/wiki/tips">tips and HOWTOs on the wiki</a>.
+</p>
+#end if
+#for $subject in $subjects
+#if $subject in $mapping 
+<h2>$subject</h2>
+#filter None
+<p>$mapping[$subject]</p>
+#end filter
+#else
+<p>Unknown subject '$subject'.</p>
+#end if
+#end for
+#if $simple
+<a href="javascript:window.close();">Close</a>
+#end if
+#end def
Index: /package_tags/sipb-xen-www/3.12/code/templates/info.tmpl
===================================================================
--- /package_tags/sipb-xen-www/3.12/code/templates/info.tmpl	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/code/templates/info.tmpl	(revision 1024)
@@ -0,0 +1,145 @@
+#from skeleton import skeleton
+#extends skeleton
+
+#def title
+Info on $machine.name
+#end def
+
+#def infoTable()
+<h2>Info</h2>
+<table>
+  #for $key, $value in $fields
+  <tr><td>$key:</td><td>$value</td></tr>
+  #end for
+</table>
+#end def
+
+#def commands()
+<form action="command" method="POST">
+  <input type="hidden" name="back" value="info"/>
+  <input type="hidden" name="machine_id" value="$machine.machine_id"/>
+  <table>
+    
+    <tr><td colspan=3>
+	#if $on
+	#if $has_vnc
+	<strong><a href="vnc?machine_id=$machine.machine_id">Get Console</a></strong>
+	#else
+	VNC console not enabled; still booting?
+	#end if
+	#else
+
+	#end if
+    </td></tr>
+      <tr>
+	#if $on
+	<td><button type="submit" class="button" name="action" value="Power off">Power off (hard)</button></td>
+	<td><button type="submit" class="button" name="action" value="Shutdown">Shut down</button></td>
+	<td><input type="submit" class="button" name="action" value="Reboot"/></td>
+	#else
+	<td><input type="submit" class="button" name="action" value="Power on"/></td>
+	#end if
+      <td>Boot CD:</td>
+      <td>#slurp
+#filter None
+$cdromList()#slurp
+#end filter
+</td>
+  </tr>
+    <tr>
+      <td><input type="submit" class="button" name="action" value="Delete VM" onclick="return confirm('Are you sure that you want to delete this VM?');"/></td>
+    </tr>
+  </table>
+</form>
+#end def
+
+#def modifyForm()
+#if $err
+<p class="error">We had a problem with your request:</p>
+#else if $varExists('new_machine')
+<p>Successfully modified.</p>
+#end if
+#if $on
+(To edit ram, disk size, or machine name, turn off the machine first.)
+#end if
+<form action="modify" method="POST">
+  <input type="hidden" name="machine_id" value="$defaults.machine_id"/>
+  <table>
+    <tr><td>Description:</td><td colspan="2"><textarea name="description" rows="4" cols="60">$defaults.description</textarea></td></tr>
+    <tr><td>Owner#slurp
+#filter None
+$helppopup("Owner")#slurp
+#end filter
+:</td><td><input type="text" name="owner", value="$defaults.owner"/></td></tr>
+#filter None
+$errorRow('owner', $err)
+#end filter
+    <tr><td>Administrator#slurp
+#filter None
+$helppopup("Administrator")#slurp
+#end filter
+:</td><td><input type="text" name="admin", value="$defaults.administrator"/></td></tr>
+#filter None
+$errorRow('administrator', $err)
+#end filter
+    <tr><td>Contact email:</td><td><input type="text" name="contact" value="$defaults.contact"/></td></tr>
+#filter None
+$errorRow('contact', $err)
+#end filter
+#if not $on
+    <tr><td>Machine Name:</td><td><input type="text" name="name" value="$defaults.name"/>.${config.dns.domains[0]}</td></tr>
+#filter None
+$errorRow('name', $err)
+#end filter
+    <tr>
+      <td>HVM/ParaVM#slurp
+#filter None
+$helppopup('HVM/ParaVM')#slurp
+#end filter
+</td>
+      <td>#slurp
+#filter None
+$vmTypeList($defaults.type)#slurp
+#end filter
+</td>
+    </tr>
+    <tr><td>Ram:</td><td><input type="text" size=3 name="memory" value="$defaults.memory"/>MiB (max $max_mem)</td></tr>
+#filter None
+$errorRow('memory', $err)
+#end filter
+    <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>
+#filter None
+$errorRow('disk', $err)
+#end filter
+#else
+#filter None
+$errorRow('name', $err)
+$errorRow('memory', $err)
+$errorRow('disk', $err)
+#end filter
+#end if
+    <tr><td><input type="submit" class="button" name="action" value="Change"/></td></tr>
+  </table>
+</form>
+#end def
+
+#def body
+<div id="info">
+#filter None
+  $infoTable()
+#end filter
+</div>
+
+<h2>Commands</h2>
+<div id="commands">
+#filter None
+  $commands()
+#end filter
+</div>
+<h2>Settings</h2>
+<div id="modify">
+#filter None
+  $modifyForm()
+#end filter
+</div>
+#end def
Index: /package_tags/sipb-xen-www/3.12/code/templates/invalid.tmpl
===================================================================
--- /package_tags/sipb-xen-www/3.12/code/templates/invalid.tmpl	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/code/templates/invalid.tmpl	(revision 1024)
@@ -0,0 +1,18 @@
+#from skeleton import skeleton
+#extends skeleton
+
+#def title
+Invalid Input
+#end def
+
+#def body
+<p>Your input was bad:</p>
+<table>
+<tr><td>operation</td><td>Field</td><td>value</td><td>reason</td></tr>
+<tr><td>$op</td><td>$err_field</td><td>$err_value</td><td>$errorMessage</td></tr>
+#if $stderr
+<p>Printed to standard error:</p>
+<pre>$stderr</pre>
+#end if
+</table>
+#end def
Index: /package_tags/sipb-xen-www/3.12/code/templates/list.tmpl
===================================================================
--- /package_tags/sipb-xen-www/3.12/code/templates/list.tmpl	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/code/templates/list.tmpl	(revision 1024)
@@ -0,0 +1,207 @@
+#from skeleton import skeleton
+#extends skeleton
+#import datetime
+
+
+#def title
+VM List
+#end def
+
+#def 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>
+#else if $varExists('new_machine')
+<p>Congratulations! You successfully created a new VM called $new_machine.</p>
+#end if
+    <form action="create" method="POST">
+    <input type="hidden" name="back" value="list"/>
+      <table>
+#filter None
+      $errorRow('create', $err)
+#end filter
+	<tr>
+	  <td>Name</td>
+	  <td><input type="text" name="name" value="$defaults.name"/>.${config.dns.domains[0]}</td>
+	</tr>
+#filter None
+$errorRow('name', $err)
+#end filter
+	<tr>
+	  <td>Description</td>
+	  <td><textarea name="description" rows="4" cols="60">$defaults.description</textarea></td>
+	</tr>
+#filter None
+$errorRow('description', $err)
+#end filter
+	<tr>
+	  <td>Memory</td>
+	  <td><input type="text" name="memory" value="$defaults.memory" size=3/> MiB ($max_memory max)</td>
+	</tr>
+#filter None
+$errorRow('memory', $err)
+#end filter
+	<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>
+#filter None
+$errorRow('disk', $err)
+#end filter
+        <tr>
+          <td>HVM/ParaVM#slurp
+#filter None
+$helppopup('HVM/ParaVM')#slurp
+#end filter
+</td>
+          <td>
+#filter None
+$vmTypeList($defaults.type)
+#end filter
+</td>
+        </tr>
+#filter None
+$errorRow('vmtype', $err)
+#end filter
+#filter None
+$errorRow('autoinstall', $err)
+#end filter
+	<tr>
+	  <td>Autoinstall#slurp
+#filter None
+$helppopup('Autoinstall')#slurp
+#end filter
+</td>
+	  <td><input type="radio" name="cd_or_auto" id="cd_or_auto_auto">
+#filter None
+$autoList($defaults.cdrom, "document.getElementById('cd_or_auto_auto').checked = true;document.getElementById('cdromlist').value = ''")
+	      (experimental; 1-2 minutes, and you have a machine with empty root password.)
+#end filter
+	  </input>
+	</tr>
+	<tr>
+	  <td>Boot CD</td>
+	  <td><input type="radio" name="cd_or_auto" id="cd_or_auto_cd" checked>
+#filter None
+$cdromList($defaults.cdrom, "document.getElementById('cd_or_auto_cd').checked = true;document.getElementById('autoinstalllist').value = ''")
+#end filter
+</td>
+	  </input>
+	</tr>
+$errorRow('cdrom', $err)
+$errorRow('cdrom', $err)
+	<tr>
+	  <td>Owner</td>
+	  <td><input type="text" name="owner" value="$defaults.owner"/></td>
+	</tr>
+#filter None
+	$errorRow('owner', $err)
+#end filter
+      </table>
+      <input type="submit" class="button" value="Create it!"/><br />
+      Windows notes: #slurp
+#filter None
+$helppopup('Windows')#slurp
+#end filter
+    </form>
+#end if
+#end def
+
+#def machineRow($machine)
+      <tr> 
+	<td rowspan="2">
+	  <form action="command" method="post">
+	    <input type="hidden" name="back" value="list"/>
+	    <input type="hidden" name="machine_id"
+		   value="$machine.machine_id"/>
+<input type="submit" class="power #slurp
+#if $machine.uptime then 'on' else 'off'
+" name="action" value="#slurp
+#if $machine.uptime then 'Power off' else 'Power on'
+"/>
+	  </form>
+	</td>
+	<td><a href="info?machine_id=$machine.machine_id">$machine.name</a></td>
+	<td>${machine.memory}M</td>
+	<td>$machine.owner</td>
+	<td>$machine.administrator</td>
+#if $machine.nics
+#set $nic = $machine.nics[0]
+	<td>$nic.ip</td>
+#else
+	<td></td>
+#end if
+<td>#slurp
+#if $machine.uptime
+${datetime.timedelta(seconds=int(machine.uptime))}#slurp
+#end if
+</td>
+	<td>#slurp
+#if $has_vnc[$machine] == True
+<a href="vnc?machine_id=$machine.machine_id">Console</a>#slurp
+#else if $has_vnc[$machine] != 'Off'
+#filter None
+$has_vnc[$machine]
+#end filter
+#end if
+</td>
+      </tr>
+      <tr>
+        <td colspan="7" style="padding-left: 1em; color: #666">$machine.description</td>
+      </tr>
+#end def
+
+#def machineList($machines)
+    <table cellspacing="0" cellpadding="2">
+      <tr>
+	<th></th>
+	<th>Name</th>
+	<th>Memory</th>
+	<th>Owner#slurp
+#filter None
+$helppopup('Owner')#slurp
+#end filter
+</th>
+        <th>Administrator#slurp
+#filter None
+$helppopup('Administrator')#slurp
+#end filter
+</th>
+	<th>IP</th>
+	<th>Uptime</th>
+	<th>VNC</th>
+      </tr>
+      #for $machine in $machines:
+    #filter None
+	$machineRow($machine)
+    #end filter
+      #end for
+    </table>
+    <script type="text/javascript" src="/static/stripe.js"></script>
+    <script type="text/javascript">
+        document.observe("dom:loaded", function() {
+            stripe(\$('machinelist').getElementsByTagName('table')[0],
+                   'stripedrow');
+        });
+    </script>
+#end def
+
+
+#def body
+<p style="font-size: 125%;">SIPB Virtual Servers is an <strong>alpha service</strong>.  <a href="/static/about.html">What does this mean?</a></p>
+#if not $machines
+<p>You don't currently control any VMs.</p>   
+#end if
+    <p><a href="list">refresh</a></p>
+    <div id="machinelist">
+    #filter None
+    $machineList($machines)
+    #end filter
+    </div>
+#filter None
+$createForm()
+#end filter
+#end def
Index: /package_tags/sipb-xen-www/3.12/code/templates/skeleton.tmpl
===================================================================
--- /package_tags/sipb-xen-www/3.12/code/templates/skeleton.tmpl	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/code/templates/skeleton.tmpl	(revision 1024)
@@ -0,0 +1,80 @@
+#from functions import functions
+#extends functions
+
+#def full_body
+<!DOCTYPE html
+PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html>
+<head><title>$title &mdash; SIPB Virtual Servers</title>
+  <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, 'pageclass'):
+  class="$pageclass"
+#end if
+  >
+
+#if False
+<div>
+<p>We are in the process of modifying the service.  Things likely will not work.</p>
+</div>
+#end if
+
+<div id="err">
+#if $varExists('error_text')
+<p>STDERR:</p><pre>$error_text</pre>
+#end if
+</div>
+
+#if not $varExists('simple') or not $simple
+<p class="loggedin">Welcome, <span class="name">$user</span>.</p>
+
+<ul class="navigation">
+<li><a href="list">List</a></li>
+#if $varExists('machine')
+<li><a href="info?machine_id=$machine.machine_id">Info</a></li>
+<li><a href="vnc?machine_id=$machine.machine_id">Console</a></li>
+#end if
+<li><a href="help">Help</a></li>
+</ul>
+#end if
+<div id="result" class="result">
+#if $varExists('result')
+$result
+#end if
+</div>
+
+#if not $varExists('simple') or not $simple
+<h1>$title &mdash; SIPB Virtual Servers</h1>
+#end if
+#filter None
+$body
+#end filter
+#if not $varExists('simple') or not $simple
+<hr />
+Questions? Contact <a href="mailto:xvm@mit.edu">xvm@mit.edu</a>.
+#end if
+</body>
+</html>
+#end def
Index: /package_tags/sipb-xen-www/3.12/code/templates/unauth.tmpl
===================================================================
--- /package_tags/sipb-xen-www/3.12/code/templates/unauth.tmpl	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/code/templates/unauth.tmpl	(revision 1024)
@@ -0,0 +1,51 @@
+#from skeleton import skeleton
+#extends skeleton
+
+
+#def title
+Intro
+#end def
+
+#def body
+<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>two-minute
+Debian install</strong> or install the <strong>operating system of your
+choice</strong>.  The service is <strong>free</strong> to any Athena
+account holder.</p>
+
+<p>MIT users:</p>
+<blockquote><big><a
+href="https://xvm.mit.edu/"><strong><font color="green">&rarr;</font> Log in to XVM now</strong>
+</a></big></blockquote>
+<p>You'll need an <a href="http://ca.mit.edu/">MIT personal
+certificate</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>A two-minute Debian (Etch) image cloner</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>
+
+<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>
+
+#end def
Index: /package_tags/sipb-xen-www/3.12/code/templates/vnc.tmpl
===================================================================
--- /package_tags/sipb-xen-www/3.12/code/templates/vnc.tmpl	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/code/templates/vnc.tmpl	(revision 1024)
@@ -0,0 +1,25 @@
+#from skeleton import skeleton
+#extends skeleton
+
+#def title
+Console to $machine.name
+#end def
+
+#def body
+<style type='text/css'>body { max-width: none }</style>
+#if not $on
+<p> Your machine appears to be off.</p>
+#else if not $has_vnc
+<p> Your machine appears to not be accepting VNC connections. Perhaps you have a ParaVM machine?</p>
+#end if
+<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="PASSWORD" VALUE="moocow">
+<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>
+#end def
Index: /package_tags/sipb-xen-www/3.12/code/validation.py
===================================================================
--- /package_tags/sipb-xen-www/3.12/code/validation.py	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/code/validation.py	(revision 1024)
@@ -0,0 +1,295 @@
+#!/usr/bin/python
+
+import cache_acls
+import getafsgroups
+import re
+import string
+from invirt.database import Machine, NIC, Type, Disk, CDROM, Autoinstall
+from invirt.config import structs as config
+from webcommon import InvalidInput
+
+MAX_MEMORY_TOTAL = 512
+MAX_MEMORY_SINGLE = 256
+MIN_MEMORY_SINGLE = 16
+MAX_DISK_TOTAL = 50
+MAX_DISK_SINGLE = 50
+MIN_DISK_SINGLE = 0.1
+MAX_VMS_TOTAL = 10
+MAX_VMS_ACTIVE = 4
+
+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
+        admin = testAdmin(username, admin, machine)
+        if admin is not None:
+            self.admin = admin
+        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:
+            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.
+    """
+    if machine is not None and machine.memory > MAX_MEMORY_SINGLE:
+        # If they've been blessed, let them have it
+        return machine.memory
+    if not on:
+        return MAX_MEMORY_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(MAX_MEMORY_SINGLE, MAX_MEMORY_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.
+    """
+    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(MAX_DISK_SINGLE, MAX_DISK_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]
+    if machines.count() >= MAX_VMS_TOTAL:
+        return 'You have too many VMs to create a new one.'
+    if len(active_machines) >= MAX_VMS_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 None
+    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[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 owner == user:
+        return owner
+    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")
+    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 testDisk(user, disksize, machine=None):
+    return disksize
+
+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
+    if not Machine.query().filter_by(name=name).count():
+        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
+    raise InvalidInput('name', name, "Name is already taken.")
+
+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/sipb-xen-www/3.12/code/webcommon.py
===================================================================
--- /package_tags/sipb-xen-www/3.12/code/webcommon.py	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/code/webcommon.py	(revision 1024)
@@ -0,0 +1,65 @@
+"""Exceptions for the web interface."""
+
+import time
+from invirt import database
+from invirt.database import Machine, MachineAccess
+
+class MyException(Exception):
+    """Base class for my exceptions"""
+    pass
+
+class InvalidInput(MyException):
+    """Exception for user-provided input is invalid but maybe in good faith.
+
+    This would include setting memory to negative (which might be a
+    typo) but not setting an invalid boot CD (which requires bypassing
+    the select box).
+    """
+    def __init__(self, err_field, err_value, expl=None):
+        MyException.__init__(self, expl)
+        self.err_field = err_field
+        self.err_value = err_value
+
+class CodeError(MyException):
+    """Exception for internal errors or bad faith input."""
+    pass
+
+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().join('acl').filter_by(
+                database.or_(MachineAccess.c.user == self.username,
+                             Machine.c.adminable == True))
+        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/sipb-xen-www/3.12/code/xen-ips
===================================================================
--- /package_tags/sipb-xen-www/3.12/code/xen-ips	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/code/xen-ips	(revision 1024)
@@ -0,0 +1,52 @@
+#!/usr/bin/python
+import random
+from invirt import database
+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):
+    n = database.NIC(machine_id=None, mac_addr=randomMAC(), ip=ip, hostname=None)
+    database.ctx.current.save(n)
+    database.ctx.current.flush()
+
+
+if __name__ == '__main__':
+    if len(sys.argv) == 2:
+        ip = sys.argv[1]
+    else:
+        usage()
+        sys.exit(1)
+    database.connect()
+    addip(ip)
Index: /package_tags/sipb-xen-www/3.12/config.todo
===================================================================
--- /package_tags/sipb-xen-www/3.12/config.todo	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/config.todo	(revision 1024)
@@ -0,0 +1,22 @@
+# will differ dev/prod
+files/etc/apache2/sites-available/ssl: web hostname
+files/etc/apache2/sites-available/svn: web hostname
+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: SIPB Virtual Servers
+code/templates/skeleton.tmpl: SIPB Virtual Servers (twice)
+code/templates/skeleton.tmpl: xvm@mit.edu
+code/templates/unauth.tmpl: tons of text
+code/templates/unauth.tmpl: https://xvm.mit.edu
+code/static/about.html: tons of text
+code/static/about.html: SIPB Virtual Servers
+
+# 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
Index: /package_tags/sipb-xen-www/3.12/debian/changelog
===================================================================
--- /package_tags/sipb-xen-www/3.12/debian/changelog	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/debian/changelog	(revision 1024)
@@ -0,0 +1,98 @@
+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/sipb-xen-www/3.12/debian/compat
===================================================================
--- /package_tags/sipb-xen-www/3.12/debian/compat	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/debian/compat	(revision 1024)
@@ -0,0 +1,1 @@
+4
Index: /package_tags/sipb-xen-www/3.12/debian/control
===================================================================
--- /package_tags/sipb-xen-www/3.12/debian/control	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/debian/control	(revision 1024)
@@ -0,0 +1,12 @@
+Source: sipb-xen-www
+Section: base
+Priority: extra
+Maintainer: SIPB Xen Project <sipb-xen@mit.edu>
+Build-Depends: cdbs (>= 0.4.23-1.1), debhelper (>= 4.1.0), subversion, sipb-xen-base
+Standards-Version: 3.7.2
+
+Package: sipb-xen-www
+Architecture: all
+Depends: ${misc:Depends}, libapache2-mod-fcgid, python-flup, python-cheetah, python-simplejson, sipb-xen-database-common, sipb-xen-vnc-client, kstart, debathena-afs-config,
+ libapache2-svn, postfix, subversion, zephyr-clients
+Description: Install the sipb-xen-dev website
Index: /package_tags/sipb-xen-www/3.12/debian/copyright
===================================================================
--- /package_tags/sipb-xen-www/3.12/debian/copyright	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/debian/copyright	(revision 1024)
@@ -0,0 +1,3 @@
+This package was created for internal use of the SIPB Xen Project of
+the MIT Student Information Processing Board.  Ask sipb-xen@mit.edu if
+you have questions about redistribution.
Index: /package_tags/sipb-xen-www/3.12/debian/rules
===================================================================
--- /package_tags/sipb-xen-www/3.12/debian/rules	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/debian/rules	(revision 1024)
@@ -0,0 +1,11 @@
+#!/usr/bin/make -f
+
+DEB_DIVERT_EXTENSION = .invirt
+DEB_DIVERT_FILES_sipb-xen-www += \
+    /etc/init.d/apache2
+
+include /usr/share/cdbs/1/rules/debhelper.mk
+include /usr/share/cdbs/1/rules/config-package.mk
+
+binary-fixup/sipb-xen-www::
+	svn co $$(invirt-getconf svn.uri)/trunk/packages/sipb-xen-www/code/ $(DEB_DESTDIR)/var/www/sipb-xen-www
Index: /package_tags/sipb-xen-www/3.12/debian/sipb-xen-www.cron.d
===================================================================
--- /package_tags/sipb-xen-www/3.12/debian/sipb-xen-www.cron.d	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/debian/sipb-xen-www.cron.d	(revision 1024)
@@ -0,0 +1,8 @@
+#
+# cron-jobs for sipb-xen-www
+# Refresh the ACL cache
+#
+
+MAILTO=root
+
+*/5 * * * * www-data python /var/www/sipb-xen-www/cache_acls.py
Index: /package_tags/sipb-xen-www/3.12/debian/sipb-xen-www.init
===================================================================
--- /package_tags/sipb-xen-www/3.12/debian/sipb-xen-www.init	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/debian/sipb-xen-www.init	(revision 1024)
@@ -0,0 +1,35 @@
+#!/bin/bash
+### BEGIN INIT INFO
+# Provides:          sipb-xen-www
+# 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: conserver config from invirt config for invirt host
+# Description:
+### END INIT INFO 
+
+PACKAGE=sipb-xen-www
+
+. /lib/lsb/init-functions
+
+gen_config()
+{
+  for i in /etc/apache2/sites-available/{ssl,svn}
+  do mako-render $i.mako > $i
+  done
+}
+
+case "$1" in
+  start|reload|force-reload|restart)
+    log_begin_msg "Reloading config for $PACKAGE"
+    gen_config
+    log_end_msg $?
+    /etc/init.d/apache2 "$1"
+    ;;
+  stop)
+    ;;
+  *)
+    log_success_msg "Usage: /etc/init.d/$PACKAGE {start|reload|force-reload|restart|stop}"
+    ;;
+esac
Index: /package_tags/sipb-xen-www/3.12/debian/sipb-xen-www.install
===================================================================
--- /package_tags/sipb-xen-www/3.12/debian/sipb-xen-www.install	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/debian/sipb-xen-www.install	(revision 1024)
@@ -0,0 +1,1 @@
+files/* .
Index: /package_tags/sipb-xen-www/3.12/debian/sipb-xen-www.postinst
===================================================================
--- /package_tags/sipb-xen-www/3.12/debian/sipb-xen-www.postinst	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/debian/sipb-xen-www.postinst	(revision 1024)
@@ -0,0 +1,45 @@
+#!/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/sipb-xen-www
+	make clean && make all
+	chgrp -R sipb-xen .
+	chmod -R g+w .
+    ;;
+
+    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/sipb-xen-www/3.12/debian/sipb-xen-www.preinst
===================================================================
--- /package_tags/sipb-xen-www/3.12/debian/sipb-xen-www.preinst	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/debian/sipb-xen-www.preinst	(revision 1024)
@@ -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 sipb-xen > /dev/null; then
+	    addgroup --system sipb-xen
+	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/sipb-xen-www/3.12/files/etc/apache2/conf.d/sipb-xen-repository
===================================================================
--- /package_tags/sipb-xen-www/3.12/files/etc/apache2/conf.d/sipb-xen-repository	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/files/etc/apache2/conf.d/sipb-xen-repository	(revision 1024)
@@ -0,0 +1,17 @@
+Alias /sipb-xen /srv/repository
+
+Alias /debian/ /debian/
+
+<Directory /srv/repository>
+		Options Indexes FollowSymLinks MultiViews
+		AllowOverride None
+		Order allow,deny
+		allow from all
+</Directory>
+
+<Directory /debian>
+		Options Indexes FollowSymLinks MultiViews
+		AllowOverride None
+		Order allow,deny
+		allow from all
+</Directory>
Index: /package_tags/sipb-xen-www/3.12/files/etc/apache2/conf.d/sipb-xen-www
===================================================================
--- /package_tags/sipb-xen-www/3.12/files/etc/apache2/conf.d/sipb-xen-www	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/files/etc/apache2/conf.d/sipb-xen-www	(revision 1024)
@@ -0,0 +1,4 @@
+<IfModule mod_fcgid.c>
+  IPCConnectTimeout 600
+  IPCCommTimeout 600
+</IfModule>
Index: /package_tags/sipb-xen-www/3.12/files/etc/apache2/sites-available/default
===================================================================
--- /package_tags/sipb-xen-www/3.12/files/etc/apache2/sites-available/default	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/files/etc/apache2/sites-available/default	(revision 1024)
@@ -0,0 +1,51 @@
+NameVirtualHost *:80
+<VirtualHost *:80>
+	ServerAdmin webmaster@localhost
+	
+	DocumentRoot /var/www/sipb-xen-www
+	<Directory /var/www/sipb-xen-www>
+		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.fcgi(.*) - [L]
+        RewriteRule ^/trac/chrome/common(.*) /usr/share/trac/htdocs$1 [L]
+	RewriteRule ^/trac/login(.*) https://xvm.mit.edu/trac/login$1 [L]
+        RewriteRule ^/trac(.*) /var/www/trac/trac.fcgi$1 [L]
+	RewriteRule ^/sipb-xen - [L]
+	RewriteRule ^/kill.cgi - [L]
+	RewriteRule ^/~ - [L]
+	RewriteRule ^/(.*) /var/www/sipb-xen-www/main.fcgi/$1 [L]
+
+	ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
+	<Directory "/usr/lib/cgi-bin">
+		AllowOverride None
+		Options ExecCGI -MultiViews +SymLinksIfOwnerMatch
+		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 notice
+
+	CustomLog /var/log/apache2/access.log combined
+	ServerSignature On
+
+    Alias /doc/ "/usr/share/doc/"
+    <Directory "/usr/share/doc/">
+        Options Indexes MultiViews FollowSymLinks
+        AllowOverride None
+        Order deny,allow
+        Deny from all
+        Allow from 127.0.0.0/255.0.0.0 ::1/128
+    </Directory>
+
+</VirtualHost>
Index: /package_tags/sipb-xen-www/3.12/files/etc/apache2/sites-available/ssl.mako
===================================================================
--- /package_tags/sipb-xen-www/3.12/files/etc/apache2/sites-available/ssl.mako	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/files/etc/apache2/sites-available/ssl.mako	(revision 1024)
@@ -0,0 +1,98 @@
+<%
+from invirt.config import structs as cfg
+hostname = cfg.web.hostname
+errmail  = cfg.web.errormail
+tracuri  = cfg.trac.uri
+%>
+<VirtualHost *:443>
+	ServerAdmin ${errmail}
+	ServerName ${hostname}:443
+	
+	DocumentRoot /var/www/sipb-xen-www
+	<Directory /var/www/sipb-xen-www>
+		Options Indexes FollowSymLinks MultiViews ExecCGI
+		AllowOverride None
+		Order allow,deny
+		allow from all
+	</Directory>
+	<Location />
+		Require valid-user
+		AuthType SSLCert
+		AuthSSLCertVar SSL_CLIENT_S_DN_Email
+		AuthSSLCertStripSuffix "@MIT.EDU"
+	</Location>
+
+	RewriteEngine On
+	RewriteRule ^/favicon.ico - [L]
+	RewriteRule ^/static(.*) - [L]
+	RewriteRule ^/overlord/static(.*) /static/$1 [L]
+	RewriteRule ^/admin/static(.*) /static/$1 [L]
+	RewriteRule ^/trac.fcgi(.*) - [L]
+	RewriteRule ^/trac/chrome/common(.*) /usr/share/trac/htdocs$1 [L]
+	RewriteRule ^/trac(.*) /var/www/trac/trac.fcgi$1 [L]
+	RewriteRule ^/var(.*) - [L]
+	RewriteRule ^/wiki(.*) - [L]
+	RewriteRule ^/kill.cgi - [L]
+	RewriteRule ^/~ - [L]
+	RewriteRule ^/(.*) /var/www/sipb-xen-www/main.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 ssl/mitCAclient.pem
+	SSLVerifyClient require
+	SSLVerifyDepth 10
+
+	SSLOptions +StdEnvVars
+	
+	SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0
+
+	Redirect /wiki ${tracuri}	
+</VirtualHost>
+
+<VirtualHost *:446>
+	ServerAdmin ${errmail}
+	ServerName ${hostname}:446
+	
+	DocumentRoot /var/www/sipb-xen-www
+	<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/sipb-xen-www/3.12/files/etc/apache2/sites-available/svn.mako
===================================================================
--- /package_tags/sipb-xen-www/3.12/files/etc/apache2/sites-available/svn.mako	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/files/etc/apache2/sites-available/svn.mako	(revision 1024)
@@ -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/sipb-xen-www/3.12/files/etc/apache2/sites-enabled/000-default
===================================================================
--- /package_tags/sipb-xen-www/3.12/files/etc/apache2/sites-enabled/000-default	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/files/etc/apache2/sites-enabled/000-default	(revision 1024)
@@ -0,0 +1,1 @@
+link ../sites-available/default
Index: /package_tags/sipb-xen-www/3.12/files/etc/apache2/sites-enabled/ssl
===================================================================
--- /package_tags/sipb-xen-www/3.12/files/etc/apache2/sites-enabled/ssl	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/files/etc/apache2/sites-enabled/ssl	(revision 1024)
@@ -0,0 +1,1 @@
+link ../sites-available/ssl
Index: /package_tags/sipb-xen-www/3.12/files/etc/apache2/sites-enabled/svn
===================================================================
--- /package_tags/sipb-xen-www/3.12/files/etc/apache2/sites-enabled/svn	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/files/etc/apache2/sites-enabled/svn	(revision 1024)
@@ -0,0 +1,1 @@
+link ../sites-available/svn
Index: /package_tags/sipb-xen-www/3.12/files/etc/init.d/apache2.invirt
===================================================================
--- /package_tags/sipb-xen-www/3.12/files/etc/init.d/apache2.invirt	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/files/etc/init.d/apache2.invirt	(revision 1024)
@@ -0,0 +1,53 @@
+#!/usr/bin/pagsh -e
+#
+# Apache kstart wrapper by anders.
+#
+
+SCRIPT=/etc/init.d/apache2.invirt-orig
+KSTART_PIDFILE=/var/run/k5start-apache2.pid
+KSTART_KEYTAB=/etc/apache2/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" \
+	-U -f "$KSTART_KEYTAB" -K10 -S afs -I "$AFSCELL" -t -b
+    cat "$TMP_PIDFILE" >|"$KSTART_PIDFILE"
+    rm -f "$TMP_PIDFILE"
+}
+kstart_stop () {
+    if [ -e $KSTART_PIDFILE ]; then
+	/sbin/start-stop-daemon --stop --pidfile $KSTART_PIDFILE
+	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/sipb-xen-www/3.12/power.svg
===================================================================
--- /package_tags/sipb-xen-www/3.12/power.svg	(revision 1024)
+++ /package_tags/sipb-xen-www/3.12/power.svg	(revision 1024)
@@ -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>
