diff --git a/sites/all/modules/uc_gift_certificate/uc_gift_certificate.admin.inc b/sites/all/modules/uc_gift_certificate/uc_gift_certificate.admin.inc
index 1e6f717..95450aa 100644
--- a/sites/all/modules/uc_gift_certificate/uc_gift_certificate.admin.inc
+++ b/sites/all/modules/uc_gift_certificate/uc_gift_certificate.admin.inc
@@ -2,12 +2,17 @@
 /**
  * Manage all of the gift certificates on record
  */
-function uc_gift_certificate_manage($view_type = 'manage') {
+function uc_gift_certificate_manage($view_type = 'manage',$term = null) {
+ // dpm($view_type);
+ // dpm($term);
   $query = "SELECT gc.* ,u.name as purchasername,u2.name as username, u.mail as purchasermail,u2.mail as usermail
     FROM {uc_gift_certificates} AS gc
     left outer join {users} AS u on gc.purchaser_id = u.uid
     left outer join {users} AS u2 on gc.user_id = u2.uid";
-
+  
+  if ($view_type == 'find'){
+    $query .= " WHERE gc.user_id = %d ";
+  }
   // $result = db_query($query);
   $rows = array();
 
@@ -20,14 +25,14 @@ function uc_gift_certificate_manage($view_type = 'manage') {
     array('sort' => 'asc'),
   );
 
-  $result = pager_query($query.tablesort_sql($header), 200, 0, NULL);
+  $result = pager_query($query.tablesort_sql($header), 200, 0, NULL, $term);
 
   while ($row = db_fetch_object($result)) {
     $rows[] = array($row->name,
                     $row->purchasername." (".$row->purchasermail.")",
-                    $row->username." (".$row->usermail.")",
+                    l($row->username, "user/$row->user_id/gift_certificates/find")." (".$row->usermail.")",
                     $row->value,
-                    l(t('edit'), "admin/store/gift_certificates/$row->certificate_id/edit") . ' ' . l(t('delete'),"admin/store/gift_certificates/$row->certificate_id/delete"),
+                    l(t('log'), "admin/store/gift_certificates/$row->certificate_id/log").' ' .l(t('edit'), "admin/store/gift_certificates/$row->certificate_id/edit") . ' ' . l(t('delete'),"admin/store/gift_certificates/$row->certificate_id/delete"),
                   );
   }
 
@@ -41,6 +46,41 @@ function uc_gift_certificate_manage($view_type = 'manage') {
   return $output;
 }
 
+function uc_gift_certificate_cert_log($certificate_id){
+  $query = "SELECT gcl.*, u.name, u.mail FROM {uc_gift_certificate_chart} gcl LEFT JOIN {users} u ON gcl.user_id = u.uid WHERE gcl.certificate_id = %d ";
+  $header = array(
+    array('data' => t('Certificate ID'), field => 'gcl.certificate_id'),
+    array('data' => t('Action'), 'field' => 'action', 'width' => 50),
+    array('data' => t('User'), 'width' => '230', 'field' => 'username'),
+    array('data' => 'Amount', 'width' => '60', 'field' => 'gcl.amount'),
+    array('data' => 'Order', 'width' => 50, 'field'=> 'gcl.order_id'),
+    array('data' => 'Timestamp', 'width' => 50, 'field'=> 'gcl.timestamp'),
+    array('sort' => 'asc'),
+  );
+
+  $result = pager_query($query.tablesort_sql($header), 200, 0, NULL, $certificate_id);
+
+  while ($row = db_fetch_object($result)) {
+    $rows[] = array($row->certificate_id,
+                    $row->action,
+                    $row->name ." (".$row->mail.")",
+                    $row->amount,
+                    $row->order_id,
+                    date('Y-m-d h:i:s a',$row->timestamp),
+                  );
+  }
+
+  $output = theme('table', $header, $rows).theme('pager', NULL, 20, 0);
+
+  // No gift certificates
+  if ($output == null) {
+    $output = "<p>There are currently no gift certificates in the system.</p>";
+  }
+
+  return $output;
+  
+}
+
 /**
  * Implementation of hook_form
  *
@@ -48,42 +88,25 @@ function uc_gift_certificate_manage($view_type = 'manage') {
  */
 function uc_gift_certificate_add_form($form_state, $certificate_id) {
   $is_add = $certificate_id == 'add';
-  $msg_to_recipient = NULL;
 
   if (!$is_add) {
-    $cert = uc_gift_certificate_load($certificate_id);
+    $value = uc_gift_certificate_load($certificate_id);
 
     $form['certificate_id'] = array(
       '#type' => 'value',
-      '#value' => $cert->certificate_id,
+      '#value' => $value->certificate_id,
     );
-    if (!empty($cert->order_id)) {
-      $order = uc_order_load($cert->order_id);
-      $form['order_id'] = array(
-        '#type' => 'item',
-        '#value' => t('This certificate was created as part of order !order_link', array('!order_link' => l('#' . $cert->order_id, 'admin/store/orders/' . $cert->order_id))),
-        '#weight' => 22,
-      );
-      foreach ($order->products as $product) {
-        if ($product->order_product_id == $cert->order_product_id &&
-            !empty($product->data['attributes']['Message To Recipient'][0])) {
-          $msg_to_recipient = $product->data['attributes']['Message To Recipient'][0];
-          break;
-        }
-      }
-    }
   }
-
   $form['name'] = array(
     '#type' => 'textfield',
     '#title' => t('Gift Certificate Name'),
-    '#default_value' => $cert->name,
+    '#default_value' => $value->name,
     '#weight' => 0,
     '#required' => true,
   );
   $form['cert_code'] = array(
     '#prefix' => t('<b>Certificate Code:</b><br/>'),
-    '#value' => $cert->cert_code,
+    '#value' => $value->cert_code,
     '#weight' => 14,
   );
 
@@ -92,16 +115,16 @@ function uc_gift_certificate_add_form($form_state, $certificate_id) {
     $form['purchaser_id'] = array(
       '#type' => 'select',
       '#title' => t('Purchaser'),
-      '#default_value' => $cert->purchaser_id,
+      '#default_value' => $value->purchaser_id,
       '#options' => uc_gift_certificate_load_users(),
-      '#description' => t('Username of the purchaser of the gift certificate'),
+      '#description' => t('Username of the purchaser of the gift certificate - leave blank to use your current account.'),
       '#weight' => 12,
     );
 
     $form['user_id'] = array(
       '#type' => 'select',
       '#title' => t('Recipient'),
-      '#default_value' => $cert->user_id,
+      '#default_value' => $value->user_id,
       '#options' => uc_gift_certificate_load_users(),
       '#description' => t('Username of the recipient of the gift certificate'),
       '#weight' => 13,
@@ -111,8 +134,8 @@ function uc_gift_certificate_add_form($form_state, $certificate_id) {
     $form['purchaser_id'] = array(
       '#type' => 'textfield',
       '#title' => t('Purchaser'),
-      '#default_value' => uc_gift_certificate_username_from_uid($cert->purchaser_id),
-      '#description' => t('Username of the purchaser of gift certificate'),
+      '#default_value' => uc_gift_certificate_username_from_uid($value->purchaser_id),
+      '#description' => t('Username of the purchaser of gift certificate - leave blank to use your current account.'),
       '#autocomplete_path' => 'user/autocomplete',
       '#weight' => 12,
     );
@@ -120,65 +143,48 @@ function uc_gift_certificate_add_form($form_state, $certificate_id) {
     $form['user_id'] = array(
       '#type' => 'textfield',
       '#title' => t('Recipient'),
-      '#default_value' => uc_gift_certificate_username_from_uid($cert->user_id),
+      '#default_value' => uc_gift_certificate_username_from_uid($value->user_id),
       '#autocomplete_path' => 'user/autocomplete',
       '#description' => t('Username of the recipient of the gift certificate'),
       '#weight' => 13,
     );
   }
+  
+  $form['user_email'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Recipient\'s Email Address'),
+    '#size' => 25,
+    '#default_value' => uc_gift_certificate_useremail_from_uid($value->user_id),
+    '#description' => t('Enter the email address of the user to issue this gift certificate to. Ignored if Purchaser is entered.'),
+    '#weight' => 19,
+    
+  );
+  
   $form['value'] = array(
     '#type' => 'textfield',
     '#title' => t('Value'),
-    '#default_value' => $cert->value,
+    '#default_value' => $value->value,
     '#size' => 25,
     '#description' => t('Amount this gift certificate is worth.'),
     '#required' => true,
     '#weight' => 6,
-  );
+    );
 
 
-  if ($is_add) {
-    $form['new_user'] = array(
-      '#type' => 'fieldset',
-      '#title' => t('Create a new user'),
-      '#collapsible' => TRUE,
-      '#collapsed' => TRUE,
-      '#weight' => 18,
-    );
-    $form['new_user']['new_user_checkbox'] = array(
-      '#type' => 'checkbox',
-      '#title' => t('Create a new user account for the recipient'),
-      '#description' => t('Please check here to create a new user account for the recipient. You must then enter the email of the new user below.'),
-      '#weight' => 18,
-    );
-    $form['new_user']['new_user_email'] = array(
-      '#type' => 'textfield',
-      '#size' => 25,
-      '#title' => t('New user\'s email address'),
-      '#description' => t(''),
-      '#weight' => 19,
-    );
-  }
-  $form['msg_to_recipient'] = array(
-    '#type' => 'textarea',
-    '#title' => t('Message to recipient'),
-    '#default_value' => $msg_to_recipient,
-    '#weight' => 20,
-  );
   $form['mail_user_checkbox'] = array(
     '#type' => 'checkbox',
     '#title' => t('Email the recipient'),
     '#description' => t('Check here to email the recipient the gift certificate.'),
-    '#weight' => 21,
+    '#weight' => 20,
   );
   $form['cancel'] = array(
     '#type' => 'item',
     '#value' => l(t('Cancel and return to Gift Certificate Listing'), 'admin/store/gift_certificates'),
-    '#weight' => 25,
+    '#weight' => 21,
   );
   $form['op'] = array('#type' => 'submit',
     '#value' => t('Submit'),
-    '#weight' => 26,
+    '#weight' => 22,
   );
   return $form;
 }
@@ -188,16 +194,31 @@ function uc_gift_certificate_add_form($form_state, $certificate_id) {
  */
 function uc_gift_certificate_add_form_validate($form, &$form_state) {
   $use_auto = variable_get('uc_use_autocomplete_user_fields', true);
-  $is_new_user = $form_state['values']['new_user_checkbox'];
+  global $user;
   if ($use_auto) {
     $form_state['values']['purchaser_id'] = uc_gift_certificate_uid_from_username($form_state['values']['purchaser_id']);
     $form_state['values']['user_id'] =  uc_gift_certificate_uid_from_username($form_state['values']['user_id']);
   }
 
   if (!db_result(db_query('SELECT uid FROM {users} WHERE uid != 0 AND uid = %d', $form_state['values']['purchaser_id']))) {
-    form_set_error('purchaser_id', t('Purchaser is not a valid user.'));
+    $form_state['values']['purchaser_id'] = $user->uid;
+    //form_set_error('purchaser_id', t('Purchaser is not a valid user.'));
   }
-  if (!$is_new_user && !db_result(db_query('SELECT uid FROM {users} WHERE uid != 0 AND uid = %d', $form_state['values']['user_id']))) {
+  
+  if (empty($form_state['values']['user_id'])) {
+    // look up from email
+    if ($uid = uc_gift_certificate_uid_from_email($form_state['values']['user_email'])) {
+      // we have an existing user
+      $new_user = false;
+      $form_state['values']['user_id'] = $uid;
+    } else {
+      $new_user = true;
+      $form_state['values']['user_id'] = -1;
+    }
+  }
+  
+  if (!$new_user && !db_result(db_query('SELECT uid FROM {users} WHERE uid != 0 AND uid = %d', $form_state['values']['user_id']))) {
+    
     form_set_error('user_id', t('Recipient is not a valid user.'));
   }
   if (empty($form_state['values']['value']) || !is_numeric($form_state['values']['value'])) {
@@ -212,8 +233,9 @@ function uc_gift_certificate_add_form_validate($form, &$form_state) {
 function uc_gift_certificate_add_form_submit($form, &$form_state) {
   $use_auto = variable_get('uc_use_autocomplete_user_fields', true);
   $is_new_cert = !isset($form_state['values']['certificate_id']);
-  $is_new_user = $form_state['values']['new_user_checkbox'];
+  $is_new_user = $form_state['values']['user_id'] == -1;
   $do_mail = $form_state['values']['mail_user_checkbox'];
+  global $user;
 
   //drupal_set_message($form['cert_code']);
   // Make sure we don't generate a new cert code if we are editing an existing certificate.
@@ -224,28 +246,51 @@ function uc_gift_certificate_add_form_submit($form, &$form_state) {
     $cert_code = $form_state['values']['cert_code'];
   }
 
+  $chart = new stdClass();
+  $chart->action = 'admin';
+  $chart->amount = $form_state['values']['value'];
+  $chart->user_id = $user->uid;
+  $chart->order_id = $order->order_id;
+  $chart->timestamp = time();
+
   if ($is_new_cert) {
     $success = drupal_write_record('uc_gift_certificates', $form_state['values']);
     $certificate_id = db_last_insert_id('uc_gift_certificates', 'certificate_id');
     $cert_code = $certificate_id."-".$cert_code;
+    $chart->certificate_id = $certificate_id;
+    
+    
     db_query("UPDATE {uc_gift_certificates} SET cert_code = '%s' WHERE certificate_id = %d", $cert_code, $certificate_id);
   } else {
     $certificate_id = $form_state['values']['certificate_id'];
+    $chart->certificate_id = $certificate_id;
     $success = drupal_write_record('uc_gift_certificates', $form_state['values'], 'certificate_id');
   }
 
   if ($success) {
-    if ($do_mail) {
-      if ($is_new_user) {
-        uc_gift_certificate_mail_cert_notice($form_state['values']['new_user_email'], $certificate_id, $form_state['values']['msg_to_recipient']);
-        drupal_set_message(t('A new user was created and emailed their gift certificate.'));
-      }
-      else {
-        $cert = uc_gift_certificate_load($certificate_id);
-        $user = user_load(array('uid' => $cert->user_id));
-        uc_gift_certificate_mail_cert_notice($user->mail, $certificate_id, $form_state['values']['msg_to_recipient']);
-        drupal_set_message(t('The recipient was emailed their gift certificate.'));
+    drupal_write_record('uc_gift_certificate_chart',$chart);
+    if ($is_new_user) {
+      uc_gift_certificate_mail_cert_notice($form_state['values']['user_email'], $certificate_id);
+      drupal_set_message(t('A new user was created and emailed their gift certificate.'));
+    }
+    if ($do_mail && !$is_new_user) {
+      $gc = uc_gift_certificate_load($certificate_id);
+      $user = user_load(array('uid' => $gc->user_id));
+      $msg_to_recipient = NULL;
+      if (!empty($gc->order_id)) {
+        $order = uc_order_load($gc->order_id);
+        foreach ($order->products as $product) {
+          if ($product->order_product_id == $gc->order_product_id) {
+            $data = $product->data;
+            if (!empty($data['attributes']['Message To Recipient'])) {
+              $msg_to_recipient = $data['attributes']['Message To Recipient'];
+            }
+            break;
+          }
+        }
       }
+      uc_gift_certificate_mail_cert_notice($user->mail, $certificate_id, $msg_to_recipient);
+      drupal_set_message(t('The recipient was emailed their gift certificate.'));
     }
 
     if ($is_new_cert) {
@@ -277,13 +322,20 @@ function uc_gift_certificate_delete_confirm($form_state, $cid) {
  */
 function uc_gift_certificate_delete_confirm_submit($form, &$form_state) {
   $cert_id = $form_state['values']['cid'];
-  $query = "DELETE FROM {uc_gift_certificates} WHERE certificate_id = '" . $cert_id . "'";
-  if (db_query($query)) {
+  $query = "DELETE FROM {uc_gift_certificates} WHERE certificate_id = '%s'";
+  if (db_query($query, $cert_id)) {
     drupal_set_message("Gift Certificate Deleted Successfully");
   }
   else {
     drupal_set_message("Error deleting gift certificate");
   }
+  $query = "DELETE FROM {uc_gift_certificate_chart} WHERE certificate_id = '%s' ";
+  if (db_query($query, $cert_id)) {
+    drupal_set_message("Gift Certificate History Deleted Successfully");
+  }
+  else {
+    drupal_set_message("Error deleting gift certificate history");
+  }
   $form_state['redirect'] = 'admin/store/gift_certificates';
 }
 
diff --git a/sites/all/modules/uc_gift_certificate/uc_gift_certificate.info b/sites/all/modules/uc_gift_certificate/uc_gift_certificate.info
index 2d3e4d2..5a5b41b 100644
--- a/sites/all/modules/uc_gift_certificate/uc_gift_certificate.info
+++ b/sites/all/modules/uc_gift_certificate/uc_gift_certificate.info
@@ -12,9 +12,9 @@ project = "uc_gift_certificate"
 datestamp = "1237005104"
 core = 6.x
 
-; Information added by drupal.org packaging script on 2010-02-09
-version = "6.x-1.x-dev"
+; Information added by drupal.org packaging script on 2009-12-16
+version = "6.x-1.1"
 core = "6.x"
 project = "uc_gift_certificate"
-datestamp = "1265674694"
+datestamp = "1260995491"
 
diff --git a/sites/all/modules/uc_gift_certificate/uc_gift_certificate.install b/sites/all/modules/uc_gift_certificate/uc_gift_certificate.install
index 223773e..d98a7e7 100644
--- a/sites/all/modules/uc_gift_certificate/uc_gift_certificate.install
+++ b/sites/all/modules/uc_gift_certificate/uc_gift_certificate.install
@@ -63,6 +63,66 @@ function uc_gift_certificate_schema() {
     'primary key' => array('certificate_id'),
   );
 
+  $schema['uc_gift_certificate_chart'] = array(
+    'description' => t('A log of all activity on a certificate balance, for an audit trail.'),
+    'fields' => array(
+      'trans_id' => array(
+        'description' => t('The transaction id, pk for this table.'),
+        'type' => 'serial',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+      ),
+      'certificate_id' => array(
+        'description' => t('The certificate id.'),
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+      ),
+      'action' => array(
+        'description' => t('Action taken on this line - one of purchase, redeem, admin, import.'),
+        'type' => 'varchar',
+        'length' => 255,
+        'not null' => TRUE,
+        'default' => '',
+      ),
+      'amount' => array(
+        'description' => t('Amount of change in this transaction.'),
+        'type' => 'numeric',
+        'precision' => 15,
+        'scale' => 3,
+        'not null' => TRUE,
+        'default' => 0.0,
+      ),
+      'user_id' => array(
+        'description' => t('The identifier of the user taking this action.'),
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+        'default' => 0,
+      ),
+       'order_id' => array(
+        'description' => t('The identifier of the order.'),
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+        'default' => 0,
+      ),
+       'timestamp' => array(
+        'description' => t('The UNIX Timestamp time this item took place.'),
+        'type' => 'int',
+        'not null' => TRUE,
+        'default' => 0,
+      ),
+ 
+    ),
+    'primary key' => array('trans_id'),
+    'indexes' => array(
+      'orders' => array('order_id'),
+      'users' => array('user_id'),
+      'certs' => array('certificate_id'),
+    ),
+  );
+  
   return $schema;
 }
 
@@ -103,3 +163,77 @@ function uc_gift_certificate_update_6003() {
   db_query("UPDATE {uc_attributes} SET required=1 WHERE name LIKE 'Recipient''s Email Address'");
   return $ret;
 }
+
+function uc_gift_certificate_update_6004() {
+  $schema['uc_gift_certificate_chart'] = array(
+    'description' => t('A log of all activity on a certificate balance, for an audit trail.'),
+    'fields' => array(
+      'trans_id' => array(
+        'description' => t('The transaction id, pk for this table.'),
+        'type' => 'serial',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+      ),
+      'certificate_id' => array(
+        'description' => t('The certificate id.'),
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+      ),
+      'action' => array(
+        'description' => t('Action taken on this line - one of purchase, redeem, admin, import.'),
+        'type' => 'varchar',
+        'length' => 255,
+        'not null' => TRUE,
+        'default' => '',
+      ),
+      'amount' => array(
+        'description' => t('Amount of change in this transaction.'),
+        'type' => 'numeric',
+        'precision' => 15,
+        'scale' => 3,
+        'not null' => TRUE,
+        'default' => 0.0,
+      ),
+      'user_id' => array(
+        'description' => t('The identifier of the user taking this action.'),
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+        'default' => 0,
+      ),
+       'order_id' => array(
+        'description' => t('The identifier of the order.'),
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+        'default' => 0,
+      ),
+       'timestamp' => array(
+        'description' => t('The UNIX Timestamp time this item took place.'),
+        'type' => 'int',
+        'not null' => TRUE,
+        'default' => 0,
+      ),
+ 
+    ),
+    'primary key' => array('trans_id'),
+    'indexes' => array(
+      'orders' => array('order_id'),
+      'users' => array('user_id'),
+      'certs' => array('certificate_id'),
+    ),
+  );
+  $ret = array();
+  db_create_table($ret, 'uc_gift_certificate_chart',$schema['uc_gift_certificate_chart']);
+  cache_clear_all('schema','cache');
+  return $ret;
+  
+}
+
+
+function uc_gift_certificate_update_6005() {
+  $ret = array();
+  db_query("insert into uc_gift_certificate_chart (certificate_id, action, amount, user_id, order_id, `timestamp`) (select certificate_id, 'import', `value` as amount, user_id, order_id, unix_timestamp() as `timestamp` from uc_gift_certificates)");
+  return $ret;
+}
diff --git a/sites/all/modules/uc_gift_certificate/uc_gift_certificate.js b/sites/all/modules/uc_gift_certificate/uc_gift_certificate.js
index 366495a..fe3f7cd 100644
--- a/sites/all/modules/uc_gift_certificate/uc_gift_certificate.js
+++ b/sites/all/modules/uc_gift_certificate/uc_gift_certificate.js
@@ -1,97 +1,81 @@
-function getCert() {
-  $('#certificate-message').remove();
-
-  var code = $('#edit-panes-cert-code');
-  $.get(Drupal.settings.base_path + "?q=cart/checkout/certificate/" + encodeURIComponent(code.val()), {}, function(certificate) {
-    if (certificate.valid) {
-      if (window.set_line_item) {
-        set_line_item('gift_certificate', certificate.title, -certificate.amount, 6);
-      }
-    }
-    else {
-      code.parent().next().after('<div id="certificate-message">' + certificate.message + '</div>');
-      if (window.remove_line_item) {
-        remove_line_item('gift_certificate');
-      }
-    }
-
-    if (window.getTax) {
-      getTax();
-    }
-    else if (window.render_line_items) {
-      render_line_items();
-    }
-  }, 'json');
-}
-
-/** Apply a Discount **/
-function getCertDiscount() {
-  $('#certificate-message').remove();
 
-  var code = $('#edit-panes-cert-certificate-user');
-  $.get(Drupal.settings.base_path + "?q=cart/checkout/get_certificate_discount/" + encodeURIComponent(code.val()), {}, function(certificate) {
-    if (certificate.valid) {
-      if (window.set_line_item) {
-        set_line_item('gift_certificate', certificate.title, -certificate.amount, 6);
-        $('#edit-panes-cert-certificate-user-value').val(-certificate.amount)
+var uc_gc = {
+  amount: 0, // Total amount of user's gift certificate credit
+  
+  total: 0, // current order total balance
+  
+  applied: 0, // current amount of gift certificate applied to this order
+  timeout: null,
+  
+  update_balance: function() { // use absolute paths, scope not guaranteed
+    
+    uc_gc.total = parseFloat($('#edit-panes-payment-current-total').val());
+    var orig_applied = uc_gc.applied;
+    if (uc_gc.amount > 0){
+      // only do anything if we have a gc balance
+      if (uc_gc.total > 0) {
+        // check to see if we've applied the full gc amount
+        if (uc_gc.amount != uc_gc.applied){
+          // update applied amount
+          if (uc_gc.amount > uc_gc.total + uc_gc.applied) {
+            uc_gc.applied = uc_gc.total + uc_gc.applied;
+            uc_gc.total = 0;
+          } else {
+            uc_gc.applied = uc_gc.amount;
+          }
+        } // else we've already gotten the correct amount
+        
+      } else if (uc_gc.total < 0) {
+        // don't apply so much
+        if (uc_gc.applied > 0){
+          uc_gc.applied = uc_gc.applied + uc_gc.total; // total is negative...
+          uc_gc.total = 0;
+        }
       }
-    }
-    else {
-      code.parent().next().after('<div id="certificate-message">' + certificate.message + '</div>');
-      if (window.remove_line_item) {
-        remove_line_item('gift_certificate');
+      
+      // now update payment options...
+      
+      if (uc_gc.total > 0) {
+          $("#payment-pane .form-radios input:radio").removeAttr('disabled').parent().show(0);
+          $("input:radio[@value=zero_total]").attr('disabled','disabled').removeAttr('checked').parent().hide(0);
+        }
+        else {
+          $("#payment-pane .form-radios input:radio").attr('disabled', 'disabled').parent().hide(0);
+          $("input:radio[@value=zero_total]").removeAttr('disabled').attr('checked', 'checked').parent().show(0);
+          
+        }
+      if (orig_applied != uc_gc.applied){
+          set_line_item("gift_certificate", 'Gift Certificates', -uc_gc.applied, 10);
       }
     }
 
-    if (window.getTax) {
-      getTax();
-    }
-    else if (window.render_line_items) {
-      render_line_items();
-    }
-  }, 'json');
-}
-
-
+  }
+  
+};
 
-function getCertificate(path) {
+/*
+ * Main goal: Add/update a line item for gift certificate, and enable/disable payment methods based on current total
+ */
+function getCertificate() {
   var progress = new Drupal.progressBar('certificateProgress');
   progress.setProgress(-1, '');
   $('#certificate_details').empty().append(progress.element).removeClass('display-none');
   $("#certificate_details").addClass("solid-border").css("margin-top", "1em");
 
   var subtotal = $('#edit-panes-payment-current-total').val();
-
+  uc_gc.total = subtotal;
+  
   // Make the post to get the details for the chosen payment method.
-  $.post(path, { },
+  $.post('/cart/checkout/certificate-balance', { },
     function(details) {
-      // details_tab : [0] : Discount validity | [1] : Discount sentense | [2] Discount id | [3] Discount code | [4] Formated discounted amount | [5] Discounted amount | [6] Weight
-      var details_tab = details.split('|');
-
-      if (details_tab[0] == false) {
-        $('#certificate_details').empty().html(details_tab[1]);
-      }
-
-      // Otherwise display the returned details.
-      else {
-        // Disable the "Add Certificate" button.
-        $('#uc-cart-checkout-form input#edit-panes-cert-certificate-get').attr('disabled', 'disabled');
-
         // If the amount of the certificate is less than the subtotal,
         // .. use up the certificates. (This will leave a difference).
-        var amount = 0;
+        uc_gc.amount = details.total;
+        
+        uc_gc.update_balance();
 
-        if (subtotal > details_tab[4]) {
-          amount = details_tab[4];
-        }
-        else {
-          amount = subtotal;
-        }
-
-        $('#certificate_details').empty().append('<span class="message">'+ details_tab[1] + '</span><span class="label">' + details_tab[3] + '</span><span class="price"> = ' + details_tab[4] + '</span>');
-        set_line_item("gift_certificate", 'Gift Certificates', -amount, 2);
-      }
-    }
+      },
+      'json'
   );
 }
 
@@ -102,17 +86,19 @@ var using_certificate = -1;
 // Adds a click function to the total so we can check its updated values.
 $(document).ready(
   function() {
-    $('#edit-panes-payment-current-total').click(function() { uc_gift_certificate_check_total(this.value); });
+    getCertificate();
+    $('#edit-panes-payment-current-total').bind('click change', uc_gc.update_balance ); //function() { uc_gift_certificate_check_total(uc_gc.value); });
   }
 );
 
+
 /**
  * Checks the current total and updates the available/selected payment methods
  * accordingly.
  */
 function uc_gift_certificate_check_total(total) {
   total = parseFloat(total);
-
+console.log('gc check total');
   if (total >= .01) {
 
   }
diff --git a/sites/all/modules/uc_gift_certificate/uc_gift_certificate.module b/sites/all/modules/uc_gift_certificate/uc_gift_certificate.module
index 3f8f6fc..c781eba 100644
--- a/sites/all/modules/uc_gift_certificate/uc_gift_certificate.module
+++ b/sites/all/modules/uc_gift_certificate/uc_gift_certificate.module
@@ -7,7 +7,7 @@
  */
 module_load_include('inc', 'uc_gift_certificate', 'uc_gift_certificate.user');
 // Conditional Actions not fully ported over yet
-//module_load_include('inc', 'uc_gift_certificate', 'uc_gift_certificate.ca');
+module_load_include('inc', 'uc_gift_certificate', 'uc_gift_certificate.ca');
 
 /**
  * Implementation of hook_perm().
@@ -41,22 +41,24 @@ function uc_gift_certificate_menu() {
     'access arguments' => array('access content'),
     'type' => MENU_SUGGESTED_ITEM,
   );
-  $items['my_gift_certificates'] = array(
-    'title' => 'Send Gift Certificates',
-    'description' => 'Issue Gift Certificates',
-    'page callback' => 'uc_gift_certificate_issue',
-    'access arguments' => array('access content'),
-    'type' => MENU_CALLBACK,
-  );
   $items['admin/store/gift_certificates'] = array(
     'title' => 'Gift Certificates',
     'description' => 'Manage Gift Certificates',
     'page callback' => 'uc_gift_certificate_manage',
     'file' => 'uc_gift_certificate.admin.inc',
-    'page arguments' => array('manage'),
+    'page arguments' => array(3,4),
     'access arguments' => array('administer gift certificates'),
     'type' => MENU_NORMAL_ITEM,
   );
+  $items['user/%/gift_certificates/find'] = array(
+     'title' => 'Gift Certificates',
+    'description' => 'Manage Gift Certificates',
+    'page callback' => 'uc_gift_certificate_manage',
+    'file' => 'uc_gift_certificate.admin.inc',
+    'page arguments' => array(3,1),
+    'access arguments' => array('administer gift certificates'),
+    'type' => MENU_LOCAL_TASK,
+  );
   $items['admin/store/gift_certificates/list'] = array(
     'title' => 'Gift Certificates',
     'description' => 'Manage Gift Certificates',
@@ -76,6 +78,13 @@ function uc_gift_certificate_menu() {
     'type' => MENU_LOCAL_TASK,
     'weight' => 10,
   );
+  $items['admin/store/reports/gift_certificates'] = array(
+    'title' => 'Gift Certificate reports',
+    'description' => 'View gift certificate reports.',
+    'page callback' => 'uc_gift_certificate_reports',
+    'access arguments' => array('view reports'),
+    'type' => MENU_NORMAL_ITEM,
+  );
   $items['gift_certificates/%/issue'] = array(
     'title' => 'Issue Gift Certificate',
     'description' => 'Issue the gift certificate to a user',
@@ -94,6 +103,15 @@ function uc_gift_certificate_menu() {
     'access arguments' => array('administer store'),
     'type' => MENU_CALLBACK,
   );
+  $items['admin/store/gift_certificates/%/log'] = array(
+    'title' => 'Certificate Activity Log',
+    'description' => 'View the activity around a particular certificate',
+    'page callback' => 'uc_gift_certificate_cert_log',
+    'page arguments' => array(3),
+    'file' => 'uc_gift_certificate.admin.inc',
+    'access arguments' => array('administer store'),
+    'type' => MENU_CALLBACK,
+  );
   $items['admin/store/gift_certificates/%/delete'] = array(
     'title' => 'Delete Gift Certificate',
     'description' => 'Delete Gift Certificate',
@@ -119,6 +137,14 @@ function uc_gift_certificate_menu() {
     'access arguments' => array('access content'),
     'type' => MENU_CALLBACK,
   );
+  $items['cart/checkout/certificate-balance'] = array(
+    'title' => 'Certificate Balance for user',
+    'description' => 'Certificate details.',
+    'page callback' => 'uc_gift_certificate_user_balance_json',
+    'page arguments' => array(),
+    'access arguments' => array('access content'),
+    'type' => MENU_CALLBACK,
+  );
   return $items;
 }
 
@@ -236,14 +262,7 @@ function uc_gift_certificate_mail_cert_notice($mail, $certificate_id, $msg_to_re
 }
 
 function uc_gift_certificate_checkout_pane() {
-  $panes[] = array(
-    'id' => 'certificate_discount',
-    'callback' => 'uc_gift_certificate_pane_coupon_discount',
-    'title' => t('Certificate Discount'),
-    'desc' => t('Allows shoppers to use a gift certificate during checkout for order discounts.'),
-    'weight' => 5,
-    'process' => TRUE,
-  );
+
   $panes[] = array(
     'id' => 'gift_certificate',
     'callback' => 'uc_checkout_pane_gift_certificate',
@@ -279,28 +298,6 @@ function uc_checkout_pane_gift_certificate($op, &$arg1, $arg2) {
   }
 }
 
-function uc_gift_certificate_pane_coupon_discount($op, &$arg1, $arg2) {
-  switch ($op) {
-
-    case 'view':
-
-      $description = t('Enter a Gift Certificate for this order.');
-      $contents['certificate_code'] = array(
-        '#type' => 'textfield',
-        '#title' => t('Coupon code'),
-        '#default_value' => $arg1->data['certificate_code'],
-        '#size' => 25,
-      );
-      return array('description' => $description, 'contents' => $contents);
-    case 'process':
-      $arg1->data['certificate_code'] = $arg2['certificate_code'];
-      return TRUE;
-    case 'review':
-
-
-      break;
-  }
-}
 
 /**
  * Callback function for the discount line item.
@@ -399,10 +396,10 @@ function uc_gift_certificate_cert_checkout($op, $arg1, $arg2) {
   global $user;
 
 
-//drupal_set_message('Op: '.$op.' Arg2: <pre>'.print_r($arg2, true).'</pre>');
+drupal_set_message('Op: '.$op.' Arg2: <pre>'.print_r($arg2, true).'</pre>');
   switch ($op) {
     case 'view':
-      uc_add_js(drupal_get_path('module', 'uc_gift_certificate') .'/uc_gift_certificate.js');
+      drupal_add_js(drupal_get_path('module', 'uc_gift_certificate') .'/uc_gift_certificate.js');
 
       if ($arg1->data['gift_certificate'] != '') {
         $certificate = uc_gift_certificate_validate($arg1->data['gift_certificate']);
@@ -414,7 +411,7 @@ function uc_gift_certificate_cert_checkout($op, $arg1, $arg2) {
       }
 
       if ($certificate->valid) {
-        uc_add_js('$(document).ready(function() {
+        drupal_add_js('$(document).ready(function() {
           if (window.set_line_item) {
             set_line_item("gift_certificate", "'. $certificate->title .'", '. -$certificate->amount .', 9);
             render_line_items();
@@ -544,7 +541,7 @@ function uc_gift_certificate_cert_checkout($op, $arg1, $arg2) {
         drupal_set_message('Discount applied: '.$arg2['certificate-user-value']);
         $certificate = uc_gift_certificate_validate_user($arg2['certificate-user']);
         if ($certificate->valid) {
-          uc_add_js('$(document).ready(function() {
+          drupal_add_js('$(document).ready(function() {
             if (window.set_line_item) {
               set_line_item("gift_certificate", "'. $certificate->title .'", '. -$certificate->amount .', 9);
               render_line_items();
@@ -579,26 +576,6 @@ function uc_gift_certificate_cert_checkout($op, $arg1, $arg2) {
 }
 
 /**
- * Implementation of hook_add_to_cart()
- *
- * Validate that when a gift cert is added the email address is valid
- */
-function uc_gift_certificate_add_to_cart($nid, $qty, $data) {
-  $node = node_load($nid);
-  if (!empty($node->attributes)) {
-    foreach ($node->attributes as $key => $attrib) {
-      if ($attrib->name == "Recipient's Email Address" && !valid_email_address($data['attributes'][$key])) {
-        $result[] = array(
-          'success' => FALSE,
-          'message' => t("Recipient's Email Address is not a valid email address."),
-        );
-        return $result;
-      }
-    }
-  }
-}
-
-/**
  * Implementation of hook_order()
  */
 function uc_gift_certificate_order($op, &$arg1, $arg2) {
@@ -625,7 +602,7 @@ function uc_gift_certificate_order($op, &$arg1, $arg2) {
         $certificate_amount = abs(db_result(db_query("SELECT SUM(amount) FROM {uc_order_line_items} WHERE `type` = 'gift_certificate' AND order_id = %d", $arg1->order_id)));
         // If so, refund them to the user.
         if ($certificate_amount) {
-          db_query("UPDATE {uc_gift_certificates} SET value = value + %f WHERE order_id = %d AND user_id = %d LIMIT 1", $certificate_amount, $arg1->order_id, $arg1->uid);
+          db_query("UPDATE {uc_gift_certificates} SET value = value + %d WHERE order_id = %d AND user_id = %d LIMIT 1", $certificate_amount, $arg1->order_id, $arg1->uid);
           uc_order_comment_save($arg1->order_id, 0, t('Refunded gift certificates worth !value.', array('!value' => uc_currency_format($certificate_amount))));
         }
 
@@ -642,7 +619,9 @@ function uc_gift_certificate_order($op, &$arg1, $arg2) {
     case 'delete':
       db_query("DELETE FROM {uc_gift_certificates} WHERE order_id = %d", $arg1->order_id);
       break;
-
+    
+    case 'total':
+      break;
     case 'save':
       $certificates = uc_gift_certificate_total($arg1->uid);
       // Automatically apply gift certificates
@@ -692,6 +671,14 @@ function uc_gift_certificate_line_item() {
  */
 function uc_gift_certificate_create_new_certs($order_id) {
   $order = uc_order_load($order_id);
+  
+  $qry = "SELECT * FROM {uc_gift_certificate_chart} WHERE order_id = %d AND action = 'purchase'";
+  $result = db_query($qry, $order_id);
+  if (db_fetch_object($result)){
+    watchdog('certificate','Gift certificate already purchased for order # %d.',array($order_id));
+    drupal_set_message('Certificates already purchased, not re-issuing.');
+    return false;
+  }
 
   foreach ($order->products as $product) {
     if ($product->data){
@@ -699,7 +686,7 @@ function uc_gift_certificate_create_new_certs($order_id) {
       // Check if the product is a gift certificate
       if ($data && $data['attributes'] && isset($data['attributes']["Recipient's Email Address"][0])){
         $data['attributes']['Certificate Code'][0] = '';
-        $title = t('@gc_title for order #@order_id', array('@gc_title' => $product->title, '@order_id' => $order_id));
+        $title = t('@gc_title purchased by @first_name @last_name', array('@gc_title' => $product->title, '@first_name' => $order->billing_first_name, '@last_name' => $order->billing_last_name));
         // Generate a random code and insert the certificate. First delete other certificates for this order_id
         $new_gc = new stdClass();
         $new_gc->name = $title;
@@ -711,7 +698,14 @@ function uc_gift_certificate_create_new_certs($order_id) {
           $certificate_id = db_last_insert_id('uc_gift_certificates', 'certificate_id');
           $cert_code = $certificate_id ."-". uc_gift_certificate_mKey();
           db_query("UPDATE {uc_gift_certificates} SET cert_code = '%s' WHERE certificate_id = %d", $cert_code, $certificate_id);
-
+          $chart = new stdClass();
+          $chart->certificate_id = $new_gc->certificate_id;
+          $chart->action = 'purchase';
+          $chart->amount = $new_gc->value;
+          $chart->user_id = $new_gc->purchaser_id;
+          $chart->order_id = $new_gc->order_id;
+          $chart->timestamp = time();
+          drupal_write_record('uc_gift_certificate_chart', $chart);
           // If this is an electronic certificate, send an email.
           if (isset($data['attributes']["Recipient's Email Address"][0])) {
             $mail = $data['attributes']["Recipient's Email Address"][0];
@@ -741,6 +735,15 @@ function uc_gift_certificate_create_new_certs($order_id) {
  * Update gift certificate amounts
  */
 function uc_gift_certificate_update_cert_vals($order_id) {
+  
+  $qry = "SELECT * FROM {uc_gift_certificate_chart} WHERE order_id = %d AND action = 'redeem'";
+  $result = db_query($qry, $order_id);
+  if (db_fetch_object($result)){
+    watchdog('certificate','Gift certificate already redeemed for order # %d.',array($order_id));
+    drupal_set_message('Certificates already redeemed, not updating. Certificate Balance must be updated manually.');
+    return false;
+  }
+
   $num_rows = db_result(db_query("SELECT COUNT(*) FROM {uc_order_line_items} WHERE order_id = %d AND type ='gift_certificate'", $order_id));
 
   if ($num_rows > 1) {
@@ -777,6 +780,15 @@ function uc_gift_certificate_update_cert_vals($order_id) {
       $new_cert_val = $cert_val - $deduct_from_cert;
 
       if (db_query("UPDATE {uc_gift_certificates} SET value  = %f, order_id = %d WHERE certificate_id = %d", $new_cert_val, $order_id, $cert->certificate_id)) {
+        $chart = new stdClass();
+        $chart->certificate_id = $cert->certificate_id;
+        $chart->action = 'redeem';
+        $chart->amount = - $deduct_from_cert;
+        $chart->user_id = $user_id;
+        $chart->order_id = $order_id;
+        $chart->timestamp = time();
+        drupal_write_record('uc_gift_certificate_chart', $chart);
+
         $user = user_load(array('uid' => $user_id));
 
         //  drupal_set_message('updated cert '.$cert->certificate_id .' to '.$new_cert_val);
@@ -838,7 +850,7 @@ function uc_payment_method_zero_total($op, &$arg1, $silent = FALSE) {
          if ($certificates >= $total) {
            $certificates = $total;
 
-           uc_add_js('$(document).ready(function() {
+           drupal_add_js('$(document).ready(function() {
              if (window.set_line_item) {
                set_line_item("gift_certificate", "'. t('Gift Certificates') .'", '. -$certificates .', 6);
              }
@@ -1071,6 +1083,18 @@ function uc_gift_certificate_apply($code = NULL) {
   exit();
 }
 
+/*
+ * Return the user certificate balance
+ */
+function uc_gift_certificate_user_balance_json(){
+  global $user;
+  
+  $total = uc_gift_certificate_total($user->uid);
+  $out['total'] = $total;
+  drupal_json($out);
+  exit();
+}
+
 /**
  * Apply the Certificate at checkout as a DISCOUNT
  */
@@ -1186,6 +1210,130 @@ function uc_gift_certificate_total($uid) {
   return $total;
 }
 
+
+/**
+ * Coupon report form.
+ */
+function uc_gift_certificate_reports_form(&$form_state, $start = NULL, $end = NULL, $statuses = NULL) {
+  if (is_null($start)) {
+    $start = time();
+  }
+  if (is_null($end)) {
+    $end = time();
+  }
+  if (is_null($statuses)) {
+    $statuses = variable_get('uc_reports_reported_statuses', array('completed'));
+  }
+
+  $options = array();
+  foreach (uc_order_status_list() as $status) {
+    $options[$status['id']] = $status['title'];
+  }
+
+  $form['start'] = array(
+    '#type' => 'date',
+    '#title' => t('Start date'),
+    '#default_value' => array('year' => format_date($start, 'custom', 'Y'), 'month' => format_date($start, 'custom', 'n'), 'day' => format_date($start, 'custom', 'j')),
+    '#after_build' => array('_uc_coupon_date_range'),
+  );
+  $form['end'] = array(
+    '#type' => 'date',
+    '#title' => t('End date'),
+    '#default_value' => array('year' => format_date($end, 'custom', 'Y'), 'month' => format_date($end, 'custom', 'n'), 'day' => format_date($end, 'custom', 'j')),
+    '#after_build' => array('_uc_coupon_date_range'),
+  );
+  $form['status'] = array(
+    '#type' => 'select',
+    '#title' => t('Order statuses'),
+    '#description' => t('Only orders with selected statuses will be included in the report.') .'<br />'. t('Hold Ctrl + click to select multiple statuses.'),
+    '#options' => $options,
+    '#default_value' => $statuses,
+    '#multiple' => TRUE,
+    '#size' => 5,
+  );
+  $form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => t('Display report'),
+  );
+  return $form;
+}
+
+/**
+ * Handle form submit and assign variables
+ */
+function uc_gift_certificate_reports_form_submit($form, &$form_state) {
+  $start = mktime(0, 0, 0, $form_state['values']['start']['month'], $form_state['values']['start']['day'], $form_state['values']['start']['year']);
+  $end = mktime(23, 59, 59, $form_state['values']['end']['month'], $form_state['values']['end']['day'], $form_state['values']['end']['year']);
+  $statuses = implode(',', array_keys($form_state['values']['status']));
+
+  $form_state['redirect'] = 'admin/store/reports/gift_certificates/'. $start .'/'. $end .'/'. $statuses;
+}
+
+
+/**
+ * Output Coupon Reports
+ *
+ * TODO: Integrate with UberCart reports functionality.
+ */
+function uc_gift_certificate_reports($start = NULL, $end = NULL, $statuses = NULL) {
+  drupal_add_css(drupal_get_path('module', 'uc_coupon') .'/reports.css', 'uc_coupon');
+
+  if (is_null($statuses)) {
+    $statuses = variable_get('uc_reports_reported_statuses', array('completed'));
+  }
+  else {
+    $statuses = explode(',', $statuses);
+  }
+
+  $output = drupal_get_form('uc_gift_certificate_reports_form', $start, $end, $statuses);
+
+  if (isset($start) && isset($end)) {
+    $query = db_query("SELECT gcr.certificate_id, u.name,gcr.user_id, gcr.amount, gcr.order_id, o.order_total, o.created FROM {uc_gift_certificate_chart} AS gcr LEFT JOIN {uc_orders} AS o ON (gcr.order_id = o.order_id) LEFT JOIN {users} u ON gcr.user_id = u.uid WHERE gcr.action = 'redeem' AND o.created > %d AND o.created < %d AND o.order_status IN ('". implode("', '", $statuses) ."') ORDER BY o.created ASC", $start, $end);
+    $total = 0;
+
+    $row_header = array(t('Order #'), t('Purchase date'), t('Total'), t('Coupon value'),t('User name'));
+    $last_cid = 0;
+
+    while ($row = db_fetch_object($query)) {
+      // Display the table of coupons if this is the next set of coupons
+      //if ($row->certificate_id != $last_cid AND $last_cid != 0) {
+      //  $td[] = array('', '<b>'. t('Uses: @total', array('@total' => $num_uses)) .'</b>', '<b>'. uc_currency_format($coupon_sale_amount) .'</b>', '<b>'. uc_currency_format($coupon_amount) .'</b>');
+      //  $data .= theme('table', $row_header, $td, array('width' => '100%'));
+      //  $td = array();
+      //  $num_uses = 0;
+      //  $coupon_amount = 0;
+      //  $coupon_sale_amount = 0;
+      //}
+      // if this is the first coupon of the set display the header first
+      //if ($row->certificate_id != $last_cid || $last_cid = 0) {
+      //  $data .= '<div class="totals">'. t('Coupon code: !link', array('!link' => l($row->code, 'admin/store/customers/coupon/'. $row->certificate_id .'/edit'))) .'</div>';
+      //}
+      $td[] = array(l('#'. $row->order_id, 'admin/store/orders/'. $row->order_id), format_date($row->created, 'custom', variable_get('uc_date_format_default', 'm/d/Y')), uc_currency_format($row->order_total), uc_currency_format($row->amount),
+                    l($row->name,'user/'.$row->user_id));
+      $num_uses++;
+      $coupon_amount += $row->amount;
+      $coupon_sale_amount += $row->order_total;
+      $last_cid = $row->certificate_id;
+      $orders_total += $row->order_total;
+      $coupons_total += $row->amount;
+      $total++;
+    }
+    $td[] = array('', '<b>'. t('Uses: @total', array('@total' => $num_uses)) .'</b>', '<b>'. uc_currency_format($coupon_sale_amount) .'</b>', '<b>'. uc_currency_format($coupon_amount) .'</b>');
+    $data .= theme('table', $row_header, $td, array('width' => '100%'));
+
+    $output .= '<h2>'. t('Gift Certificates redeemed report') .'</h2>';
+    $output .= $data;
+    $output .= '<br /><table width="100%"><tr>';
+    $output .= '<td>'. t('Orders with Gift Certificates used: @total', array('@total' => $total)) .'</td>';
+    $output .= '<td>'. t('Orders total: @total', array('@total' => uc_currency_format($orders_total))) .'</td>';
+    $output .= '<td>'. t('Certificates total: @total', array('@total' => uc_currency_format($coupons_total))) .'</td>';
+    $output .= '</tr></table>';
+  }
+  return $output;
+}
+
+
+
 /**
  * Settings for gift certificate text field options
  */
diff --git a/sites/all/modules/uc_gift_certificate/uc_gift_certificate.user.inc b/sites/all/modules/uc_gift_certificate/uc_gift_certificate.user.inc
index 979becb..5b67c35 100644
--- a/sites/all/modules/uc_gift_certificate/uc_gift_certificate.user.inc
+++ b/sites/all/modules/uc_gift_certificate/uc_gift_certificate.user.inc
@@ -20,6 +20,13 @@ function uc_gift_certificate_uid_from_username($name){
   }
   return false;
 }
+function uc_gift_certificate_uid_from_email($email){
+  $result = db_query("SELECT uid FROM {users} WHERE mail = '%s'", $email);
+  if ($user = db_fetch_object($result)) {
+    return $user->uid;
+  }
+  return false;
+}
 
 /**
  * Update the user a certificate belongs to
@@ -45,6 +52,16 @@ function uc_gift_certificates_gift($user, $amount) {
   $certificate_id = db_last_insert_id('uc_gift_certificates', 'certificate_id');
   $cert_code = $certificate_id."-".$cert_code;
   db_query("UPDATE {uc_gift_certificates} SET cert_code = '%s' WHERE certificate_id = %d", $cert_code, $certificate_id);
+
+  $order = uc_order_load($_SESSION['cart_order']);
+  $chart = new stdClass();
+  $chart->certificate_id = $certificate_id;
+  $chart->action = 'purchase';
+  $chart->amount = $amount;
+  $chart->user_id = $user->uid;
+  $chart->order_id = $order->order_id;
+  $chart->timestamp = time();
+  drupal_write_record('uc_gift_certificate_chart',$chart);
   uc_order_comment_save($order->order_id, $user->uid, t('Added gift certificate !code worth !value.', array('!code' => $cert_code, '!value' => uc_currency_format($amount))), 'admin');
   return array('cert_code' => $cert_code, 'cert_id' => $certificate_id);
 }
@@ -54,6 +71,7 @@ function uc_gift_certificates_gift($user, $amount) {
  */
 function uc_gift_certificate_reverse($order_id) {
 
+  // TODO !
 }
 
 /**
@@ -126,7 +144,8 @@ function uc_gift_certificate_user($op, $edit, &$account, $category = NULL) {
   global $user;
   switch ($op) {
     case 'view':
-      if (($account->uid == $user->uid || user_access('administer gift certificates')) && $total = uc_gift_certificate_total($account->uid)) {
+      $total = uc_gift_certificate_total($account->uid);
+      if (($account->uid == $user->uid && $total ) || user_access('administer gift certificates')) {
         $account->content['gift_certificates'] = array(
           '#type' => 'user_profile_category',
           '#weight' => -4, // Underneath "view order history"
@@ -190,6 +209,18 @@ function uc_gift_certificate_username_from_uid($uid){
 }
 
 /**
+ * Helper function for the autocomplete username field
+ */
+function uc_gift_certificate_useremail_from_uid($uid){
+  $result = db_query("SELECT mail FROM {users} WHERE uid = %d", $uid);
+  if ($user = db_fetch_object($result)) {
+    return $user->email;
+  }
+  return false;
+}
+
+
+/**
  * Form to enter a gift certificate (for a product)
  */
 function uc_gift_certificate_issue_form($form_state, $certificate_id) {
