diff --git a/README.txt b/README.txt
old mode 100644
new mode 100755
index e00dce5..712d2d8
--- a/README.txt
+++ b/README.txt
@@ -1,3 +1,4 @@
+// $Id: README.txt,v 1.7 2009/11/01 16:27:22 agentken Exp $
 
 /**
  * @file
diff --git a/domain_user.admin.inc b/domain_user.admin.inc
old mode 100644
new mode 100755
index a0707af..2c8eac0
--- a/domain_user.admin.inc
+++ b/domain_user.admin.inc
@@ -1,4 +1,5 @@
 <?php
+// $Id: domain_user.admin.inc,v 1.4 2009/11/01 16:27:22 agentken Exp $
 
 /**
  * @file
@@ -7,20 +8,44 @@
  * @ingroup domain_user
  */
 
- /**
+/**
  * FormsAPI for module settings
  */
-function domain_user_configure_form() {
+function domain_user_configure_form($form, &$form_state) {
   drupal_set_title(t('User domain settings'));
   $form = array();
-  $form['domain_user'] = array(
+  
+  $form['domain_user_categories']['add_category'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Add category'),
+  );
+  
+  $form['domain_user_create'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Create user domains'),
+  );  
+  
+  $form['domain_user_create']['domain_user'] = array(
     '#type' => 'radios',
-    '#title' => t('Module behavior'),
-    '#options' => array(0 => t('Do not create domains for users'), 1 => t('Automatically create domains for new users'), 2 => t('Ask users if they would like to create a domain')),
-    '#description' => t('Should subdomains be created when users register?'),
+    '#title' => t('Should subdomains be created when users register?'),
+    '#options' => array(
+      0 => t('Do not create domains for users'),
+      1 => t('Automatically create domains for new users'),
+      2 => t('Ask users if they would like to create a domain'),
+    ),
+    '#description' => t(''),
     '#default_value' => variable_get('domain_user', 0),
   );
-  $form['domain_user_root'] = array(
+  
+  $form['domain_user_create']['domain_user_create_category'] = array(
+      '#type' => 'radios',
+      '#title' => t('Category to create user domain under'),
+      '#options' => variable_get('domain_user_categories', array(1 => 'Personal web site')),
+      '#description' => t('What category should the new user domain appear under?'),
+      '#default_value' => variable_get('domain_user_create_category', 1),
+    );
+  
+  $form['domain_user_create']['domain_user_root'] = array(
     '#type' => 'textfield',
     '#title' => t('Root domain name'),
     '#size' => 40,
@@ -29,35 +54,63 @@ function domain_user_configure_form() {
     '#default_value' => variable_get('domain_user_root', variable_get('domain_root', '')),
     '#description' => t('The root domain to use for creating user domains, typically <em>example.com</em>.  No http or slashes.
       <br /> When users create domains, their username will be added to the root domain to create a custom domain.
-      <br /> For example, <em>user1.example.com</em> or <em>administrator.example.com</em>.')
-  );
-  $form['domain_user_scheme'] = array(
+      <br /> For example, <em>user1.example.com</em> or <em>administrator.example.com</em>.'),
+  );    
+  
+  $form['domain_user_create']['domain_user_scheme'] = array(
     '#type' => 'radios',
     '#title' => t('User Domain URL scheme'),
-    '#options' => array('http' => 'http://', 'https' => 'https://'),
+    '#options' => array(
+      'http' => 'http://',
+      'https' => 'https://',
+    ),
     '#default_value' => variable_get('domain_user_scheme', 'http'),
-    '#description' => t('The URL scheme for accessing user domains.')
+    '#description' => t('The URL scheme for accessing user domains.'),
   );
+  
   $form['domain_user_login'] = array(
-    '#type' => 'radios',
+    '#type' => 'fieldset',
     '#title' => t('User login behavior'),
-    '#options' => array(1 => t('On login, go to personal domain'), 0 => t('Do not go to personal domain on login')),
+  ); 
+  
+  $form['domain_user_login']['domain_user_login'] = array(
+    '#type' => 'radios',
+    '#title' => t('Redirect to domain?'),
+    '#options' => array(
+      1 => t('On login, go to personal domain'),
+      0 => t('Do not go to personal domain on login'),
+    ),
     '#default_value' => variable_get('domain_user_login', 1),
-    '#description' => t('The domain users should go to when they login to the site.')
+    '#description' => t('The domain users should go to when they login to the site.'),
   );
+  
+  $form['domain_user_login']['domain_user_login_category'] = array(
+      '#type' => 'radios',
+      '#title' => t('Category of domain to log in to'),
+      '#options' => variable_get('domain_user_categories', array(1 => 'Personal web site')),
+      '#description' => t('What category should be used to select the domain to log in to?'),
+      '#default_value' => variable_get('domain_user_login_category', 1),
+  );
+  
   $form['domain_user_assign'] = array(
     '#type' => 'radios',
     '#title' => t('Assign user domains'),
-    '#options' => array(0 => t('Only assign to user domain'), 1 => t('Assign to both user domain and active domain')),
+    '#options' => array(
+      0 => t('User is assigned only to their user domain'),
+      1 => t('Users can be assigned to other domains besides their user domains'),
+    ),
     '#default_value' => variable_get('domain_user_assign', 0),
-    '#description' => t('Indicates which domains should the user be assigned to when new user accounts are created.')
+    '#description' => t('Indicates which domains should the user be assigned to when new user accounts are created.'),
   );
   if (module_exists('domain_prefix')) {
     $form['domain_user_prefixing'] = array(
       '#type' => 'radios',
       '#title' => t('Domain table prefixing'),
-      '#options' => array(0 => t('Never create prefixed tabled for user domains'), 1 => t('Obey the settings in Domain Prefix')),
-      '#description' => t('Should user domains have detabase talbes created?'),
+      '#options' => array(
+        0 => t('Never create prefixed tabled for user domains'),
+        1 => t('Obey the settings in Domain Prefix'),
+      ),
+      '#description' => t('Should user domains have database tables created?'),
       '#default_value' => variable_get('domain_user_prefixing', 0),
     );
   }
@@ -66,14 +119,59 @@ function domain_user_configure_form() {
   if (!empty($rules)) {
     $output = '<ul>';
     foreach ($rules as $rule) {
-      $output .= '<li>'. $rule .'</li>';
+      $output .= '<li>' . $rule . '</li>';
     }
     $output .= '</ul>';
   }
   $form['rules'] = array(
     '#type' => 'markup',
     '#weight' => 20,
-    '#value' => '<br /><br />'. t('<h3>Reserved Usernames</h3><p>The following usernames cannot be registered, since they are used as unique domains:</p>') . $output,
+    '#value' => '<br /><br />' . t('<h3>Reserved Usernames</h3><p>The following usernames cannot be registered, since they are used as unique domains:</p>') . $output,
   );
-  return system_settings_form($form);
+  
+  $form = system_settings_form($form);
+  array_unshift($form['#submit'], 'domain_user_add_category_submit');
+  // System settings form adds a theme we cannot use.
+  unset($form['#theme']);
+  return $form;
 }
+
+
+function domain_user_add_category_submit($form, &$form_state) {
+    $category = $form_state['values']['add_category'];
+    
+    $categories = variable_get('domain_user_categories', array(1 => 'Personal web site'));
+    
+    if(!in_array($categories, $category) && !empty($category)) {
+       $max_key = max(array_keys($categories));
+       $categories[$max_key +1] = $category;       
+    }   
+    
+    variable_set('domain_user_categories', $categories);   
+    
+    unset($form_state['values']['add_category']);   
+     
+}    
+
+
+/**
+ * FormsAPI theming.
+ */
+function theme_domain_user_configure_form($variables) {  
+  
+  $form = $variables['form'];
+  $output = '';
+  $categories = variable_get('domain_user_categories', array(1 => 'Personal web site'));
+  $header = array('ID' , 'Category', '');
+  $rows = array();
+  foreach ( $categories as $id => $category ) {
+    $rows[] = array($id, $category, l('delete', 'domain-user/delete/' . $id)); 
+  }  
+
+  $output .= theme('table', array('header' => $header, 'rows' => $rows));
+  $output .= drupal_render_children($form);
+  return $output;
+}
+
+
+
diff --git a/domain_user.info b/domain_user.info
old mode 100644
new mode 100755
index 04a2925..f503b98
--- a/domain_user.info
+++ b/domain_user.info
@@ -1,7 +1,12 @@
+;  $Id: domain_user.info,v 1.2 2008/03/26 02:47:32 agentken Exp $
 name = Domain User
 description = Creates unique subdomains for registered users.
 package = Domain Access
 dependencies[] = domain
 core = 7.x
-files[] = domain_user.module
-files[] = domain_user.admin.inc
+
+files[] = domain_user.views.inc
+
+; Views handlers
+files[] = includes/domain_user_handler_relationships.inc
+
diff --git a/domain_user.install b/domain_user.install
old mode 100644
new mode 100755
index 956f718..1ec2154
--- a/domain_user.install
+++ b/domain_user.install
@@ -1,4 +1,5 @@
 <?php
+// $Id: domain_user.install,v 1.7 2009/05/31 18:16:41 agentken Exp $
 
 /**
  * @file
@@ -6,33 +7,69 @@
  */
 
 /**
- * Implement hook_install()
+ * Implements hook_install().
  */
 function domain_user_install() {
-  drupal_install_schema('domain_user');
+  // TODO The drupal_(un)install_schema functions are called automatically in D7.
+  // drupal_install_schema('domain_user')
 }
 
 /**
- * Implement hook_schema()
+ * Implements hook_schema().
  */
 function domain_user_schema() {
   $schema['domain_user'] = array(
     'fields' => array(
-      'domain_id' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
-      'uid' => array('type' => 'int', 'not null' => TRUE, 'default' => 0)),
+      'domain_id' => array(
+        'description' => 'Domain ID as found in domain table.',
+        'type' => 'int',
+        'not null' => TRUE,
+        'default' => 0,
+      ),
+      'uid' => array(
+        'description' => 'User ID as found in users table.',
+        'type' => 'int',
+        'not null' => TRUE,
+        'default' => 0,
+      ),
+      'category' => array(
+        'description' => 'ID of user domain category.',
+        'type' => 'int',
+        'not null' => TRUE,
+        'default' => 1,
+      ),
+    ),
     'indexes' => array(
       'domain_id' => array('domain_id'),
-      'uid' => array('uid')),
+      'uid' => array('uid'),
+      'category' => array('uid'),
+    ),
+    'primary key' => array('domain_id', 'uid', 'category'),
   );
   return $schema;
 }
 
 /**
- * Implement hook_uninstall()
+ * Add category column to domain_user table.
+ */
+function domain_user_update_7001() {   
+    db_add_field('domain_user', 'category', array('description' => 'ID of user domain category.', 'type' => 'int', 'not null' => TRUE, 'default' => 1));
+        
+}   
+
+/**
+ * Add primary key and index.
+ */
+function domain_user_update_7002() {
+   db_add_primary_key('domain_user', array('domain_id', 'uid', 'category'));
+   db_add_index('domain_user', 'category', array('category'));
+}     
+
+/**
+ * Implements hook_uninstall().
  */
 function domain_user_uninstall() {
-  // Drop the storage table.
-  drupal_uninstall_schema('domain_user');
+
   variable_del('domain_user');
   variable_del('domain_user_root');
   variable_del('domain_user_scheme');
diff --git a/domain_user.module b/domain_user.module
old mode 100644
new mode 100755
index 45bdef7..46821c0
--- a/domain_user.module
+++ b/domain_user.module
@@ -1,52 +1,86 @@
 <?php
+// $Id: domain_user.module,v 1.28.2.2 2010/04/05 14:30:43 agentken Exp $
 
 /**
  * @defgroup domain_user Domain User: personal subdomains
- *
  * Creates unique subdomains for registered users.
- */
-
-/**
  * @file
  * Creates unique subdomains for registered users.
- *
  * @ingroup domain_user
  */
 
 /**
- * Implement hook_init()
+ * Implements hook_init().
  *
  * We have to do this because we cannot redirect on login.
  */
 function domain_user_init() {
   if (isset($_SESSION['domain_user'])) {
-    $domain = domain_user_lookup($_SESSION['domain_user']);
+    
+    $login_category = variable_get('domain_user_login_category', 1);
+    $domain = domain_user_lookup($_SESSION['domain_user'], $login_category);
     unset($_SESSION['domain_user']);
     domain_goto($domain);
   }
 }
 
 /**
- * Implement hook_menu()
+ * Implements hook_menu().
  */
 function domain_user_menu() {
   $items = array();
-  $items['admin/build/domain/user'] = array(
+  $items['admin/structure/domain/user'] = array(
     'title' => 'User domains',
     'type' => MENU_LOCAL_TASK,
     'access arguments' => array('administer domains'),
     'page callback' => 'drupal_get_form',
     'page arguments' => array('domain_user_configure_form'),
-    'file' => 'domain_user.admin.inc'
+    'file' => 'domain_user.admin.inc',
+  );
+  
+  // Todo - there is a premade confirm form somewhere we can use for this
+  $items['domain-user/delete/%category'] = array(
+    'title' => 'User domains',
+    'type' => MENU_LOCAL_TASK,
+    'access arguments' => array('administer domains'),
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('domain_user_category_delete_form', 2),
+    'file' => 'domain_user.admin.inc',
   );
   return $items;
 }
 
 /**
- * Implement hook_perm()
+ * Implements hook_permission().
+ */
+function domain_user_permission() {
+  return array(
+    'create personal domain' => array(
+      'title' => t('Create personal domain'),
+      'description' => t('Allow users to create their own domain'),
+    ),
+    'create user domains' => array(
+      'title' => t('Create user domains'),
+      'description' => t('Allow users to create domains for other users'),
+    ),
+    'change user domains' => array(
+      'title' => t('Change user domains'),
+      'description' => t('Allow users to assign users to other domains. (This doesnt apply to categories for which domains are created upon login)'),
+    ),
+  );
+}
+
+/**
+ * Implements hook_theme()
  */
-function domain_user_perm() {
-  return array('create personal domain', 'create user domains');
+function domain_user_theme($existing, $type, $theme, $path) {
+  $themes = array(
+    'domain_user_configure_form' => array(
+      'render element' => 'form',
+      'file' => 'domain_user.admin.inc',
+    ),
+  );
+  return $themes;
 }
 
 /**
@@ -68,15 +102,21 @@ function domain_user_rules($generate = TRUE) {
   foreach ($domains as $domain) {
     if ($domain['domain_id'] > 0 && empty($domain['uid']) && !empty($root)) {
       // Chop the name of domains to find the username equivalent.
-      $string = str_replace('.'. $root, '', $domain['subdomain']);
+      $string = str_replace('.' . $root, '', $domain['subdomain']);
       // In this case, we do strip port protocols, since they make no sense as usernames.
       $str = explode(':', $string);
       $name_string = $str[0];
       $reserved[] = $name_string;
       if ($generate && !empty($name_string)) {
-        $check = db_result(db_query("SELECT aid FROM {access} WHERE mask = '%s'", $name_string));
+        $check = db_query("SELECT aid FROM {access} WHERE mask = :mask", array(':mask' => $name_string))->fetchField();
         if (!$check) {
-          db_query("INSERT INTO {access} (mask, type, status) VALUES ('%s', '%s', %d)", $name_string, 'user', 0);
+          $id = db_insert('access')
+             ->fields(array(
+            'mask' => $name_string,
+            'type' => 'user',
+            'status' => 0,
+          ))
+          ->execute();
         }
       }
     }
@@ -85,7 +125,7 @@ function domain_user_rules($generate = TRUE) {
 }
 
 /**
- * Implement hook_enable()
+ * Implements hook_enable().
  *
  * When the module is enabled, create the rules for existing domains.
  */
@@ -94,7 +134,7 @@ function domain_user_enable() {
 }
 
 /**
- * Implement hook_disable()
+ * Implements hook_disable().
  *
  * Deletes our user access masks.
  */
@@ -102,181 +142,333 @@ function domain_user_disable() {
   $rules = domain_user_rules(FALSE);
   if (!empty($rules)) {
     foreach ($rules as $rule) {
-      db_query("DELETE FROM {access} WHERE mask = '%s'", $rule);
+      db_delete('access')
+      ->condition('mask', $rule)
+      ->execute();
     }
   }
 }
 
 /**
- * Implement hook_domainload()
+ * Implements hook_domainload().
+ *
+ * change: changed $domain[uid] to array as there may be multiple users
+ * note - we might have to have another index here for personal domains
  */
 function domain_user_domainload(&$domain) {
   // Zero is the default domain, and we don't want to invalidate it.
   if ($domain['domain_id'] > 0) {
-    $data = db_fetch_array(db_query("SELECT du.uid, u.status FROM {domain_user} du
+    $result = db_query("SELECT du.uid, du.category, u.status FROM {domain_user} du
       INNER JOIN {users} u ON du.uid = u.uid
-      WHERE du.domain_id = %d", $domain['domain_id']));
-    if ($data['uid']) {
-      $domain['uid'] = $data['uid'];
+      WHERE du.domain_id = :domain_id", array(':domain_id' => $domain['domain_id']))->fetchAssoc();
+    $domain['uid'] = array(); 
+    if (!empty($result)) { 
+      foreach ($result as $data) {
+        if ($data['uid']) {  
+          $domain['uid'][$data['category']] = $data['uid'];
+        }
+      }    
     }
   }
 }
 
 /**
- * Implement hook_user()
+ * Implements hook_user_view().
  */
-function domain_user_user($op, &$edit, &$account, $category = NULL) {
-  switch ($op) {
-    case 'view':
-      $domain = domain_user_lookup($account->uid);
-      if ($domain != -1) {
-        $account->content['summary']['domain_user'] = array(
-          '#type' => 'user_profile_item',
-          '#title' => t('Personal web site'),
-          '#weight' => 6,
-          '#value' => l($domain['path'], $domain['path']),
-        );
-      }
-      break;
-    case 'register':
-    case 'form':
-      // This function will return -1 if no domain exists. If no user exists yet, assume -1.
-      $domain = -1;
-      if (isset($account->uid)) {
-        $domain = domain_user_lookup($account->uid);
-      }
-      else {
-        $account->uid = 0;
-        $account->roles = array(0 => t('anonymous user'));
-      }
-      // New users throw E_ALL errors.
-      $name = t('username');
-      if (isset($account->name)) {
-        // Sanitize the username according to the host RFC.
-        $name = domain_user_strip_chars($account->name);
-      }
-      $default = domain_default();
-      $root = variable_get('domain_user_root', $default['subdomain']);
+function domain_user_user_view($account, $view_mode) {
+    
+  $categories = variable_get('domain_user_categories', array(1 => 'Personal web site'));
+  foreach ($categories as $category_id => $category) {  
+    
+    $domain = domain_user_lookup($account->uid, $category_id);
+    if ($domain != -1) {
+        
+      $account->content['summary']['domain_user_'. $category_id] = array(
+        '#type' => 'user_profile_item',
+        '#title' => $category,
+        '#weight' => 6,
+        '#markup' => l($domain['path'], $domain['path']),
+      );
+    }
+  }  
+}
+
+/**
+ * Implements hook_form_FORM_ID_alter().
+ */
+function domain_user_form_user_profile_form_alter(&$form, &$form_state) {
+  domain_user_form_user_form_alter($form, $form_state);
+}
+
+/**
+ * Implements hook_form_FORM_ID_alter().
+ */
+function domain_user_form_user_register_form_alter(&$form, &$form_state) {
+  domain_user_form_user_form_alter($form, $form_state);
+}
+
+/**
+ * Helper function for the two user forms we care about.
+ */
+function domain_user_form_user_form_alter(&$form, &$form_state) {
+      
+  $categories = variable_get('domain_user_categories', array(1 => 'Personal web site'));
+  $account = $form['#user'];
+  
+  // New users throw E_ALL errors.
+  $name = t('username');
+  if (isset($account->name)) {
+    // Sanitize the username according to the host RFC.
+    $name = domain_user_strip_chars($account->name);
+  }
+  
+  $default = domain_default();
+  $root = variable_get('domain_user_root', $default['subdomain']);
+  
+  $login_category = variable_get('domain_user_login_category', 1);
+  $create_domain = variable_get('domain_user', 0);
+  
+  if (!isset($account->uid)) {
+    $account->uid = 0;
+    $account->roles = array(0 => t('anonymous user'));
+  }  
+
+  foreach($categories as $category_id => $category) {
+    
+    $domain = -1;
+    if (isset($account->uid)) {
+      $domain = domain_user_lookup($account->uid, $category_id);
+      $default = array($domain['domain_id']);
+        //drupal_set_message($default[$domain['domain_id']]);
+    }
+    
+    if ($create_domain > 0 && $category_id == $login_category) {
       // If the user name is on the ban list, we do not create a domain.
       // TODO: Maybe we should set a message here.
-      if ($domain == -1 && domain_lookup(NULL, $name .'.'. $root) == -1) {
-        $create_domain = variable_get('domain_user', 0);
-        if (user_access('create personal domain', $account) || user_access('create user domains')) {
-          // For the add user page, we force the checkbox.
-          if (empty($account->uid) && arg(0) == 'admin' && $create_domain == 1) {
-            $create_domain = 2;
-          }
-          if ($create_domain == 1 && !empty($root)) {
-            $form['domain_user_domain']['domain_create_user'] = array(
+      if ($domain == -1 && domain_lookup(NULL, $name . '.' . $root) == -1 && 
+         (user_access('create personal domain', $account) || user_access('create user domains'))) { 
+            
+        $form['domain_user']['domain_create_user_category'] = array(
               '#type' => 'value',
-              '#value' => 1,
-            );
-          }
-          else if ($create_domain == 2 && !empty($root)) {
-            $form['domain_user_domain'] = array(
-              '#type' => 'fieldset',
-              '#title' => t('Personal web site'),
-              '#collapsible' => TRUE,
-              '#collapsed' => FALSE,
-              '#weight' => 1
-            );
-            $form['domain_user_domain']['domain_create_user'] = array(
-              '#type' => 'checkbox',
-              '#return_value' => 1,
-              '#title' => t('Yes, I want to create my own site at <b>!user.!site</b>', array('!user' => $name, '!site' => $root)),
-            );
-          }
-          return $form;
+              '#value' => $category_id,
+        );        
+        
+        // For the add user page, we force the checkbox.
+        if (empty($account->uid) && arg(0) == 'admin' && $create_domain == 1) {
+          $create_domain = 2;
         }
+      
+        if ($create_domain == 1 && !empty($root)) {
+          $form['domain_user']['domain_create_user'] = array(
+            '#type' => 'value',
+            '#value' => 1,
+          );
+        }
+        else if ($create_domain == 2 && !empty($root)) {
+
+          $form['domain_user']['domain_create_user'] = array(
+            '#type' => 'checkbox',
+            '#return_value' => 1,
+            '#title' => 'Create '. $category . 'site',
+            '#description' => t('Yes, I want to create my own site at <b>!user.!site</b>', array('!user' => $name, '!site' => $root)),
+          );
+        }       
       }
-      break;
-    case 'insert':
-    case 'update':
-      // If we did not come from our expected form, do nothing.
-      if (!isset($edit['domain_create_user'])) {
-        return;
-      }
-      if (!empty($edit['domain_create_user']) && (user_access('create personal domain', $account) || !user_access('create user domains'))) {
-        $user_root = variable_get('domain_user_root', variable_get('domain_root', ''));
-        $name = domain_user_strip_chars($account->name);
-        $form_state['values']['sitename'] = $account->name;
-        $form_state['values']['subdomain'] = $name .'.'. $user_root;
-        $form_state['values']['valid'] = $account->status;
-        $form_state['values']['user_submitted'] = TRUE;
-        // This function will return -1 if no domain exists.
-        $domain = domain_user_lookup($account->uid);
-        if ($domain == -1) {
-          // Set arguments to be passed to the form
-          $arguments = array('user_submitted' => TRUE, 'ignore_domain_status_check' => TRUE);
-          // Include the form file.
-          include_once drupal_get_path('module', 'domain') .'/domain.admin.inc';
-          // Set the scheme as needed.
-          $form_state['values']['domain_scheme'] = variable_get('domain_user_scheme', 'http');
-          drupal_execute('domain_form', $form_state, array(), $arguments);
-          $domain = domain_lookup(NULL, $form_state['values']['subdomain'], TRUE);
-          if ($domain['domain_id']) {
-            db_query("INSERT INTO {domain_user} (domain_id, uid) VALUES (%d, %d)", $domain['domain_id'], $account->uid);
-            // If this user has never registered before, or settings require it, remove other domain editing permissions.
-            if (empty($account->login) || !variable_get('domain_user_assign', 0)) {
-              db_query("DELETE FROM {domain_editor} WHERE uid = %d", $account->uid);
-            }
-            db_query("INSERT INTO {domain_editor} (domain_id, uid) VALUES (%d, %d)", $domain['domain_id'], $account->uid);
-            $edit['domains'][] = $domain['domain_id'];
-            drupal_set_message(t('Your personal URL is <a href="!url">!url</a>.', array('!url' => url($domain['path']))));
-          }
-          else {
-            drupal_set_message(t('Your personal URL could not be created.'));
+    }           
+    else if (user_access('administer domains') || user_access('change user domains') ) {
+        
+      if (!isset($options)) {
+        $options = array();
+        //might need to change this
+        $options[-99] = 'None';
+        $domains = domain_domains();
+        foreach ($domains as $domain) {
+          // Handle 0 and -1
+          if ($domain['domain_id'] == variable_get('default_domain', 0)) {
+            $domain['domain_id'] = -1;
           }
+          $options[$domain['domain_id']] = check_plain($domain['sitename']);
         }
-        // Set the user's default domain to their subdomain.
-        if ($domain['domain_id'] > 0) {
-          // If the user cannot assign domain editors, only allow their unique domain.
-          if (!user_access('assign domain editors')) {
-            $edit['domain_user'] = array();
-          }
-          $edit['domain_user'][$domain['domain_id']] = $domain['domain_id'];
-          // If the user account is blocked, set the domain to invalid.
-          if ($account->status == 0) {
-            db_query("UPDATE {domain} SET valid = %d WHERE domain_id = %d", 0, $domain['domain_id']);
-          }
+        $format = domain_select_format();
+      }   
+     
+      $form['domain_user']['subdomain-' . $category_id] = array(
+        '#type' => empty($format) ? 'checkboxes' : 'select',
+        '#options' => $options,
+        '#title' => $category,
+        '#description' => t('Select the user\'s default websites.'),
+        '#default_value' => $default
+      );
+    }
+  } 
+}
+
+/**
+ * Implements hook_user_insert().
+ */
+function domain_user_user_insert(&$edit, $account, $category) {
+  domain_user_user_insertupdate($edit, $account, $category);  
+}       
+
+/**
+ * Implements hook_user_presave().
+ */
+function domain_user_user_presave(&$edit, $account, $category) { 
+  domain_user_user_insertupdate($edit, $account, $category); 
+}    
+       
+function domain_user_user_insertupdate(&$edit, $account, $category) {       
+      
+  if (!empty($edit['domain_create_user']) && (user_access('create personal domain', $account) || !user_access('create user domains'))) {
+    
+    $category = variable_get('domain_user_create_category', 1); 
+    
+    $user_root = variable_get('domain_user_root', variable_get('domain_root', ''));
+    $name = domain_user_strip_chars($account->name);
+    $form_state['values']['sitename'] = $account->name;
+    $form_state['values']['subdomain'] = $name . '.' . $user_root;
+    $form_state['values']['valid'] = $account->status;
+    $form_state['values']['user_submitted'] = TRUE;
+    // This function will return -1 if no domain exists.
+    $domain = domain_user_lookup($account->uid, $edit['domain_create_user_category']);
+    if ($domain == -1) {
+      // Set arguments to be passed to the form
+      $arguments = array(
+        'user_submitted' => TRUE,
+        'ignore_domain_status_check' => TRUE,
+      );
+      // Include the form file.
+      include_once DRUPAL_ROOT . '/' . drupal_get_path('module', 'domain') . '/domain.admin.inc';
+      // Set the scheme as needed.
+      $form_state['values']['domain_scheme'] = variable_get('domain_user_scheme', 'http');
+      drupal_form_submit('domain_form', $form_state, array(), $arguments);
+      $domain = domain_lookup(NULL, $form_state['values']['subdomain'], TRUE);
+      
+      if ($domain['domain_id']) {
+
+        $id = db_insert('domain_user')
+         ->fields(array(
+         'domain_id' => $domain['domain_id'],
+         'uid' => $account->uid,
+         'category' => $category,
+         ))
+         ->execute();
+     }  
+     // If this user has never registered before, or settings require it, remove 
+     // other domain editing permissions. We will then give editing permissions
+     // over his user domains later.
+     if (empty($account->login) || !variable_get('domain_user_assign', 0)) {
+          db_delete('domain_editor')
+          ->condition('uid', $account->uid)
+        ->execute();
+     } 
+
+     $id = db_insert('domain_editor')
+           ->fields(array(
+          'domain_id' => $domain['domain_id'],
+          'uid' => $account->uid,
+     ))
+      ->execute();
+      $edit['domains'][] = $domain['domain_id'];
+      drupal_set_message(t('Your personal URL is <a href="!url">!url</a>.', array('!url' => url($domain['path']))));
+      
+      // Set the user's default domain to their subdomain.
+      if ($domain['domain_id'] > 0) {
+        // If the user cannot assign domain editors, only allow their unique domain.
+        if (!user_access('assign domain editors')) {
+          $edit['domain_user'] = array();
+        }
+        $edit['domain_user'][$domain['domain_id']] = $domain['domain_id'];
+        // If the user account is blocked, set the domain to invalid.
+        if ($account->status == 0) {
+          db_update('domain')
+          ->fields(array(
+            'valid' => 0,
+          ))
+          ->condition('domain_id', $domain['domain_id'])
+          ->execute();
         }
       }
-      if (isset($edit['domain_create_user']) && !(user_access('create personal domain', $account) || user_access('create user domains'))) {
-        drupal_set_message(t('Your personal URL could not be created.'));
-      }
+      
       // Throw away what we do not need.
       $edit['domain_create_user'] = NULL;
       $edit['domains'] = NULL;
-      // Special case if the username has changed.
-      if ($op == 'update' && isset($edit['name']) && $edit['name'] != $account->name) {
-        $domain = domain_user_lookup($account->uid, TRUE);
+     
+      // Change user domain the username has changed.
+      if (isset($edit['name']) && $edit['name'] != $account->name) {
+        $domain = domain_user_lookup($account->uid, $category, TRUE);
         if ($domain != -1) {
           $user_root = variable_get('domain_user_root', variable_get('domain_root', ''));
           $name = domain_user_strip_chars($edit['name']);
-          $string = $name .'.'. $user_root;
-          db_query("UPDATE {domain} SET subdomain = '%s', sitename = '%s' WHERE domain_id = %d", $string, $edit['name'], $domain['domain_id']);
+          $string = $name . '.' . $user_root;
+          db_update('domain')
+          ->fields(array(
+            'subdomain' => $string,
+            'sitename' => $edit['name'],
+          ))
+          ->condition('domain_id', $domain['domain_id'])
+          ->execute();
         }
       }
-      break;
-    case 'login':
-      // If the user has a personal domain, take them there.
-      $domain = domain_user_lookup($account->uid);
-      if (variable_get('domain_user_login', 1) && $domain != -1) {
-        // We cannot do a redirect on login, which forces us to use a $_SESSION variable.
-        // Only store the uid here, no need to store extra data where it can get hijacked.
-        $_SESSION['domain_user'] = $account->uid;
-      }
-      break;
-    case 'delete':
-      // Delete the record
-      // Run the lookup before we delete the row!
-      $domain = domain_user_lookup($account->uid);
-      if ($domain != -1) {
-        db_query("DELETE FROM {domain} WHERE domain_id = %d", $domain['domain_id']);
-        // Let other modules act.
-        module_invoke_all('domainupdate', 'delete', $domain);
-      }
-      break;
+      
+    }
+    else {
+      drupal_set_message(t('Your personal domain name could not be created.'));
+    }
+  }
+  
+  $categories = variable_get('domain_user_categories', array(1 => 'Personal web site'));
+  
+  foreach ($categories as $category_id => $category) {
+    if ($edit['domain_create_user_category'] != $category_id) {       
+      if (isset($edit['subdomain-' . $category_id])) {
+        
+        $domain_id = $edit['subdomain-' . $category_id];
+        
+        db_merge('domain_user')
+        ->key(array(
+         'uid' => $account->uid, 
+         'category' => $category_id,
+        )) 
+        ->fields(array(
+         'domain_id' => $domain_id,
+         'uid' => $account->uid,
+         'category' => $category_id,
+       ))
+       ->execute();
+        
+      }    
+    }    
+  }         
+}
+
+
+/**
+ * Implements hook_user_login().
+ */
+function domain_user_user_login(&$edit, $account) {
+  // If the user has a personal domain, take them there.
+  $domain = domain_user_lookup($account->uid);
+  if (variable_get('domain_user_login', 1) && $domain != -1) {
+    // We cannot do a redirect on login, which forces us to use a $_SESSION variable.
+    // Only store the uid here, no need to store extra data where it can get hijacked.
+    $_SESSION['domain_user'] = $account->uid;
+  }
+}
+
+/**
+ * Implements hook_user_cancel().
+ */
+function domain_user_user_cancel($edit, $account, $method) {
+  // Delete the record
+  // Run the lookup before we delete the row!
+  $domain = domain_user_lookup($account->uid);
+  if ($domain != -1) {
+    db_delete('domain')
+    ->condition('domain_id', $domain['domain_id'])
+    ->execute();
+    // Let other modules act.
+    module_invoke_all('domainupdate', 'delete', $domain);
   }
 }
 
@@ -296,7 +488,7 @@ function domain_user_strip_chars($name) {
 }
 
 /**
- * Implement hook_domainupdate()
+ * Implements hook_domainupdate().
  */
 function domain_user_domainupdate($op, $domain, $form_state = array()) {
   $root = variable_get('domain_user_root', variable_get('domain_root', ''));
@@ -304,26 +496,40 @@ function domain_user_domainupdate($op, $domain, $form_state = array()) {
     case 'update':
       // If these are different, then we must delete a row from {access}.
       if (isset($form_state['values']['subdomain']) && $domain['subdomain'] != $form_state['values']['subdomain']) {
-        $mask = str_replace('.'. $root, '', $domain['subdomain']);
-        db_query("DELETE FROM {access} WHERE mask = '%s'", $mask);
+        $mask = str_replace('.' . $root, '', $domain['subdomain']);
+        db_delete('access')
+        ->condition('mask', $mask)
+        ->execute();
       }
       domain_user_rules();
       break;
     case 'delete':
-      // Delete from {domain_user}
-      db_query("DELETE FROM {domain_user} WHERE domain_id = %d", $domain['domain_id']);
+      db_delete('domain_user')
+      ->condition('domain_id', $domain['domain_id'])
+      ->execute();
       // Move from user domain to default domain for {domain_editor}
-      $check = db_result(db_query("SELECT COUNT(uid) FROM {domain_editor} WHERE uid = %d AND domain_id = 0", $domain['uid']));
+      $check = db_query("SELECT COUNT(uid) FROM {domain_editor} WHERE uid = :uid AND domain_id = :domain_id", array(':uid' => $domain['uid'], ':domain_id' => 0))->fetchField();
       if (empty($check)) {
-        db_query("INSERT INTO {domain_editor} (domain_id, uid) VALUES (0, %d)", $domain['uid'], $domain['domain_id']);
+        $id = db_insert('domain_editor')
+         ->fields(array(
+          'domain_id' => 0,
+          'uid' => $domain['uid'],
+        ))
+        ->execute();
       }
       else {
-        db_query("DELETE FROM {domain_editor} WHERE uid = %d AND domain_id = %d", $domain['uid'], $domain['domain_id']);
+  
+        db_delete('domain_editor')
+        ->condition('uid', $domain['uid'])
+        ->condition('domain_id', $domain['domain_id'])
+        ->execute();
       }
       // Delete from the access rules.
       $user_root = variable_get('domain_user_root', variable_get('domain_root', ''));
-      $mask = str_replace('.'. $user_root, '', $domain['subdomain']);
-      db_query("DELETE FROM {access} WHERE mask = '%s'", $mask);
+      $mask = str_replace('.' . $user_root, '', $domain['subdomain']);
+      db_delete('access')
+      ->condition('mask', $mask)
+      ->execute();
       break;
   }
 }
@@ -333,6 +539,8 @@ function domain_user_domainupdate($op, $domain, $form_state = array()) {
  *
  * @param $uid
  *  The user id of the domain to be checked. Optional.
+  * @param $category_id
+ *  The domain category to be checked. Optional, defaults to 1.
  * @param $name
  *  The username of the domain to be checked. Optional.
  * @param $domain_id
@@ -340,18 +548,19 @@ function domain_user_domainupdate($op, $domain, $form_state = array()) {
  * @param $clear
  *  A boolean flag to clear the static variable if necessary. Not used.  Here for consistency.
  */
-function domain_user_lookup($uid = NULL, $name = NULL, $domain_id = NULL, $clear = FALSE) {
+function domain_user_lookup($uid = NULL, $category_id = 1, $name = NULL, $domain_id = NULL, $clear = FALSE) {
   if ($uid) {
-    $id = db_result(db_query("SELECT domain_id FROM {domain_user} WHERE uid = %d", $uid));
+    $id = db_query("SELECT domain_id FROM {domain_user} WHERE uid = :uid AND category = :id", array(':uid' => $uid, ':id' => $category_id))->fetchField();
   }
   else if ($name) {
-    $id = db_result(db_query("SELECT du.domain_id FROM {domain_user} du
+    $id = db_query("SELECT du.domain_id FROM {domain_user} du
       INNER JOIN {users} u ON du.uid = u.uid
-      WHERE u.name = '%s'", $name));
+      WHERE u.name = :name AND du.category = :id", array(':name' => $name, ':id' => $category_id))->fetchField();
   }
   else if ($domain_id) {
-    $id = db_result(db_query("SELECT domain_id FROM {domain_user} WHERE domain_id = %d", $domain_id));
+    $id = db_query("SELECT domain_id FROM {domain_user} WHERE domain_id = :domain_id AND category = :id", array(':domain_id' => $domain_id, ':id' => $category_id))->fetchField();
   }
+  
   if (!empty($id)) {
     $return = domain_lookup($id);
   }
@@ -362,9 +571,9 @@ function domain_user_lookup($uid = NULL, $name = NULL, $domain_id = NULL, $clear
 }
 
 /**
- * Implement hook_domainview()
+ * Implements hook_domainview().
  */
-function domain_user_domainview($op, $domain = array()) {
+/* function domain_user_domainview($op, $domain = array()) {
   switch ($op) {
     case 'header':
       return array(array('data' => t('User'), 'field' => 'du.uid'));
@@ -376,9 +585,17 @@ function domain_user_domainview($op, $domain = array()) {
       break;
     case 'data':
       if (isset($domain['uid'])) {
-        $account = user_load(array('uid' => $domain['uid']));
-        return l($account->name, 'user/'. $account->uid);
+        $account = user_load($domain['uid']);
+        return l($account->name, 'user/' . $account->uid);
       }
       break;
   }
+} */
+
+
+/**
+ * Implement hook_views_api().
+ */
+function domain_user_views_api() {
+  return array('api' => 3);
 }
