Index: advpoll-form.js
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/advpoll/advpoll-form.js,v
retrieving revision 1.1.2.6
diff -u -p -r1.1.2.6 advpoll-form.js
--- advpoll-form.js	4 Sep 2007 15:36:47 -0000	1.1.2.6
+++ advpoll-form.js	7 Sep 2007 19:28:30 -0000
@@ -18,18 +18,18 @@ Drupal.advpoll.maxChoices = function(num
     if (i == selected) {
       newMaxChoices += 'selected="selected" ';
     }
-    newMaxChoices += 'value="' + i + '">' + name + '</option>';
+    newMaxChoices += 'value="'+ i +'">'+ name +'</option>';
   }
   newMaxChoices += '</select>';
   // Remove old maxchoices
   $("#edit-settings-maxchoices").remove();
   
   label.after(newMaxChoices);
-}
+};
 
 // Click event for Remove link, called on pageload and when Add choice is clicked
-Drupal.advpoll.removeChoiceClick = function()  {
-  $('a.remove-choice').unclick().click(function() {
+Drupal.advpoll.removeChoiceClick = function() {
+  $("a.remove-choice").unclick().click(function() {
     var nextRemoveLink = $(this).parent().next().find(".remove-choice");
     // Set focus at next or previous Remove link
     if(nextRemoveLink.html()) {
@@ -42,13 +42,13 @@ Drupal.advpoll.removeChoiceClick = funct
     $(this).parent().remove();
     var i = 1;
     $("input.choices").prev().each(function() {
-      // Give each label it's correct number
+      // Give each label its correct number
       $(this).html($(this).html().replace(/\d+(?=<)/g, i++));
     });
     
-    Drupal.advpoll.maxChoices(i-1);
+    Drupal.advpoll.maxChoices(i - 1);
   });
-}
+};
 
 // Show/hide "display write-ins" option when user checks unchecks the write-ins
 // box.
@@ -61,7 +61,7 @@ Drupal.advpoll.updateWriteins = function
     $(".edit-settings-show-writeins").hide();
     $("#edit-settings-show-writeins").attr("disabled", "disabled");
   }
-}
+};
 
 Drupal.advpoll.nodeFormAutoAttach = function() {
   // This code is used on the node edit page and the content-type settings page.
@@ -76,16 +76,16 @@ Drupal.advpoll.nodeFormAutoAttach = func
   }
 
   // Hide "need more choices" checkbox
-  $("#morechoices").hide();
+  $("#more-choices").hide();
   
   // Insert Remove links
-  $('<a class="remove-choice">' + Drupal.settings.advPoll.remove + '</a>').insertAfter("input.choices");
+  $('<a class="remove-choice">'+ Drupal.settings.advPoll.remove +'</a>').insertAfter("input.choices");
   Drupal.advpoll.removeChoiceClick();
   
   // "Backup" of the first choice
   var newChoice = $("input.choices:first").parent().clone();
   
-  $('<a class="add-choice" href="#">' + Drupal.settings.advPoll.addChoice + '</a>').insertAfter("#morechoices").click(function() {
+  $('<a class="add-choice" href="#">'+ Drupal.settings.advPoll.addChoice +'</a>').insertAfter("#more-choices").click(function() {
     var numChoices = $("input.choices").length + 1;
     // Extract the last choice's offset from its id.
     var newChoiceN = parseInt($("input.choices:last").id().match(/\d+/)) + 1;
@@ -96,18 +96,17 @@ Drupal.advpoll.nodeFormAutoAttach = func
     // Replace the label to use a more accurate count of choices.
     $("label", newChoice).html($("label", newChoice).html().replace(/\d+(?=<)|\d+(?=-)|\d+(?=\])/g, numChoices));
     // Clear the value, insert and fade in.
-    newChoice.find("input").val("").end().insertBefore("#morechoices").fadeIn();
+    newChoice.find("input").val("").end().insertBefore("#more-choices").fadeIn();
     // Update hidden form values
     $("#edit-choices").val(newChoiceN);
     $("#edit-changed").val($("#edit-changed").val() + 1);
     
     Drupal.advpoll.removeChoiceClick();
-    
     Drupal.advpoll.maxChoices(numChoices);
     
     return false;
   });
-}
+};
 
 // Global Killswitch
 if (Drupal.jsEnabled) {
Index: advpoll-vote.js
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/advpoll/advpoll-vote.js,v
retrieving revision 1.1.2.9
diff -u -p -r1.1.2.9 advpoll-vote.js
--- advpoll-vote.js	6 Sep 2007 23:41:00 -0000	1.1.2.9
+++ advpoll-vote.js	7 Sep 2007 19:28:30 -0000
@@ -8,11 +8,11 @@ if (typeof(Drupal) == "undefined" || !Dr
 * Submit advpoll forms with ajax
 */
 Drupal.advpoll.attachVoteAjax = function() {
-  var submitSelect = "input[@value=" + Drupal.settings.advPoll.vote +"]";
+  var submitSelect = "input[@value="+ Drupal.settings.advPoll.vote +"]";
   $("form.advpoll-vote").each(function() {
     var thisForm = this;
     var options = {
-      dataType: 'json',
+      dataType: "json",
       after: function(data) {
         // Remove previous messages
         $("div.messages").remove(); 
@@ -31,7 +31,6 @@ Drupal.advpoll.attachVoteAjax = function
         $(submitSelect, thisForm).removeAttr("disabled");
 
       },
-
       before: function() {
         // Disable all voting forms for this poll
         var nid = $("input.edit-nid", thisForm).val();
@@ -46,11 +45,11 @@ Drupal.advpoll.attachVoteAjax = function
     $("input.ajax", thisForm).val(true);
     $(this).ajaxForm(options);
   });
-}
+};
 
 Drupal.advpoll.nodeVoteAutoAttach = function() {
   Drupal.advpoll.attachVoteAjax();
-}
+};
 
 Drupal.advpoll.handleWriteins = function() {
   $("div.poll").each(function() {
Index: advpoll.install
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/advpoll/advpoll.install,v
retrieving revision 1.5.2.13
diff -u -p -r1.5.2.13 advpoll.install
--- advpoll.install	4 Sep 2007 15:36:47 -0000	1.5.2.13
+++ advpoll.install	7 Sep 2007 19:28:30 -0000
@@ -1,7 +1,6 @@
 <?php
 // $Id: advpoll.install,v 1.5.2.13 2007/09/04 15:36:47 chriskennedy Exp $
 
-
 /**
  * Implementation of hook_install().
  */
@@ -89,10 +88,10 @@ function advpoll_uninstall() {
   }
 
   // Remove all votes.
-  db_query("DELETE FROM {votingapi_vote} WHERE content_type='advpoll'");
+  db_query("DELETE FROM {votingapi_vote} WHERE content_type = 'advpoll'");
 
   // Remove all cache data.
-  db_query("DELETE FROM {votingapi_cache} WHERE content_type='advpoll'");
+  db_query("DELETE FROM {votingapi_cache} WHERE content_type = 'advpoll'");
 
   // Remove all advpoll nodes.
   $result = db_query('SELECT nid FROM {advpoll}');
@@ -160,7 +159,7 @@ function advpoll_update_3() {
     case 'mysql':
     case 'mysqli':
       // New default '0' instead of NULL for startdate
-      $ret[] = update_sql("ALTER TABLE {advpoll} CHANGE startdate startdate int NOT NULL DEFAULT '0'");
+      $ret[] = update_sql("ALTER TABLE {advpoll} CHANGE startdate startdate int NOT NULL default '0'");
       $ret[] = update_sql("UPDATE {advpoll} SET startdate = 0 WHERE startdate IS NULL");
       // Add the new column.
       $ret[] = update_sql("ALTER TABLE {advpoll} ADD COLUMN enddate int NOT NULL default '0' AFTER startdate");
@@ -193,9 +192,9 @@ function advpoll_update_4() {
   switch ($GLOBALS['db_type']) {
     case 'mysql':
     case 'mysqli':
-      $ret[] = update_sql("ALTER TABLE {advpoll} ADD writeins TINYINT NOT NULL DEFAULT '0'");
-      $ret[] = update_sql("ALTER TABLE {advpoll} ADD show_writeins TINYINT NOT NULL DEFAULT '0'");
-      $ret[] = update_sql("ALTER TABLE {advpoll_choices} ADD writein TINYINT NOT NULL DEFAULT '0'");
+      $ret[] = update_sql("ALTER TABLE {advpoll} ADD writeins tinyint NOT NULL default '0'");
+      $ret[] = update_sql("ALTER TABLE {advpoll} ADD show_writeins tinyint NOT NULL default '0'");
+      $ret[] = update_sql("ALTER TABLE {advpoll_choices} ADD writein tinyint NOT NULL default '0'");
       break;
     case 'pgsql':
       db_add_column($ret, 'advpoll', 'writeins', 'smallint', array('default' => 0, 'not null' => TRUE));
Index: advpoll.module
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/advpoll/advpoll.module,v
retrieving revision 1.21.2.62
diff -u -p -r1.21.2.62 advpoll.module
--- advpoll.module	4 Sep 2007 16:21:39 -0000	1.21.2.62
+++ advpoll.module	7 Sep 2007 19:57:24 -0000
@@ -12,10 +12,29 @@ define('ADVPOLL_ELECTORAL_LIST', 0);
 define('ADVPOLL_SHOWVOTES', 1);
 define('ADVPOLL_WRITEINS', 0);
 define('ADVPOLL_SHOW_WRITEINS', 0);
+define('ADVPOLL_INITIAL_CHOICES', 5);
 // Options: always, aftervote, or afterclose.
 define('ADVPOLL_VIEW_RESULTS', 'aftervote');
 
 /**
+ * Implementation of hook_help().
+ */
+function advpoll_help($section) {
+  switch ($section) {
+    case 'admin/modules#description':
+      return t('A sophisticated polling module for voting, elections, and group decision-making.');
+      break;
+  }
+}
+
+/**
+ * Implementation of hook_perm().
+ */
+function advpoll_perm() {
+  return array('create polls', 'edit polls', 'edit own polls', 'vote on polls', 'cancel own vote', 'administer polls', 'inspect all votes', 'access electoral list', 'add write-ins'); 
+}
+
+/**
  * Implementation of hook_access().
  */
 function advpoll_access($op, $node) {
@@ -32,6 +51,142 @@ function advpoll_access($op, $node) {
 }
 
 /**
+ * Implementation of hook_node_info().
+ */
+function advpoll_node_info() {
+  $modes = _advpoll_list_modes();
+  $info = array();
+  foreach ($modes as $mode) {
+    $info['advpoll_'. $mode['name']] = array(
+      'name' => t('@name poll', array('@name' => $mode['name_label'])),
+      'module' => 'advpoll',
+      'description' => $mode['description'],
+      'title_label' => t('@name question', array('@name' => $mode['name_label'])),
+      'body_label' => t('Description'),
+    );
+  }
+  return $info;
+}
+
+/**
+ * Implementation of hook_menu().
+ */
+function advpoll_menu($may_cache) {
+  global $user;
+
+  $modes = _advpoll_list_modes();
+  $items = array();
+
+  if ($may_cache) {
+    $items[] = array(
+      'path' => 'advpoll/cancel',
+      'title' => t('Cancel'),
+      'callback' => 'advpoll_cancel',
+      'access' => user_access('cancel own vote'),
+      'type' => MENU_CALLBACK,
+    );
+    $items[] = array(
+      'path' => 'polls',
+      'title' => t('Advanced Polls'),
+      'callback' => 'advpoll_page',
+      'access' => user_access('access content'),
+      'type' => MENU_SUGGESTED_ITEM,
+    );
+  }
+  else {
+    // Use Poll modules stylesheet, no need to duplicate at this point.
+    // We put this in !$may_cache so it's only added once per request.
+    drupal_add_css(drupal_get_path('module', 'poll') .'/poll.css');
+    
+    // Need to be able to extract the nid.
+    if (arg(0) == 'node' && is_numeric(arg(1))) {
+      $nid = arg(1);
+      $node = node_load($nid);
+      // Make sure we're on the actual poll node's page.
+      if (strstr($node->type, 'advpoll_') == 0) {
+        // Show the results tab.
+        if (_advpoll_is_active($node) && !$node->voted && _advpoll_can_view_results($node)) {
+          $items[] = array(
+            'path' => 'node/'. $nid .'/results',
+            'title' => t('Results'),
+            'callback' => 'advpoll_results',
+            'access' => user_access('access content'),
+            'weight' => 3,
+            'type' => MENU_LOCAL_TASK,
+          );
+        }
+
+        // Show the votes tab.
+        if ($node->showvotes) {
+          $items[] = array(
+            'path' => 'node/'. $nid .'/votes',
+            'title' => t('Votes'),
+            'callback' => 'advpoll_tab_votes',
+            'access' => user_access('inspect all votes'),
+            'weight' => 3,
+            'type' => MENU_LOCAL_TASK,
+          );
+        }
+
+        // Show electoral list tab if using the functionality.
+        if ($node->uselist) {
+          $items[] = array(
+            'path' => 'node/'. $nid .'/electoral_list',
+            'title' => t('Electoral list'),
+            'callback' => 'advpoll_tab_electoral_list',
+            'access' => user_access('access electoral list'),
+            'weight' => 3,
+            'type' => MENU_LOCAL_TASK,
+          );
+
+          // Allow voters to be removed.
+          $items[] = array(
+            'path' => 'node/'. $nid .'/remove',
+            'callback' => 'advpoll_remove_voter',
+            'access' => user_access('administer polls'),
+            'weight' => 3,
+            'type' => MENU_CALLBACK,
+          );
+        }
+
+        // Allow votes to be reset.
+        $items[] = array(
+          'path' => 'node/'. $nid .'/reset',
+          'callback' => 'drupal_get_form',
+          'callback arguments' => 'advpoll_reset_confirm',
+          'access' => user_access('administer polls'),
+          'weight' => 3,
+          'type' => MENU_CALLBACK,
+        );
+
+        // Show the write-ins tab if there is at least one.
+        if ($node->writeins) {
+          $has_writeins = FALSE;
+          foreach ($node->choice as $choice) {
+            if ($choice['writein']) {
+              $has_writeins = TRUE;
+              break;
+            }
+          }
+          if ($has_writeins) {
+            $items[] = array(
+              'path' => 'node/'. $nid .'/writeins',
+              'title' => t('Write-ins'),
+              'callback' => 'advpoll_tab_writeins',
+              'access' => user_access('administer polls'),
+              'weight' => 3,
+              'type' => MENU_LOCAL_TASK,
+            );
+          }
+        }
+      }
+    }
+  }
+
+  return $items;
+}
+
+/**
  * Implementation of hook_block().
  */
 function advpoll_block($op = 'list') {
@@ -63,7 +218,7 @@ function theme_advpoll_block_mostrecent(
 }
 
 function advpoll_mostrecent() {
-  $result = db_query('SELECT MAX(n.nid) AS nid FROM {node} n INNER JOIN {advpoll} p ON p.nid = n.nid WHERE n.status = 1 AND p.active=1');
+  $result = db_query('SELECT MAX(n.nid) AS nid FROM {node} n INNER JOIN {advpoll} p ON p.nid = n.nid WHERE n.status = 1 AND p.active = 1');
   $poll = db_fetch_object($result);
   // The nid will be NULL if there are no active polls.
   if ($poll->nid) {
@@ -72,52 +227,6 @@ function advpoll_mostrecent() {
   return $node;
 }
 
-function advpoll_page() {
-  // List all polls
-  $sql = "SELECT n.nid, n.title, p.active, n.created, c.value AS votes FROM {node} n INNER JOIN {advpoll} p ON n.nid = p.nid INNER JOIN {votingapi_cache} c ON n.nid = c.content_id WHERE n.status = 1 AND c.tag = '_advpoll' AND c.function='total_votes' AND c.content_type='advpoll' GROUP BY n.nid, n.title, p.active, n.created, c.value ORDER BY n.created DESC";
-  $sql = db_rewrite_sql($sql);
-  $result = pager_query($sql, 15);
-  $output = '<ul>';
-  while ($node = db_fetch_object($result)) {
-    $output .= '<li>'. l($node->title, "node/$node->nid") .' - '. format_plural($node->votes, '1 vote', '@count votes') .' - '. (_advpoll_is_active($node) ? t('open') : t('closed')) .'</li>';
-  }
-  $output .= '</ul>';
-  $output .= theme('pager', NULL, 15);
-  return $output;
-}
-
-/**
- * Implementation of VotingAPI's hook_calculate.
- * 
- * Recalculate results whenever a vote is added or removed.
- */
-function advpoll_votingapi_calculate(&$results, $votes, $content_type, $content_id) {
-  // Make sure it's an Advanced Poll content type
-  if ($content_type == 'advpoll') {
-    // Don't load the node from cache in case the mode or algorithm changed.
-    $node = node_load($content_id, NULL, TRUE);
-    $mode = _advpoll_get_mode($node->type);
-    $function = 'advpoll_calculate_results_'. $mode;
-    if (function_exists($function)) {
-      $function($results, $votes, $node);
-    }
-    cache_clear_all();
-  }
-}
-
-/**
- * Implementation of hook_delete().
- */
-function advpoll_delete($node) {
-  db_query("DELETE FROM {advpoll} WHERE nid = %d", $node->nid);
-  db_query("DELETE FROM {advpoll_choices} WHERE nid = %d", $node->nid);
-  db_query("DELETE FROM {advpoll_electoral_list} WHERE nid = %d", $node->nid);
-
-  // TODO: These should be converted to a votingapi method eventually.
-  db_query("DELETE FROM {votingapi_vote} WHERE content_id = %d AND content_type='advpoll'", $node->nid);
-  db_query("DELETE FROM {votingapi_cache} WHERE content_id = %d AND content_type='advpoll'", $node->nid);
-}
-
 /**
  * Implementation of hook_form().
  *
@@ -126,6 +235,7 @@ function advpoll_delete($node) {
 function advpoll_form($node, $form_values = NULL) {
   $mode = _advpoll_get_mode($node->type);
   $type = node_get_types('type', $node);
+  $form = array();
 
   // Only add javascript once, even if _form is called multiple times.
   static $add_js;
@@ -134,7 +244,7 @@ function advpoll_form($node, $form_value
     drupal_add_js(array('advPoll' => array('remove' => t('Remove'), 'addChoice' => t('Add choice'), 'noLimit' => t('No limit'))), 'setting');
     drupal_add_js(drupal_get_path('module', 'advpoll') .'/advpoll-form.js', 'module');
     drupal_add_css(drupal_get_path('module', 'advpoll') .'/advpoll.css', 'module');
-    $add_js = true;
+    $add_js = TRUE;
   }
 
   $form['title'] = array(
@@ -143,7 +253,6 @@ function advpoll_form($node, $form_value
     '#required' => TRUE,
     '#default_value' => $node->title,
   );
-
   $form['body_filter']['body'] = array(
     '#type' => 'textarea',
     '#title' => check_plain($type->body_label),
@@ -155,12 +264,12 @@ function advpoll_form($node, $form_value
 
   if (isset($form_values)) {
     $choices = $form_values['choices'];
-    if ($form_values['morechoices']) {
+    if ($form_values['more_choices']) {
       $choices *= 2;
     }
   }
   else {
-    $choices = max(2, count($node->choice)? count($node->choice) : 5);
+    $choices = max(2, count($node->choice) ? count($node->choice) : ADVPOLL_INITIAL_CHOICES);
   }
 
   $form['choices'] = array(
@@ -178,27 +287,25 @@ function advpoll_form($node, $form_value
     '#tree' => TRUE,
     '#weight' => 1,
   );
-
   $form['choice']['choice_note'] = array(
     '#value' => '<div id="edit-settings-choice-note" class="description">'. t('Note: adding or removing choices after voting has begun is not recommended.') .'</div>',
   );
-  
-  $form['choice']['morechoices'] = array(
+  $form['choice']['more_choices'] = array(
     '#type' => 'checkbox',
     '#title' => t('Need more choices'),
     '#value' => 0,
-    '#parents' => array('morechoices'), // Don't pollute $form['choice']
-    '#prefix' => '<div id="morechoices">',
+    '#parents' => array('more_choices'), // Don't pollute $form['choice']
+    '#prefix' => '<div id="more-choices">',
     '#suffix' => '</div>',
-    '#description' => t("If the amount of boxes above isn't enough, check this box and click the Preview button below to add some more."),
-    '#weight' => 1
+    '#description' => t("If the number of choices above isn't enough, check this box and click the Preview button below to double the number of choices."),
+    '#weight' => 1,
   );
 
   // First, loop through any currently existing choices.
   $current_choices = 0;
   if (isset($node->choice)) {
     foreach ($node->choice as $index => $choice) {
-       $form['choice'][$index]['label'] = array(
+      $form['choice'][$index]['label'] = array(
         '#type' => 'textfield',
         '#title' => t('Choice %n', array('%n' => $current_choices + 1)) . ($choice['writein'] ? ' '. t('(write-in)') : ''),
         '#default_value' => $choice['label'],
@@ -240,9 +347,9 @@ function advpoll_form($node, $form_value
   $form['settings']['maxchoices'] = array(
     '#type' => 'select',
     '#title' => t('Maximum choices'),
-    '#default_value' => ($node->maxchoices? $node->maxchoices : variable_get('advpoll_maxchoices_'. $type->type, ADVPOLL_MAXCHOICES)),
+    '#default_value' => ($node->maxchoices ? $node->maxchoices : variable_get('advpoll_maxchoices_'. $type->type, ADVPOLL_MAXCHOICES)),
     '#options' => $max_choice_list,
-    '#DANGEROUS_SKIP_CHECK' => true, // Allow jQuery to add new options
+    '#DANGEROUS_SKIP_CHECK' => TRUE, // Allow jQuery to add new options
     '#description' => t('Limits the total number of choices voters may select.')
   );
 
@@ -282,7 +389,6 @@ function advpoll_form($node, $form_value
     '#maxlength' => 25,
     '#default_value' => $node->startdate ? format_date($node->startdate, 'custom', 'Y-m-d H:i:s O') : $default_startdate,
   );
-  
   $form['settings']['enddate'] = array(
     '#type' => 'textfield',
     '#title' => t('Ending date'),
@@ -295,13 +401,12 @@ function advpoll_form($node, $form_value
   // Settings available for users with 'administer polls' permission.
   $default_uselist = isset($node->uselist) ? $node->uselist : variable_get('advpoll_electoral_list_'. $type->type, ADVPOLL_ELECTORAL_LIST);
   $default_showvotes = isset($node->showvotes) ? $node->showvotes : variable_get('advpoll_showvotes_'. $type->type, ADVPOLL_SHOWVOTES);
-  $default_writeins = isset($node->writeins)? $node->writeins : variable_get('advpoll_writeins_'. $type->type, ADVPOLL_WRITEINS);
-  $default_show_writeins = isset($node->show_writeins)? $node->show_writeins : variable_get('advpoll_show_writeins_'. $type->type, ADVPOLL_SHOW_WRITEINS);
+  $default_writeins = isset($node->writeins) ? $node->writeins : variable_get('advpoll_writeins_'. $type->type, ADVPOLL_WRITEINS);
+  $default_show_writeins = isset($node->show_writeins) ? $node->show_writeins : variable_get('advpoll_show_writeins_'. $type->type, ADVPOLL_SHOW_WRITEINS);
   if (user_access('administer polls')) {
     $form['settings']['admin_note'] = array(
       '#value' => '<div id="edit-settings-admin-note" class="description">'. t('The settings below are only available for users with the <em>administer polls</em> permission.') .'</div>',
     );
-
     $form['settings']['writeins'] = array(
       '#type' => 'checkbox',
       '#title' => t('Allow users to cast a write-in vote'),
@@ -309,7 +414,6 @@ function advpoll_form($node, $form_value
       '#description' => t('Allow voters with the "add write-ins" permission to write-in up to one choice each.'),
       '#attributes' => array('class' => 'settings-writeins'),
     );
-
     $form['settings']['show_writeins'] = array(
       '#type' => 'checkbox',
       '#title' => t('Display write-in votes as choices for future voters'),
@@ -318,14 +422,12 @@ function advpoll_form($node, $form_value
       '#prefix' => '<div class="edit-settings-show-writeins">',
       '#suffix' => '</div>',
     );
-
     $form['settings']['uselist'] = array(
       '#type' => 'checkbox',
       '#title' => t('Restrict voting to electoral list'),
       '#description' => t('If enabled, a list of eligible voters will be created and only that group will be able to vote in the poll.'),
       '#default_value' => $default_uselist,
     );
-  
     $form['settings']['showvotes'] = array(
       '#type' => 'checkbox',
       '#title' => t('Show individual votes'),
@@ -342,7 +444,7 @@ function advpoll_form($node, $form_value
     }
   }
   else {
-    // Just pass the values for users without the 'administer polls' permission.
+    // Just pass the values for users without the "administer polls" permission.
     $defaults = array('uselist' => $default_uselist, 'showvotes' => $default_showvotes, 'writeins' => $default_writeins, 'show_writeins' => $default_show_writeins);
     foreach ($defaults as $name => $value) {
       $form['settings'][$name] = array(
@@ -365,7 +467,7 @@ function advpoll_form_alter($form_id, &$
     $node_type = $form['old_type']['#value'];
     // Display poll settings if this is an advpoll content type.
     if ($form['module']['#value'] == 'advpoll') {
-      // We need to include the JS and CSS for the show_writeins setting toggle.
+      // Include JS and CSS for the show_writeins setting toggle.
       drupal_add_js(drupal_get_path('module', 'advpoll') .'/advpoll-form.js', 'module');
       drupal_add_css(drupal_get_path('module', 'advpoll') .'/advpoll.css', 'module');
       $form['advpoll'] = array(
@@ -373,7 +475,6 @@ function advpoll_form_alter($form_id, &$
         '#title' => t('Poll settings'),
         '#collapsible' => TRUE,
       );
-      
       $form['advpoll']['advpoll_maxchoices'] = array(
         '#type' => 'select',
         '#title' => t('Default maximum choices'),
@@ -402,15 +503,13 @@ function advpoll_form_alter($form_id, &$
         '#options' => array(0 => t('Unlimited')) + drupal_map_assoc(array(86400, 172800, 345600, 604800, 1209600, 1814400, 2419200, 4838400, 9676800, 31536000), 'format_interval'),
         '#description' => t('The date the poll was created is used as start date for the default duration. This setting can be overridden on the poll edit page.'),
       );
-
       $form['advpoll']['advpoll_writeins'] = array(
         '#type' => 'checkbox',
         '#title' => t('Allow users to cast a write-in vote by default'),
         '#default_value' => variable_get('advpoll_writeins_'. $node_type, ADVPOLL_WRITEINS),
-        '#description' => t("Allow voters with the 'add write-ins' permission to write-in up to one choice each. Users with the <em>administer polls</em> permission will be able to override this setting."),
+        '#description' => t('Allow voters with the "add write-ins" permission to write-in up to one choice each. Users with the <em>administer polls</em> permission will be able to override this setting.'),
         '#attributes' => array('class' => 'settings-writeins'),
       );
-
       $form['advpoll']['advpoll_show_writeins'] = array(
         '#type' => 'checkbox',
         '#title' => t('Display write-in votes as choices for future voters by default'),
@@ -419,14 +518,12 @@ function advpoll_form_alter($form_id, &$
         '#prefix' => '<div class="edit-settings-show-writeins">',
         '#suffix' => '</div>',
       );
-
       $form['advpoll']['advpoll_electoral_list'] = array(
         '#type' => 'checkbox',
         '#title' => t('Use electoral list by default'),
         '#description' => t('Use an electoral list by default for new polls. Users with the <em>administer polls</em> permission will be able to override this setting.'),
         '#default_value' => variable_get('advpoll_electoral_list_'. $node_type, ADVPOLL_ELECTORAL_LIST),
       );
-      
       $form['advpoll']['advpoll_showvotes'] = array(
         '#type' => 'checkbox',
         '#title' => t('Show individual votes by default'),
@@ -439,7 +536,7 @@ function advpoll_form_alter($form_id, &$
         'aftervote' => t('After user has voted'),
         'afterclose' => t('After voting has closed'),
       );
-    
+
       $form['advpoll']['advpoll_view_results'] = array(
         '#type' => 'radios',
         '#title' => t('Display results'),
@@ -452,31 +549,20 @@ function advpoll_form_alter($form_id, &$
 }
 
 /**
- * Implementation of hook_help().
- */
-function advpoll_help($section) {
-  switch ($section) {
-    case 'admin/modules#description':
-      return t('A sophisticated polling module for voting, elections, and group decision-making.');
-    default:
-  }
-}
-
-/**
  * Implementation of hook_load().
  *
  * Load the votes and poll-specific data into the node object.
  */
 function advpoll_load($node) {
   global $user;
-  $poll = db_fetch_object(db_query("SELECT * FROM {advpoll} WHERE nid = %d", $node->nid));
-  $result = db_query("SELECT vote_offset, label, writein FROM {advpoll_choices} WHERE nid = %d ORDER BY vote_offset", $node->nid);
+  $poll = db_fetch_object(db_query('SELECT * FROM {advpoll} WHERE nid = %d', $node->nid));
+  $result = db_query('SELECT vote_offset, label, writein FROM {advpoll_choices} WHERE nid = %d ORDER BY vote_offset', $node->nid);
   while ($choice = db_fetch_array($result)) {
     $poll->choice[$choice['vote_offset']] = $choice;
   }
   $poll->choices = count($poll->choice);
 
-  $result = db_query("SELECT value FROM {votingapi_cache} where content_type='advpoll' AND content_id=%d AND tag='_advpoll' AND function='total_votes'", $node->nid);
+  $result = db_query("SELECT value FROM {votingapi_cache} WHERE content_type = 'advpoll' AND content_id = %d AND tag = '_advpoll' AND function = 'total_votes'", $node->nid);
   if (db_num_rows($result) > 0) {
     $cache = db_fetch_object($result);
     $poll->votes = $cache->value;
@@ -490,158 +576,198 @@ function advpoll_load($node) {
 }
 
 /**
- * Check if a user has voted on a poll.
- *
- * @return Array indicating if user voted and, if so, if the vote is cancellable.
+ * Implementation of hook_validate().
  */
-function _advpoll_user_voted($nid) {
-  global $user;
-  $voted = FALSE;
-  $cancel_vote = FALSE;
-
-  if ($user->uid) {
-    // Voter is logged in.
-    $voted = (count(votingapi_get_user_votes('advpoll', $nid)) > 0);
-    if ($voted) {
-      $cancel_vote = TRUE;
-    }
+function advpoll_validate(&$node) {
+  global $form_values;
+  if ($form_values['op'] == t('Reset votes')) {
+    drupal_goto('node/'. $node->nid .'/reset');
   }
   else {
-    // Voter is anonymous.
+    // Use form_set_error for any errors.
+    $node->choice = array_values($node->choice);
 
-    // TODO: add options to check cookie rather than IP for anonymous votes.
+    // Start keys at 1 rather than 0.
+    array_unshift($node->choice, '');
+    unset($node->choice[0]);
 
-    // Check if there is already an anonymous vote for this IP.
-    $host =  $_SERVER['REMOTE_ADDR'] . ($_SERVER['HTTP_X_FORWARDED_FOR'] ? '-'. $_SERVER['HTTP_X_FORWARDED_FOR'] : '');
-    $result = db_query("SELECT value FROM {votingapi_vote} WHERE content_id=%d AND content_type='advpoll' AND hostname='%s' AND uid=0", $nid, $host);
-    if (db_num_rows($result) > 0) {
-      $voted = TRUE;
-      $cancel_vote = TRUE;
+    // Check for at least two choices.
+    $realchoices = 0;
+    foreach ($node->choice as $i => $choice) {
+      if ($choice['label'] != '') {
+        $realchoices++;
+      }
+    }
+
+    if ($realchoices < 2) {
+      form_set_error("choice][$realchoices][label", t('You must fill in at least two choices.'));
+    }
+
+    // Validate maxchoices since it has #DANGEROUS_SKIP_CHECK set to true.
+    if ($node->settings['maxchoices'] < 0) {
+      form_set_error('settings][maxchoices]', t('Maximum choices must be a non-negative integer.'));
+    }
+
+    if ($node->settings['maxchoices'] > count($node->choice)) {
+      form_set_error('settings][maxchoices]', t('Maximum choices cannot be larger than the number of choices submitted.'));
+    }
+    
+    // Validate dates.
+    if (!empty($node->settings['startdate']) && strtotime($node->settings['startdate']) <= 0) {
+      form_set_error('settings][startdate', t('You have to specify a valid starting date.'));
+    }
+    if (!empty($node->settings['enddate']) && strtotime($node->settings['enddate']) <= 0) {
+      form_set_error('settings][enddate', t('You have to specify a valid ending date.'));
+    }
+    if (!empty($node->settings['enddate']) && $node->settings['enddate'] < $node->settings['startdate']) {
+      form_set_error('settings][enddate', t('Ending date cannot be before the starting date.'));
     }
   }
-  return array($voted, $cancel_vote);
 }
 
 /**
- * Implementation of hook_menu().
+ * Implementation of hook_insert().
+ *
+ * This is called upon node creation.
  */
-function advpoll_menu($may_cache) {
-  global $user;
+function advpoll_insert($node) {
+  $mode = _advpoll_get_mode($node->type);
+  db_query("INSERT INTO {advpoll} (nid, mode, uselist, active, maxchoices, algorithm, showvotes, startdate, enddate, writeins, show_writeins) VALUES (%d, '%s', %d, %d, %d, '%s', %d, '%s', '%s', %d, %d)", $node->nid, $mode, $node->settings['uselist'], !$node->settings['close'], $node->settings['maxchoices'], $node->settings['algorithm'], $node->settings['showvotes'], $node->settings['startdate'] ? strtotime($node->settings['startdate']) : 0, $node->settings['enddate'] ? strtotime($node->settings['enddate']) : 0, $node->settings['writeins'], $node->settings['show_writeins']);
 
-  // Load the modes in here instead of _init() toprofit from caching,
-  // as recommended by http://api.drupal.org/api/head/function/hook_init.
-  $modes = _advpoll_list_modes();
+  // Insert the choices.
+  _advpoll_insert_choices($node->nid);
+}
 
-  $items = array();
+/**
+ * Implementation of hook_update().
+ *
+ * This is called upon node edition.
+ */
+function advpoll_update($node) {
 
-  if ($may_cache) {
-    $items[] = array(
-      'path' => 'advpoll/cancel',
-      'title' => t('Cancel'),
-      'callback' => 'advpoll_cancel',
-      'access' => user_access('cancel own vote'),
-      'type' => MENU_CALLBACK
+  db_query("UPDATE {advpoll} SET active = %d, maxchoices = %d, algorithm = '%s', uselist = %d, showvotes = %d, startdate = '%s', enddate = '%s', writeins = %d, show_writeins = %d WHERE nid = %d", !$node->settings['close'], $node->settings['maxchoices'], $node->settings['algorithm'], $node->settings['uselist'], $node->settings['showvotes'], $node->settings['startdate'] ? strtotime($node->settings['startdate']) : 0, $node->settings['enddate'] ? strtotime($node->settings['enddate']) : 0, $node->settings['writeins'], $node->settings['show_writeins'], $node->nid);
+
+  _advpoll_insert_choices($node->nid);
+  votingapi_recalculate_results('advpoll', $node->nid);
+}
+
+/**
+ * Implementation of hook_view().
+ */
+function advpoll_view($node, $teaser = FALSE, $page = FALSE) {
+  drupal_add_css(drupal_get_path('module', 'advpoll') .'/advpoll.css', 'module');
+  $status = _advpoll_is_active($node, TRUE);
+  
+  if ($node->in_preview) {
+    // Previewing a node, so display voting form instead of results.
+    $mode = _advpoll_get_mode($node->type);
+    $node->content['poll'] = array(
+      '#weight' => 1,
+      '#value' => drupal_get_form('advpoll_voting_'. $mode .'_form', $node, $teaser, $page),
     );
-    
-    $items[] = array(
-      'path' => 'polls',
-      'title' => t('Advanced Polls'),
-      'callback' => 'advpoll_page',
-      'access' => user_access('access content'),
-      'type' => MENU_SUGGESTED_ITEM,
+  }
+  else if (!$node->voted && arg(2) != 'results' && ($status == 'open' || $status == 'pending')) {
+    // User hasn't voted, we're not on the results tab and poll is open or opening in the future.
+    $node->content['poll'] = array(
+      '#weight' => 1,
+      '#value' => drupal_get_form('advpoll_voting_'. $node->mode .'_form', $node, $teaser, $page, $status),
     );
+    static $addjs = TRUE;
+    if ($addjs) {
+      // Add javascript for posting voting forms with Ajax.
+      drupal_add_js(array('advPoll' => array('vote' => t('Vote'))), 'setting');
+      drupal_add_js(drupal_get_path('module', 'advpoll') .'/advpoll-vote.js', 'module');
+      drupal_add_js(drupal_get_path('module', 'advpoll') .'/jquery.form.js', 'module');
+      $addjs = FALSE;
+    }
   }
   else {
-    // Use Poll modules stylesheet, no need to duplicate at this point.
-    // We put this in !$may_cache so it's only added once per request.
-    drupal_add_css(drupal_get_path('module', 'poll') .'/poll.css');
-    
-    // Need to be able to extract the nid
-    if (arg(0) == 'node' && is_numeric(arg(1))) {
-      $nid = arg(1);
-      $node = node_load($nid);
-      // Make sure we're on the actual poll node's page
-      if (strstr($node->type, 'advpoll_') == 0) {
-        // Show the results tab
-        if (_advpoll_is_active($node) && !$node->voted && _advpoll_can_view_results($node)) {
-          $items[] = array(
-            'path' => 'node/'. $nid .'/results',
-            'title' => t('Results'),
-            'callback' => 'advpoll_results',
-            'access' => user_access('access content'),
-            'weight' => 3,
-            'type' => MENU_LOCAL_TASK,
-          );
-        }
-
-        // Show the votes tab
-        if ($node->showvotes) {
-          $items[] = array(
-            'path' => 'node/'. $nid .'/votes',
-            'title' => t('Votes'),
-            'callback' => 'advpoll_tab_votes',
-            'access' => user_access('inspect all votes'),
-            'weight' => 3,
-            'type' => MENU_LOCAL_TASK,
-          );
-        }
+    // Show results (the user has voted, poll is closed or poll has passed).
+    $node->content['poll'] = array(
+      '#weight' => 1,
+      '#value' => advpoll_view_results($node, $teaser, $page),
+    );  
+  }
+  return node_prepare($node, $teaser);
+}
 
-        // Show electoral list tab if using the functionality
-        if ($node->uselist) {
-          $items[] = array(
-            'path' => 'node/'. $nid .'/electoral_list',
-            'title' => t('Electoral list'),
-            'callback' => 'advpoll_tab_electoral_list',
-            'access' => user_access('access electoral list'),
-            'weight' => 3,
-            'type' => MENU_LOCAL_TASK,
-          );
+/**
+ * Implementation of hook_delete().
+ */
+function advpoll_delete($node) {
+  db_query('DELETE FROM {advpoll} WHERE nid = %d', $node->nid);
+  db_query('DELETE FROM {advpoll_choices} WHERE nid = %d', $node->nid);
+  db_query('DELETE FROM {advpoll_electoral_list} WHERE nid = %d', $node->nid);
 
-          // Allow voters to be removed
-          $items[] = array(
-            'path' => 'node/'. $nid .'/remove',
-            'callback' => 'advpoll_remove_voter',
-            'access' => user_access('administer polls'),
-            'weight' => 3,
-            'type' => MENU_CALLBACK,
-          );
-        }
+  // TODO: These should be converted to a votingapi method eventually.
+  db_query("DELETE FROM {votingapi_vote} WHERE content_id = %d AND content_type = 'advpoll'", $node->nid);
+  db_query("DELETE FROM {votingapi_cache} WHERE content_id = %d AND content_type = 'advpoll'", $node->nid);
+}
 
-        // Allow votes to be reset
-        $items[] = array(
-          'path' => 'node/'. $nid .'/reset',
-          'callback' => 'drupal_get_form',
-          'callback arguments' => 'advpoll_reset_confirm',
-          'access' => user_access('administer polls'),
-          'weight' => 3,
-          'type' => MENU_CALLBACK,
-        );
+function advpoll_page() {
+  // List all polls
+  $sql = "SELECT n.nid, n.title, p.active, n.created, c.value AS votes FROM {node} n INNER JOIN {advpoll} p ON n.nid = p.nid INNER JOIN {votingapi_cache} c ON n.nid = c.content_id WHERE n.status = 1 AND c.tag = '_advpoll' AND c.function = 'total_votes' AND c.content_type = 'advpoll' GROUP BY n.nid, n.title, p.active, n.created, c.value ORDER BY n.created DESC";
+  $sql = db_rewrite_sql($sql);
+  $result = pager_query($sql, 15);
+  $output = '<ul>';
+  while ($node = db_fetch_object($result)) {
+    $output .= '<li>'. l($node->title, 'node/'. $node->nid) .' - '. format_plural($node->votes, '1 vote', '@count votes') .' - '. (_advpoll_is_active($node) ? t('open') : t('closed')) .'</li>';
+  }
+  $output .= '</ul>';
+  $output .= theme('pager', NULL, 15);
+  return $output;
+}
 
-        // Show the write-ins tab if there is at least one.
-        if ($node->writeins) {
-          $has_writeins = FALSE;
-          foreach ($node->choice as $choice) {
-            if ($choice['writein']) {
-              $has_writeins = TRUE;
-              break;
-            }
-          }
-          if ($has_writeins) {
-            $items[] = array(
-              'path' => 'node/'. $nid .'/writeins',
-              'title' => t('Write-ins'),
-              'callback' => 'advpoll_tab_writeins',
-              'access' => user_access('administer polls'),
-              'weight' => 3,
-              'type' => MENU_LOCAL_TASK,
-            );
-          }
-        }
-      }
+/**
+ * Implementation of VotingAPI's hook_calculate.
+ * 
+ * Recalculate results whenever a vote is added or removed.
+ */
+function advpoll_votingapi_calculate(&$results, $votes, $content_type, $content_id) {
+  // Make sure it's an Advanced Poll content type
+  if ($content_type == 'advpoll') {
+    // Don't load the node from cache in case the mode or algorithm changed.
+    $node = node_load($content_id, NULL, TRUE);
+    $mode = _advpoll_get_mode($node->type);
+    $function = 'advpoll_calculate_results_'. $mode;
+    if (function_exists($function)) {
+      $function($results, $votes, $node);
     }
+    cache_clear_all();
   }
+}
 
-  return $items;
+/**
+ * Check if a user has voted on a poll.
+ *
+ * @return Array indicating if user voted and, if so, if the vote is cancellable.
+ */
+function _advpoll_user_voted($nid) {
+  global $user;
+  $voted = FALSE;
+  $cancel_vote = FALSE;
+
+  if ($user->uid) {
+    // Voter is logged in.
+    $voted = (count(votingapi_get_user_votes('advpoll', $nid)) > 0);
+    if ($voted) {
+      $cancel_vote = TRUE;
+    }
+  }
+  else {
+    // Voter is anonymous.
+
+    // TODO: add options to check cookie rather than IP for anonymous votes.
+
+    // Check if there is already an anonymous vote for this IP.
+    $host =  $_SERVER['REMOTE_ADDR'] . ($_SERVER['HTTP_X_FORWARDED_FOR'] ? '-'. $_SERVER['HTTP_X_FORWARDED_FOR'] : '');
+    $result = db_query("SELECT value FROM {votingapi_vote} WHERE content_id = %d AND content_type = 'advpoll' AND hostname = '%s' AND uid = 0", $nid, $host);
+    if (db_num_rows($result) > 0) {
+      $voted = TRUE;
+      $cancel_vote = TRUE;
+    }
+  }
+  return array($voted, $cancel_vote);
 }
 
 /**
@@ -649,10 +775,12 @@ function advpoll_menu($may_cache) {
  */
 function advpoll_tab_electoral_list() {
   if ($node = node_load(arg(1))) {
+    // Bail out if electoral list isn't available for this node.
     if (!$node->uselist) {
       drupal_not_found();
       return;
     }
+    
     drupal_set_title(check_plain($node->title));
     
     if (user_access('administer polls')) {
@@ -663,7 +791,7 @@ function advpoll_tab_electoral_list() {
 
     $header[] = array('data' => t('Voter'), 'field' => 'u.name');
 
-    $result = pager_query("SELECT u.uid, u.name FROM {advpoll_electoral_list} el LEFT JOIN {users} u ON el.uid = u.uid WHERE el.nid = %d" . tablesort_sql($header), 20, 0, NULL, $node->nid);
+    $result = pager_query("SELECT u.uid, u.name FROM {advpoll_electoral_list} el LEFT JOIN {users} u ON el.uid = u.uid WHERE el.nid = %d". tablesort_sql($header), 20, 0, NULL, $node->nid);
     $eligible_voters = array();
     while ($voter = db_fetch_object($result)) {
       $temp = array(
@@ -693,7 +821,6 @@ function advpoll_electoral_list_form($ni
     '#collapsible' => TRUE,
     '#weight' => 2,
   );
-
   $form['electoral_list']['add_user'] = array(
     '#type' => 'textfield',
     '#title' => t('Add user'),
@@ -707,7 +834,7 @@ function advpoll_electoral_list_form($ni
   }
 
   // List all roles with "vote on polls" permission, but don't include anonymous users.
-  $result = db_query("SELECT r.name, r.rid FROM {role} r LEFT JOIN {permission} p ON p.rid=r.rid WHERE p.perm LIKE '%vote on polls%' AND r.rid != 1 ORDER BY r.name");
+  $result = db_query("SELECT r.name, r.rid FROM {role} r LEFT JOIN {permission} p ON p.rid = r.rid WHERE p.perm LIKE '%vote on polls%' AND r.rid != 1 ORDER BY r.name");
   $role_options = array(0 => t('(Select a role)'));
   while ($role = db_fetch_object($result)) {
     $role_options[$role->rid] = $role->name;
@@ -719,12 +846,10 @@ function advpoll_electoral_list_form($ni
     '#description' => t('Only roles that have the "vote on polls" permission are listed.'),
     '#options' => $role_options,
   );
-
   $form['electoral_list']['submit'] = array(
     '#type' => 'submit',
     '#value' => t('Add to electoral list'),
   );
-
   $form['electoral_list']['reset'] = array(
     '#type' => 'button',
     '#value' => t('Clear electoral list'),
@@ -741,16 +866,15 @@ function advpoll_remove_voter() {
   $nid = arg(1);
   $uid = arg(3);
   if ($uid && $node = node_load($nid)) {
-    $result = db_query('SELECT name FROM {users} WHERE uid=%d', $uid);
+    $result = db_query('SELECT name FROM {users} WHERE uid = %d', $uid);
     if (db_num_rows($result) > 0) {
       $user = db_fetch_object($result);
-      db_query('DELETE FROM {advpoll_electoral_list} WHERE nid=%d AND uid=%d', $nid, $uid);
+      db_query('DELETE FROM {advpoll_electoral_list} WHERE nid = %d AND uid = %d', $nid, $uid);
       drupal_set_message(t('%user removed from the electoral list.', array('%user' => $user->name)));
     }
     else {
       drupal_set_message(t('No user found with a uid of %uid.', array('%uid' => $uid)));
     }
-
   }
   drupal_goto('node/'. $node->nid .'/electoral_list');
 }
@@ -761,7 +885,7 @@ function advpoll_remove_voter() {
 function advpoll_electoral_list_form_validate($form_id, $form_values) {
   if ($form_values['op'] == t('Reset electoral list')) {
     if (user_access('administer polls')) {
-      db_query('DELETE FROM {advpoll_electoral_list} WHERE nid=%d', $form_values['nid']);
+      db_query('DELETE FROM {advpoll_electoral_list} WHERE nid = %d', $form_values['nid']);
       drupal_set_message(t('Electoral list cleared.'));
       return;
     }
@@ -770,7 +894,7 @@ function advpoll_electoral_list_form_val
   $add_user = $form_values['electoral_list']['add_user'];
   if ($add_user) {
     // Check that the user exists
-    $result = db_query("SELECT uid FROM {users} WHERE name='%s'", $add_user);
+    $result = db_query("SELECT uid FROM {users} WHERE name = '%s'", $add_user);
     if (db_num_rows($result) == 0) {
       form_set_error('electoral_list][add_user', t('User %user does not exist.', array('%user' => $add_user)));
       return FALSE;
@@ -791,7 +915,7 @@ function advpoll_electoral_list_form_sub
   $add_role = $form_values['electoral_list']['add_role'];
   if ($add_role) {
     // Get the current electoral list.
-    $result = db_query('SELECT uid FROM {advpoll_electoral_list} WHERE nid=%d', $form_values['nid']);
+    $result = db_query('SELECT uid FROM {advpoll_electoral_list} WHERE nid = %d', $form_values['nid']);
     $current_list = array(0);
     while ($user = db_fetch_object($result)) {
       $current_list[] = $user->uid;
@@ -799,8 +923,8 @@ function advpoll_electoral_list_form_sub
 
     $user_in_string = implode(',', $current_list);
     // Check if all authenticated users should be added.
-    $result = db_fetch_object(db_query("SELECT COUNT(*) AS hit FROM {role} r WHERE r.name = 'authenticated user' AND r.rid = %d", $add_role));
-    if ($result->hit) {
+    $is_authenticated = db_result(db_query("SELECT COUNT(*) FROM {role} r WHERE r.name = 'authenticated user' AND r.rid = %d", $add_role));
+    if ($is_authenticated) {
       // Special case: any authenticated user can vote.
       // Add all current users to electoral list.
       $result = db_query("INSERT INTO {advpoll_electoral_list} (nid, uid) SELECT '%d', u.uid FROM {users} u WHERE u.uid NOT IN('%s')", $form_values['nid'], $user_in_string);
@@ -809,8 +933,8 @@ function advpoll_electoral_list_form_sub
       // Insert new users into the electoral_list based on the role chosen.
       $result = db_query("INSERT INTO {advpoll_electoral_list} (nid, uid) SELECT '%d', u.uid FROM {users} u LEFT JOIN {users_roles} ur ON u.uid = ur.uid WHERE ur.rid = %d AND u.uid NOT IN('%s')", $form_values['nid'], $add_role, $user_in_string);
     }
-    drupal_set_message(format_plural(db_affected_rows($result), 'Added <em>1</em> user to the electoral list.', 'Added @count users to the electoral list.'));
-
+    $count = db_affected_rows($result);
+    drupal_set_message(format_plural($count, 'Added <em>1</em> user to the electoral list.', 'Added @count users to the electoral list.', array('@count' => $count)));
   }
 }
 
@@ -820,7 +944,7 @@ function advpoll_electoral_list_form_sub
 function advpoll_tab_votes() {
   if ($node = node_load(arg(1))) {
     if (!$node->showvotes) {
-      // Advanced Poll is set to not allow viewing of votes
+      // Advanced Poll is set to not allow viewing of votes.
       drupal_not_found();
       return;
     }
@@ -830,24 +954,24 @@ function advpoll_tab_votes() {
     $header[] = array('data' => t('Visitor'), 'field' => 'u.name');
     $header[] = array('data' => t('Vote'), '');
 
-    $result = pager_query("SELECT v.value, v.uid, v.hostname, v.tag, u.name FROM {votingapi_vote} v LEFT JOIN {users} u ON v.uid = u.uid WHERE v.content_type='advpoll' AND v.content_id = %d". tablesort_sql($header), 20, 0, NULL, $node->nid);
+    $result = pager_query("SELECT v.value, v.uid, v.hostname, v.tag, u.name FROM {votingapi_vote} v LEFT JOIN {users} u ON v.uid = u.uid WHERE v.content_type = 'advpoll' AND v.content_id = %d". tablesort_sql($header), 20, 0, NULL, $node->nid);
     $rows = array();
     while ($vote = db_fetch_object($result)) {
-      $key = $vote->uid? $vote->uid : $vote->hostname;
+      $key = $vote->uid ? $vote->uid : $vote->hostname;
       $rows[$key]['name'] = $vote->name ? theme('username', $vote) : check_plain($vote->hostname);
       if ($node->type == 'advpoll_ranking') {
-        // Need two dimensional results (if equal rankings are allowed)
-        $rows[$key]['votes'][$vote->value][] = _advpoll_choice_markup($node->choice[$vote->tag]['label'], $node->format, false);
+        // Need two dimensional results (if equal rankings are allowed).
+        $rows[$key]['votes'][$vote->value][] = _advpoll_choice_markup($node->choice[$vote->tag]['label'], $node->format, FALSE);
       }
       else {
-        // Just need one dimensional results
-        $rows[$key]['votes'][] = _advpoll_choice_markup($node->choice[$vote->tag]['label'], $node->format, false);
+        // Just need one dimensional results.
+        $rows[$key]['votes'][] = _advpoll_choice_markup($node->choice[$vote->tag]['label'], $node->format, FALSE);
       }
     }
     
     $separators = array('advpoll_ranking' => ' > ', 'advpoll_binary' => ', ');
 
-    // Create strings out of each vote
+    // Create strings out of each vote.
     $results = array();
 
     foreach ($rows as $key => $container) {
@@ -855,13 +979,13 @@ function advpoll_tab_votes() {
       asort($ranking);
       $rankings = array();
       if ($node->type == 'advpoll_ranking') {
-        // Include support for multiple choices having the same ranking
+        // Include support for multiple choices having the same ranking.
         foreach ($ranking as $vote => $choices) {
           $rankings[$vote] = implode(' = ', $choices);
         }
       }
       else {
-        // Just copy the previous array
+        // Just copy the previous array.
         $rankings = $ranking;
       }
       ksort($rankings);
@@ -889,54 +1013,15 @@ function _advpoll_can_view_results($node
 }
 
 /**
- * Implementation of hook_node_info().
- */
-function advpoll_node_info() {
-  $modes = _advpoll_list_modes();
-  $info = array();
-  foreach ($modes as $mode) {
-    $info['advpoll_'. $mode['name']] = array(
-      'name' => t('@name poll', array('@name' => $mode['name_label'])),
-      'module' => 'advpoll',
-      'description' => $mode['description'],
-      'title_label' => t('@name question', array('@name' => $mode['name_label'])),
-      'body_label' => t('Description'),
-    );
-  }
-  return $info;
-}
-
-/**
- * Implementation of hook_perm().
- */
-function advpoll_perm() {
-  return array('create polls', 'edit polls', 'edit own polls', 'vote on polls', 'cancel own vote', 'administer polls', 'inspect all votes', 'access electoral list', 'add write-ins'); 
-}
-
-/**
  * Helper function to display 'cancel vote' button if user has voted.
  */
 function advpoll_cancel_form($nid) {
-  $form['#action'] = url("advpoll/cancel/$nid");
+  $form['#action'] = url('advpoll/cancel/'. $nid);
   $form['submit'] = array('#type' => 'submit', '#value' => t('Cancel your vote'));
   return $form;  
 }
 
 /**
- * Implementation of hook_update().
- *
- * This is called upon node edition.
- */
-function advpoll_update($node) {
-
-  db_query("UPDATE {advpoll} SET active = %d, maxchoices = %d, algorithm = '%s', uselist = %d, showvotes = %d, startdate = '%s', enddate = '%s', writeins = %d, show_writeins = %d WHERE nid = %d", !$node->settings['close'], $node->settings['maxchoices'], $node->settings['algorithm'], $node->settings['uselist'], $node->settings['showvotes'], $node->settings['startdate'] ? strtotime($node->settings['startdate']) : 0, $node->settings['enddate'] ? strtotime($node->settings['enddate']) : 0, $node->settings['writeins'], $node->settings['show_writeins'], $node->nid);
-
-  _advpoll_insert_choices($node->nid);
-  votingapi_recalculate_results('advpoll', $node->nid);
-}
-
-
-/**
  * Helper function to check if a poll is active.
  */
 function _advpoll_is_active($node, $return_status = FALSE) {
@@ -964,13 +1049,7 @@ function _advpoll_is_active($node, $retu
       $status = 'passed';
     }
   }
-  
-  if ($return_status) {
-    return $status;  
-  }
-  else {
-    return $active;  
-  }  
+  return $return_status ? $status : $active; 
 }
 
 function _advpoll_insert_choices($nid) {
@@ -995,19 +1074,6 @@ function _advpoll_get_mode($node_type) {
 }
 
 /**
- * Implementation of hook_insert().
- *
- * This is called upon node creation.
- */
-function advpoll_insert($node) {
-  $mode = _advpoll_get_mode($node->type);
-  db_query("INSERT INTO {advpoll} (nid, mode, uselist, active, maxchoices, algorithm, showvotes, startdate, enddate, writeins, show_writeins) VALUES (%d, '%s', %d, %d, %d, '%s', %d, '%s', '%s', %d, %d)", $node->nid, $mode, $node->settings['uselist'], !$node->settings['close'], $node->settings['maxchoices'], $node->settings['algorithm'], $node->settings['showvotes'], $node->settings['startdate'] ? strtotime($node->settings['startdate']) : 0, $node->settings['enddate'] ? strtotime($node->settings['enddate']) : 0, $node->settings['writeins'], $node->settings['show_writeins']);
-
-  // Insert the choices
-  _advpoll_insert_choices($node->nid);
-}
-
-/**
  * Callback to display a reset votes confirmation form.
  */ 
 function advpoll_reset_confirm() {
@@ -1017,13 +1083,7 @@ function advpoll_reset_confirm() {
   $node = node_load($edit['nid']);
 
   $form['nid'] = array('#type' => 'value', '#value' => $node->nid);
-  $output = confirm_form($form,
-    t('Are you sure you want to reset the votes for %title?',
-    array('%title' => $node->title)),
-    'node/'. $node->nid,
-    t('This action cannot be undone.'),
-    t('Reset votes'),
-    t('Cancel'));
+  $output = confirm_form($form, t('Are you sure you want to reset the votes for %title?', array('%title' => $node->title)), 'node/'. $node->nid, t('This action cannot be undone.'), t('Reset votes'), t('Cancel'));
   return $output;
 }
 
@@ -1034,107 +1094,16 @@ function advpoll_reset_confirm_submit($f
   if ($form_values['confirm']) {
     $nid = arg(1);
     if ($node = node_load($nid)) {
-      // Delete any votes for the poll
-      db_query("DELETE FROM {votingapi_vote} WHERE content_type='advpoll' AND content_id = %d", $node->nid);
+      // Delete any votes for the poll.
+      db_query("DELETE FROM {votingapi_vote} WHERE content_type = 'advpoll' AND content_id = %d", $node->nid);
       votingapi_recalculate_results('advpoll', $node->nid);
-      drupal_set_message('Votes have been reset.');
+      drupal_set_message(t('Votes have been reset.'));
       drupal_goto('node/'. $node->nid);
     }
   }
-
   return '';
 }
 
-/**
- * Implementation of hook_validate().
- */
-function advpoll_validate(&$node) {
-  global $form_values;
-  if ($form_values['op'] == t('Reset votes')) {
-    drupal_goto('node/'. $node->nid .'/reset');
-  }
-  else {
-    // Use form_set_error for any errors
-    $node->choice = array_values($node->choice);
-
-    // Start keys at 1 rather than 0
-    array_unshift($node->choice, '');
-    unset($node->choice[0]);
-
-    // Check for at least two choices
-    $realchoices = 0;
-    foreach ($node->choice as $i => $choice) {
-      if ($choice['label'] != '') {
-        $realchoices++;
-      }
-    }
-
-    if ($realchoices < 2) {
-      form_set_error("choice][$realchoices][label", t('You must fill in at least two choices.'));
-    }
-
-    /* Validate maxchoices since it has #DANGEROUS_SKIP_CHECK set to true */
-    if ($node->settings['maxchoices'] < 0) {
-      form_set_error('settings][maxchoices]', t('Maximum choices must be a non-negative integer.'));
-    }
-
-    if ($node->settings['maxchoices'] > count($node->choice)) {
-      form_set_error('settings][maxchoices]', t('Maximum choices cannot be larger than the number of choices submitted.'));
-    }
-    
-    // Validate dates
-    if (!empty($node->settings['startdate']) && strtotime($node->settings['startdate']) <= 0) {
-      form_set_error('settings][startdate', t('You have to specify a valid starting date.'));
-    }
-    if (!empty($node->settings['enddate']) && strtotime($node->settings['enddate']) <= 0) {
-      form_set_error('settings][enddate', t('You have to specify a valid ending date.'));
-    }
-    if (!empty($node->settings['enddate']) && $node->settings['enddate'] < $node->settings['startdate']) {
-      form_set_error('settings][enddate', t('Ending date cannot be before the starting date.'));
-    }
-  }
-}
-
-/**
- * Implementation of hook_view().
- */
-function advpoll_view($node, $teaser = FALSE, $page = FALSE) {
-  drupal_add_css(drupal_get_path('module', 'advpoll') .'/advpoll.css', 'module');
-  $status = _advpoll_is_active($node, TRUE);
-  
-  if ($node->in_preview) {
-    // Previewing a node, so display voting form instead of results.
-    $mode = _advpoll_get_mode($node->type);
-    $node->content['poll'] = array(
-      '#weight' => 1,
-      '#value' => drupal_get_form('advpoll_voting_'. $mode .'_form', $node, $teaser, $page),
-    );
-  }
-  else if (!$node->voted && arg(2) != 'results' && ($status == 'open' || $status == 'pending')) {
-    // User hasn't voted, we're not on the results tab and poll is open or opening in the future.
-    $node->content['poll'] = array(
-      '#weight' => 1,
-      '#value' => drupal_get_form('advpoll_voting_'. $node->mode .'_form', $node, $teaser, $page, $status),
-    );
-    static $addjs = TRUE;
-    if ($addjs) {
-      // Add javascript for posting voting forms with Ajax
-      drupal_add_js(array('advPoll' => array('vote' => t('Vote'))), 'setting');
-      drupal_add_js(drupal_get_path('module', 'advpoll') .'/advpoll-vote.js', 'module');
-      drupal_add_js(drupal_get_path('module', 'advpoll') .'/jquery.form.js', 'module');
-      $addjs = FALSE;
-    }
-  }
-  else {
-    // Show results (the user has voted, poll is closed or poll has passed).
-    $node->content['poll'] = array(
-      '#weight' => 1,
-      '#value' => advpoll_view_results($node, $teaser, $page)
-    );  
-  }
-  return node_prepare($node, $teaser);
-}
-
 function _advpoll_block_resultslink($node) {
   return array(
     'title' => t('Results'),
@@ -1172,7 +1141,7 @@ function theme_advpoll_bar($title, $perc
 }
 
 /**
- * Callback for 'results' tab for advpoll you can vote on.
+ * Callback for results tab.
  */
 function advpoll_results() {
   if ($node = node_load(arg(1))) {
@@ -1180,7 +1149,7 @@ function advpoll_results() {
     return node_show($node, 0);
   }
   else {
-    // The url does not provide the appropriate node id
+    // The url does not provide the appropriate node id.
     drupal_not_found();
   }
 }
@@ -1193,7 +1162,7 @@ function _advpoll_vote_response($node, $
     unset($node->choice);
     // Get all choices from database. This is necessary to get information about
     // newly submitted write-in choices.
-    $result = db_query("SELECT vote_offset, label, writein FROM {advpoll_choices} WHERE nid = %d ORDER BY vote_offset", $node->nid);
+    $result = db_query('SELECT vote_offset, label, writein FROM {advpoll_choices} WHERE nid = %d ORDER BY vote_offset', $node->nid);
     while ($choice = db_fetch_array($result)) {
       $node->choice[$choice['vote_offset']] = $choice;
     }
@@ -1211,13 +1180,13 @@ function _advpoll_vote_response($node, $
 
     list($node->voted, $node->cancel_vote) = _advpoll_user_voted($node->nid);
     $ajax_output .= advpoll_view_results($node, NULL, NULL);
-    // Remove linebreaks as they will break jQuery's insert-HTML methods
+    // Remove linebreaks as they will break jQuery's insert-HTML methods.
     $ajax_output = str_replace("\n", '', $ajax_output);
     drupal_set_header('Content-Type: text/plain; charset=utf-8');
     print drupal_to_js(array('statusMsgs' => '<div class="messages status">'. $msg .'</div>', 'response' => $ajax_output));
     exit();
   }
-  // Usual response
+  // Usual response.
   else {
     drupal_set_message($msg);
   }
@@ -1233,10 +1202,9 @@ function _advpoll_vote_response($node, $
 function advpoll_view_results(&$node, $teaser, $page) {
   $mode = _advpoll_get_mode($node->type);
   if (_advpoll_can_view_results($node)) {
-    if (function_exists("advpoll_view_results_$mode")) {
-      $results = call_user_func("advpoll_view_results_$mode", $node, $teaser, $page);
-      $output .= theme('advpoll_results', check_plain($node->title),
-        $results['results'], $results['votes'], $node->links, $node->nid, $node->voted, $node->cancel_vote);
+    if (function_exists('advpoll_view_results_'. $mode)) {
+      $results = call_user_func('advpoll_view_results_'. $mode, $node, $teaser, $page);
+      $output .= theme('advpoll_results', check_plain($node->title), $results['results'], $results['votes'], $node->links, $node->nid, $node->voted, $node->cancel_vote);
     }
   }
   $output .= _advpoll_show_cancel_form($node);
@@ -1256,7 +1224,7 @@ function advpoll_cancel($nid) {
       }
       else {
         $host = $_SERVER['HTTP_X_FORWARDED_FOR']? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
-        db_query("DELETE FROM {votingapi_vote} WHERE content_id=%d and hostname = '%s' AND uid=0", $node->nid, $host);
+        db_query("DELETE FROM {votingapi_vote} WHERE content_id = %d and hostname = '%s' AND uid = 0", $node->nid, $host);
         votingapi_recalculate_results('advpoll', $nid);
       }
 
@@ -1268,7 +1236,7 @@ function advpoll_cancel($nid) {
       drupal_set_message(t('Your vote was canceled.'));
     }
     else {
-      drupal_set_message(t("You are not allowed to cancel an invalid choice."), 'error');
+      drupal_set_message(t('You are not allowed to cancel an invalid choice.'), 'error');
     }
     drupal_goto('node/'. $nid);
   }  
@@ -1287,8 +1255,7 @@ function advpoll_eligible($node, $uid = 
   }
 
   if ($node->uselist) {
-    $can_vote = db_fetch_object(db_query("SELECT COUNT(*) AS eligible FROM {advpoll_electoral_list} WHERE nid=%d AND uid=%d", $node->nid, $uid));
-    $eligible = $can_vote->eligible;
+    $eligible = db_result(db_query('SELECT COUNT(*) FROM {advpoll_electoral_list} WHERE nid = %d AND uid = %d', $node->nid, $uid));
   }
   else {
     $eligible = user_access('vote on polls');
@@ -1297,7 +1264,7 @@ function advpoll_eligible($node, $uid = 
 }
 
 function advpoll_algorithms($mode) {
-  return call_user_func("advpoll_algorithms_$mode");
+  return call_user_func('advpoll_algorithms_'. $mode);
 }
 
 /**
@@ -1308,18 +1275,18 @@ function advpoll_algorithms($mode) {
  * added to the mode list.
  */
 function _advpoll_list_modes() {
-  static $_advpoll_modes;
-  if (!$_advpoll_modes) {
-    foreach (file_scan_directory(dirname(__FILE__) .'/modes/',
-        '^([^\.].*)\.inc$', array('.', '..', 'CVS'), 0, FALSE) as $file) {
+  static $advpoll_modes;
+  if (!$advpoll_modes) {
+    $files = file_scan_directory(dirname(__FILE__) .'/modes/', '^([^\.].*)\.inc$', array('.', '..', 'CVS'), 0, FALSE);
+    foreach ($files as $file) {
       require_once($file->filename);
       $mode = $file->name;
-      if (function_exists("advpoll_info_$mode")) {
-        $_advpoll_modes[$mode] = call_user_func("advpoll_info_$mode");
+      if (function_exists('advpoll_info_'. $mode)) {
+        $advpoll_modes[$mode] = call_user_func('advpoll_info_'. $mode);
       }
     }
   }
-  return $_advpoll_modes;
+  return $advpoll_modes;
 }
 
 /**
@@ -1328,18 +1295,17 @@ function _advpoll_list_modes() {
  * We strip out the paragraphs which are not allowed within the label element
  * and created by check_markup() when "Line break converter"-filter is used.
  */
-function _advpoll_choice_markup($text, $format = FILTER_FORMAT_DEFAULT, $check = true) {
+function _advpoll_choice_markup($text, $format = FILTER_FORMAT_DEFAULT, $check = TRUE) {
   $text = check_markup($text, $format, $check);
   $text = str_replace(array('<p>', '</p>'), '', $text);
   $text = trim($text);
-
   return $text; 
 }
 
 /**
  * Wrapper function around form_set_error() to support validating of Ajax voting.
  */
-function _advpoll_form_set_error($name = NULL, $message = '', $ajax = false) {
+function _advpoll_form_set_error($name = NULL, $message = '', $ajax = FALSE) {
   if ($ajax) {
     drupal_set_header('Content-Type: text/plain; charset=utf-8');
     print drupal_to_js(array('errors' => '<div class="messages error">'. $message .'</div>'));
Index: modes/binary.inc
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/advpoll/modes/binary.inc,v
retrieving revision 1.7.2.26
diff -u -p -r1.7.2.26 binary.inc
--- modes/binary.inc	6 Sep 2007 23:41:00 -0000	1.7.2.26
+++ modes/binary.inc	7 Sep 2007 19:28:30 -0000
@@ -20,9 +20,10 @@ function advpoll_algorithms_binary() {
  */
 function advpoll_voting_binary_form(&$node, $teaser, $page, $status) {
   static $binary_form_count = 0; 
-  $form['#id'] = 'advpoll_voting_binary_form-'. $binary_form_count++;
-  $form['#attributes'] = array('class' => 'advpoll-vote');
-  
+  $form = array(
+    '#id' => 'advpoll_voting_binary_form-'. $binary_form_count++,
+    '#attributes' => array('class' => 'advpoll-vote'),
+  );
   $form['ajax'] = array(
     '#type' => 'hidden',
     '#attributes' => array('class' => 'ajax'),
@@ -35,7 +36,7 @@ function advpoll_voting_binary_form(&$no
     foreach ($node->choice as $i => $choice) {
       // Don't show blank choices or write-in votes if the setting is disabled.
       if ($choice['label'] && ($node->show_writeins || !$choice['writein'])) {
-         $list[$i] = _advpoll_choice_markup($choice['label'], $node->format, $check) . ($choice['writein'] ? ' '. t('(write-in)') : '');
+        $list[$i] = _advpoll_choice_markup($choice['label'], $node->format, $check) . ($choice['writein'] ? ' '. t('(write-in)') : '');
       }
     }
     // Add write-in checkbox/radio if write-ins are enabled and user has permission.
@@ -53,12 +54,8 @@ function advpoll_voting_binary_form(&$no
       '#suffix' => '</div>',
     );
 
-    if ($node->in_preview) {
-      $maxchoices = $node->settings['maxchoices'];
-    }
-    else {
-      $maxchoices = $node->maxchoices; 
-    }
+    $maxchoices = $node->in_preview ? $node->settings['maxchoices'] : $node->maxchoices; 
+
     if ($maxchoices == 1) {
       // Plurality voting
       $form['choice']['#type'] = 'radios';
@@ -72,7 +69,7 @@ function advpoll_voting_binary_form(&$no
 
   // Add write-in text field if write-ins are enabled and user has permission.
   if ($node->writeins && user_access('add write-ins')) {
-    $form['writein_choice'] = array (
+    $form['writein_choice'] = array(
       '#prefix' => '<div class="writein-choice">',
       '#suffix' => '</div>',
       '#type' => 'textfield',
@@ -97,7 +94,7 @@ function advpoll_voting_binary_form(&$no
     );
   }
   elseif ($node->in_preview) {
-    //Display nothing
+    // Display nothing.
   }
   elseif ($status == 'pending') {
     $form['message']['#value'] = t('This poll opens @time.', array('@time' => format_date($node->startdate)));
@@ -149,7 +146,7 @@ function advpoll_view_results_binary($no
     foreach ($votes as $i => $count) {
       $choice = $node->choice[$i];
       $percentage = round(100 * $votes[$i] / $total_votes, 0);
-      $output .= theme('advpoll_bar', _advpoll_choice_markup($choice['label'], $node->format, false), $percentage, format_plural($count, '1 vote', '@count votes'), $choice);
+      $output .= theme('advpoll_bar', _advpoll_choice_markup($choice['label'], $node->format, FALSE), $percentage, format_plural($count, '1 vote', '@count votes'), $choice);
     }
   }
 
@@ -249,16 +246,16 @@ function advpoll_voting_binary_form_vali
       $writein_option = TRUE;
     }
     // The choice is invalid (not between 0 and the write-in key).
-    elseif (!($form_values['choice'] > 0 ) && ($form_values['choice'] < $form_values['writein_key'])) {
+    elseif (!($form_values['choice'] > 0) && ($form_values['choice'] < $form_values['writein_key'])) {
       // Nothing is selected.
       _advpoll_form_set_error('choice[', t('At least one choice must be selected.'), $ajax);
     }
   }
   else {
-    // Approval voting
+    // Approval voting.
     $numchoices = 0;
     foreach ($node->choice as $i => $val) {
-      // see if the box is checked
+      // See if the box is checked.
       if ($form_values['choice'][$i]) {
         $numchoices++;
       }
@@ -272,14 +269,14 @@ function advpoll_voting_binary_form_vali
       $writein_option = TRUE;
     }
   
-    // Too many choices ranked
+    // Too many choices ranked.
     if ($node->maxchoices != 0 && $numchoices > $node->maxchoices) {
       $message = t('%num choices were selected but only %max are allowed.', array('%num' => $numchoices, '%max' => $node->maxchoices));
       _advpoll_form_set_error('choice[', $message, $ajax);
 
     }
 
-    // Not enough choices ranked
+    // Not enough choices ranked.
     $minchoices = 1;
     if ($numchoices < $minchoices) {
       _advpoll_form_set_error('choice[', t('At least one choice must be selected.'), $ajax);
Index: modes/ranking.inc
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/advpoll/modes/ranking.inc,v
retrieving revision 1.8.2.31
diff -u -p -r1.8.2.31 ranking.inc
--- modes/ranking.inc	6 Sep 2007 23:41:00 -0000	1.8.2.31
+++ modes/ranking.inc	7 Sep 2007 19:28:30 -0000
@@ -17,21 +17,18 @@ function advpoll_algorithms_ranking() {
 }
 
 function advpoll_voting_ranking_form(&$node, $teaser, $page, $status) {
-  $form = array();
-
   static $ranking_form_count = 0; 
-  $form['#id'] = 'advpoll_voting_ranking_form-'. $ranking_form_count++;
-  $form['#attributes'] = array('class' => 'advpoll-vote');
-
+  $form = array(
+    '#id' => 'advpoll_voting_ranking_form-'. $ranking_form_count++,
+    '#attributes' => array('class' => 'advpoll-vote'),
+  );
   $form['ajax'] = array(
     '#type' => 'hidden',
     '#attributes' => array('class' => 'ajax'),
   );
 
-
   if ($node->choice) {
     $list = array();
-
     $num_choices = count($node->choice);
 
     // Generate the list of possible rankings
@@ -48,21 +45,20 @@ function advpoll_voting_ranking_form(&$n
       }
       else {
         $val = t($i .'th');
-        // Fix to work around limitations in the current translation system. By 
-        // listing the strings here they are made immediately available for 
-        // translating. Listing up to 15 here, as it should be enough for most 
-        // users. If more are needed they are made available for translating in 
-        // Drupal when a poll with more than 15 choices has been created.
-        // TODO: Find a better solution for this.
-        $_make_translatable = array(t('4th'), t('5th'), t('6th'), t('7th'), t('8th'), t('9th'), t('10th'), t('11th'), t('12th'), t('13th'), t('14th'), t('15th'));
-
       }
       $choices[$i] = $val;
     }
+    // Fix to work around limitations in the current translation system. By 
+    // listing the strings here they are made immediately available for 
+    // translating. Listing up to 15 here, as it should be enough for most 
+    // users. If more are needed they are made available for translating in 
+    // Drupal when a poll with more than 15 choices has been created.
+    // TODO: Find a better solution for this.
+    array(t('4th'), t('5th'), t('6th'), t('7th'), t('8th'), t('9th'), t('10th'), t('11th'), t('12th'), t('13th'), t('14th'), t('15th'));
 
     $form['choice'] = array(
       '#tree' => TRUE,
-      // XXX: Workaround for FormAPI bug in PHP 4, see http://drupal.org/node/86657
+      // XXX: Workaround for FormAPI bug in PHP 4, see http://drupal.org/node/86657.
       '#type' => 'checkboxes',
       '#prefix' => '<div class="vote-choices">',
       '#suffix' => '</div>',
@@ -81,12 +77,12 @@ function advpoll_voting_ranking_form(&$n
 
     // Add write-in select box if write-ins are enabled and user has permission.
     if ($node->writeins && user_access('add write-ins')) {
-      $form['choice'][$key + 1] = array (
+      $form['choice'][$key + 1] = array(
         '#type' => 'select',
         '#title' => t('(write-in)'),
         '#options' => $choices,
       );
-      // Key index of the write-in option
+      // Key index of the write-in option.
       $form['writein_key'] = array(
         '#type' => 'value',
         '#value' => $key + 1,
@@ -96,7 +92,7 @@ function advpoll_voting_ranking_form(&$n
 
   // Add write-in text field if write-ins are enabled and user has permission.
   if ($node->writeins && user_access('add write-ins')) {
-    $form['writein_choice'] = array (
+    $form['writein_choice'] = array(
       '#prefix' => '<div class="writein-choice">',
       '#suffix' => '</div>',
       '#type' => 'textfield',
@@ -121,7 +117,7 @@ function advpoll_voting_ranking_form(&$n
     );
   }
   elseif ($node->in_preview) {
-    //Display nothing
+    // Display nothing.
   }
   elseif ($status == 'pending') {
     $form['message']['#value'] = t('This poll opens @time.', array('@time' => format_date($node->startdate)));
@@ -143,7 +139,7 @@ function advpoll_view_results_ranking($n
 
   // If no one has voted, $results = array() and thus is empty.
   if (!empty($results)) {
-    // Temporary list of choices indexes for the ranking
+    // Temporary list of choices indexes for the ranking.
     $ranking_list = array();
     // Result object
     $ranking = array();
@@ -153,12 +149,11 @@ function advpoll_view_results_ranking($n
     foreach ($results as $result) {
       $tag = $result->tag;
       if ($tag == '_advpoll') {
-        // Poll-wide cached value
+        // Poll-wide cached value.
         $poll[$result->function] = $result->value;
       }
       else if (strstr($tag, '_rounds_')) {
-        // Reconstruct round data.
-        // Extract the round from the tag.
+        // Re-construct round data and extract the round from the tag.
         $round = str_replace('_rounds_', '', $tag);
         if (!isset($rounds[$round])) {
           $rounds[$round] = array();
@@ -170,7 +165,7 @@ function advpoll_view_results_ranking($n
         // Note: choices that have been removed will not pass the previous
         // line's test even though their values are still in the vote table.
 
-        // Choice-specific cached value
+        // Choice-specific cached value.
         if ($result->function == 'ranking') {
           $ranking_list[$result->value][] = $tag;
         }
@@ -180,7 +175,7 @@ function advpoll_view_results_ranking($n
       }
     }
 
-    // Re-construct the rankings object
+    // Re-construct the rankings object.
     foreach ($ranking_list as $i => $choice_list) {
       $ranking[$i]->choices = array();
       foreach ($choice_list as $choice_i) {
@@ -195,38 +190,36 @@ function advpoll_view_results_ranking($n
 
     if ($node->algorithm == 'borda_count') {
       foreach ($ranking as $i => $ranking) {
-        $first_one = true;
+        $first_one = TRUE;
         $this_rank = '';
 
-        // Loop through all choices with this ranking
+        // Loop through all choices with this ranking.
         foreach ($ranking->choices as $choice) {
-          $label = isset($node->choice[$choice])? _advpoll_choice_markup($node->choice[$choice]['label'], $node->format, FALSE) . ($node->choice[$choice]['writein']? ' '. t('(write-in)') : '') : t('(deleted)');
+          $label = isset($node->choice[$choice]) ? _advpoll_choice_markup($node->choice[$choice]['label'], $node->format, FALSE) . ($node->choice[$choice]['writein']? ' '. t('(write-in)') : '') : t('(deleted)');
           $this_rank .= ($first_one ? '' : ', ') . $label;
-          $first_one = false;
+          $first_one = FALSE;
         }
 
         $percentage = round(100 * $ranking->percentage, 0);
         $output .= theme('advpoll_bar', $this_rank, $percentage, $ranking->viewscore);
-
       }
     }
     else {
       $output .= '<ol>';
-
       for ($i = 0; $i < count($ranking); $i++) {
         $output .= '<li> ';
-        $first_one = true;
+        $first_one = TRUE;
         // If previewing check the format against the current users permissions.
         $check = $node->in_preview;
 
-        // Loop through all choices with this ranking
+        // Loop through all choices with this ranking.
         foreach ($ranking[$i]->choices as $choice) {
-          $label = isset($node->choice[$choice])? _advpoll_choice_markup($node->choice[$choice]['label'], $node->format, FALSE) . ($node->choice[$choice]['writein']? ' '. t('(write-in)') : '') : t('(deleted)');
-          $output .= ($first_one? '' : ', ') . $label;
-          $first_one = false;
+          $label = isset($node->choice[$choice]) ? _advpoll_choice_markup($node->choice[$choice]['label'], $node->format, FALSE) . ($node->choice[$choice]['writein']? ' '. t('(write-in)') : '') : t('(deleted)');
+          $output .= ($first_one ? '' : ', ') . $label;
+          $first_one = FALSE;
         }
 
-        // Show the ranking's score if it exists (depends on algorithm)
+        // Show the ranking's score if it exists (depends on algorithm).
         if ($ranking[$i]->viewscore) {
           $output .= ' ('. $ranking[$i]->viewscore .'%)';
         }
@@ -261,6 +254,7 @@ function advpoll_view_results_ranking($n
     }
   }
   $output .= $round_table;
+  
   return array('results' => $output, 'votes' => $poll['total_votes']);
 }
 
@@ -285,7 +279,7 @@ function advpoll_calculate_results_ranki
     $results = _advpoll_calculate_instantrunoff($node);
   }
 
-  // Cache rankings
+  // Cache rankings.
   // API: $cache[$tag][$type][$function] = $value (0 is the default $type)
   for ($i = 0; $i < count($results->ranking); $i++) {
     foreach ($results->ranking[$i]['choices'] as $choice) {
@@ -298,7 +292,7 @@ function advpoll_calculate_results_ranki
     }
   }
 
-  // Cache round results
+  // Cache round results.
   if (isset($results->matrix)) {
     foreach ($results->matrix as $i => $round) {
       $key = '_rounds_'. $i;
@@ -309,10 +303,10 @@ function advpoll_calculate_results_ranki
     }
   }
 
-  // Cache total votes
+  // Cache total votes.
   $cache['_advpoll'][0]['total_votes'] = $results->total_votes;
 
-  // Cache total points (if it exists)
+  // Cache total points (if it exists).
   if (isset($results->total_points)) {
     $cache['_advpoll'][0]['total_points'] = $results->total_points;
   }
@@ -332,15 +326,15 @@ function advpoll_calculate_results_ranki
  *   -totalVoters : the total number of voters who participated
  */
 function _advpoll_calculate_bordacount($node) {
-   $votes = array();
-  // ORDER BY value ASC lets us ensure no gaps
-  $result = db_query("SELECT * FROM {votingapi_vote} v WHERE content_type='%s' AND content_id=%d ORDER BY value ASC", 'advpoll', $node->nid);
+  $votes = array();
+  // ORDER BY value ASC lets us ensure no gaps.
+  $result = db_query("SELECT * FROM {votingapi_vote} v WHERE content_type = '%s' AND content_id = %d ORDER BY value ASC", 'advpoll', $node->nid);
   while ($vobj = db_fetch_object($result)) {
     $votes[] = $vobj;
   }
 
   if (count($votes) == 0) {
-    // No votes yet
+    // No votes yet.
     return array();
   }
 
@@ -350,33 +344,30 @@ function _advpoll_calculate_bordacount($
 
   foreach ($votes as $vote) {
     if ($vote->uid == 0) {
-      // Anonymous user
+      // Anonymous user.
       $key = $vote->hostname;
     }
     else {
-      // Logged-in user
+      // Logged-in user.
       $key = $vote->uid;
     }
-
     $user_votes[$key][$vote->value] = $vote->tag;
   }
 
   $choice_votes = array();
-
   $total_choices = count($node->choice);
   $total_points = 0;
-
   // Loop through each user's vote
   foreach ($user_votes as $uid => $user_vote) {
     foreach ($user_vote as $ranking => $choice) {
       // Negative values are possible if choices were removed after vote
       $vote_value = max($total_choices - $ranking, 0);
-      $choice_votes[$choice] +=   $vote_value;
+      $choice_votes[$choice] += $vote_value;
       $total_points += $vote_value;
     }
   }
 
-  // Add any remaining choices that received no votes
+  // Add any remaining choices that received no votes.
   foreach ($node->choice as $i => $choice) {
     if (!isset($choice_votes[$i])) {
       // Didn't receive any votes
@@ -384,24 +375,23 @@ function _advpoll_calculate_bordacount($
     }
   }
 
-  // Sort descending (although there may be ties)
+  // Sort descending (although there may be ties).
   arsort($choice_votes);
 
-  // Figure out the final ranking
+  // Figure out the final ranking.
   $ranking = array();
   $previous_total = -1;
   $cur_result = -1;
 
   foreach ($choice_votes as $choice => $total) {
     if ($total != $previous_total) {
-      // Didn't tie with the previous score
+      // Didn't tie with the previous score.
       $cur_result++;
     }
     $ranking[$cur_result]['choices'][] = $choice;
     $ranking[$cur_result]['rawscore'] = $total;
-    $ranking[$cur_result]['viewscore'] = format_plural($total, '1 point',
-      '@count points');
-    $ranking[$cur_result]['percentage'] = $total_points? $total / $total_points : 0;
+    $ranking[$cur_result]['viewscore'] = format_plural($total, '1 point', '@count points');
+    $ranking[$cur_result]['percentage'] = $total_points ? $total / $total_points : 0;
     $previous_total = $total;
   }
 
@@ -428,15 +418,15 @@ function _advpoll_calculate_bordacount($
  *   -totalVoters : the total number of voters who participated
  */
 function _advpoll_calculate_instantrunoff($node) {
-   $votes = array();
-  // ORDER BY value ASC lets us ensure no gaps
-  $result = db_query("SELECT * FROM {votingapi_vote} v WHERE content_type='%s' AND content_id=%d ORDER BY value ASC", 'advpoll', $node->nid);
+  $votes = array();
+  // ORDER BY value ASC lets us ensure no gaps.
+  $result = db_query("SELECT * FROM {votingapi_vote} v WHERE content_type = '%s' AND content_id = %d ORDER BY value ASC", 'advpoll', $node->nid);
   while ($vobj = db_fetch_object($result)) {
     $votes[] = $vobj;
   }
 
   if (count($votes) == 0) {
-    // No votes yet
+    // No votes yet.
     return array();
   }
 
@@ -446,11 +436,11 @@ function _advpoll_calculate_instantrunof
 
   foreach ($votes as $vote) {
     if ($vote->uid == 0) {
-      // Anonymous user
+      // Anonymous user.
       $key = $vote->hostname;
     }
     else {
-      // Logged-in user
+      // Logged-in user.
       $key = $vote->uid;
     }
 
@@ -461,10 +451,10 @@ function _advpoll_calculate_instantrunof
 
   $total_votes = count($user_votes);
 
-  // Log of 1st-place votes per choice in each round
+  // Log of 1st-place votes per choice in each round.
   $round_log = array();
 
-  // Gradually append candidates as they are eliminated; end with the winner
+  // Gradually append candidates as they are eliminated; end with the winner.
   $reverse_ranking = array();
   
   // If we eliminate one choice per round and have n choices, we should
@@ -472,7 +462,7 @@ function _advpoll_calculate_instantrunof
   $max_rounds = count($node->choice); 
   for ($round = 0; $round < $max_rounds; $round++) {
 
-    // Initialize cur_round
+    // Initialize cur_round.
     $cur_round = array();
     $total_choices = count($node->choice);
 
@@ -480,10 +470,9 @@ function _advpoll_calculate_instantrunof
       $cur_round[$chi] = array();
     }
 
-    
-    // Loop through each user
+    // Loop through each user.
     foreach ($user_votes as $key => $user_vote) {
-      // $user_vote[0] contains the user's first remaining preference
+      // $user_vote[0] contains the user's first remaining preference.
       $cur_round[$user_vote[0]][] = $key;
     }
 
@@ -498,24 +487,23 @@ function _advpoll_calculate_instantrunof
       }
     }
 
-
-    // Add the current round to the matrix
+    // Add the current round to the matrix.
     $round_log[] = $cur_round;
 
-    // Calculate the min and max number of votes
+    // Calculate the min and max number of votes.
     $min_votes = -1;
     $max_votes = 0;
 
-    // Number of choices that have already been discarded
+    // Number of choices that have already been discarded.
     $num_discarded = 0;
 
-    // Examine the number of votes each choice received this round
+    // Examine the number of votes each choice received this round.
     foreach ($cur_round as $ch => $choice_votes) {
       $num_votes = count($choice_votes);
 
       if ($num_votes > $max_votes) {
         $max_votes = $num_votes;
-        // Store current winner in case it has a majority
+        // Store current winner in case it has a majority.
         $cur_winner = $ch;
       }
 
@@ -534,29 +522,29 @@ function _advpoll_calculate_instantrunof
     // ballots and may have already had all of their choices eliminated.
     if ($max_votes > count($user_votes) / 2) {
     
-      // Prune out the winning choice if it's still in there
+      // Prune out the winning choice if it's still in there.
       if (isset($cur_round[$cur_winner])) {
           unset($cur_round[$cur_winner]);
       }
 
-      // Keep computing until we figure out all final rankings
+      // Keep computing until we figure out all final rankings.
       while (count($cur_round)  > 0) {
-        // Loop through non-winning choices
+        // Loop through non-winning choices.
         $current_place = array();
         $min = -1;
         foreach ($cur_round as $ch => $choice_votes) {
-          // Choice has already been eliminated, just unset it
+          // Choice has already been eliminated, just unset it.
           if (count($choice_votes) == 0) {
             unset($cur_round[$ch]);
           }
           else if ($min == -1
               || count($choice_votes) < $min) {
-            // New minimum
+            // New minimum.
             $current_place = array($ch);
             $min = count($choice_votes);
           }
           else if (count($choice_votes) == $min) {
-            // Tied for minimum
+            // Tied for minimum.
             $current_place[] = $ch;
           }
         }
@@ -566,14 +554,14 @@ function _advpoll_calculate_instantrunof
         // at the beginning.
         if (count($current_place) > 0) {
           $reverse_ranking[]['choices'] = $current_place;  
-          // Remove all choices that had the minimum
+          // Remove all choices that had the minimum.
           foreach ($current_place as $ch_key) {
             unset($cur_round[$ch_key]);
           }
         }
       }
 
-      // Save a reversed version of the round log to help compute winnerPercent
+      // Save a reversed version of the round log to help compute winnerPercent.
       $revmat = array_reverse($round_log);
 
       // The winner finally gets added
@@ -597,7 +585,7 @@ function _advpoll_calculate_instantrunof
       if (count($choice_votes) == $min_votes) {
         $min_choices[] = $ch;
       }
-     }
+    }
 
     // Randomly select the choice to eliminate out of the available choices.
     // TODO: due to the randomness, this result must be cached after each vote.
@@ -605,9 +593,9 @@ function _advpoll_calculate_instantrunof
 
     $reverse_ranking[]['choices'] = array($min_choices[$round_loser]);
     
-    // Loop through the users who voted for the loser and redistribute
+    // Loop through the users who voted for the loser and redistribute.
     foreach ($cur_round[$min_choices[$round_loser]] as $user_key) {
-      // Remove their current first preference
+      // Remove their current first preference.
       array_shift($user_votes[$user_key]);
 
       // Keep eliminating first preference until we run out or find an choice
@@ -623,7 +611,7 @@ function _advpoll_calculate_instantrunof
     }
   }
   // Loop detected. Signal user and record.
-  drupal_set_message("Could not find a solution within $max_rounds iterations.");
+  drupal_set_message(t('Could not find a solution within @rounds iterations.', array('@rounds' => $max_rounds)));
   $result_obj->matrix = $round_log;
   $result_obj->total_votes = $total_votes;
   return $result_obj;
@@ -671,12 +659,12 @@ function advpoll_voting_ranking_form_val
   $node = node_load($form_values['nid']);
   $ajax = $form_values['ajax'];
   
-  // Check if user is eligible to vote
+  // Check if user is eligible to vote.
   if (!advpoll_eligible($node)) {
     _advpoll_form_set_error('choice[', t('You are not allowed to vote in this poll.'), $ajax);
   }
   
-  // Check if poll is active
+  // Check if poll is active.
   if (!_advpoll_is_active($node)) {
     _advpoll_form_set_error('choice[', t('This poll is closed.'), $ajax);
   }
@@ -685,15 +673,15 @@ function advpoll_voting_ranking_form_val
   $writein_option = FALSE;
   $writein_text = $form_values['writein_key'] ? $form_values['writein_choice'] : '';
 
-  // Check if user has already voted
+  // Check if user has already voted.
   list($voted, $cancel_vote) = _advpoll_user_voted($node->nid);
   if ($voted) {
     _advpoll_form_set_error('choice[', t('You have already voted in this poll.'), $ajax);
   }
 
-  // Array used to check which values are set
+  // Array used to check which values are set.
   $setvalues = array();
-  
+
   $numchoices = 0;
 
   // Write-ins are enabled, user has permission, and the write-in box is checked.
@@ -704,7 +692,6 @@ function advpoll_voting_ranking_form_val
   }
 
   foreach ($node->choice as $key => $choice) {
-    
     // Count the number of choices that are ranked.
     if ($form_values['choice'][$key]) {
       $numchoices++;
@@ -737,13 +724,13 @@ function advpoll_voting_ranking_form_val
   // Do validation specific to writeins.
   _advpoll_writeins_voting_form_validate($node, $writein_option, $writein_text, $ajax);
 
-  // Too many choices ranked
+  // Too many choices ranked.
   if ($node->maxchoices != 0 && $numchoices > $node->maxchoices) {
     $message = t('%num choices were selected but only %max are allowed.', array('%num' => $numchoices, '%max' => $node->maxchoices));
     _advpoll_form_set_error('choice', $message, $ajax);
   }
 
-  // Not enough choices ranked
+  // Not enough choices ranked.
   $minchoices = 1;
   if ($numchoices < $minchoices) {
     _advpoll_form_set_error('choice', t('At least one choice must be selected.'), $ajax);
@@ -766,7 +753,7 @@ function theme_advpoll_voting_ranking_fo
   
   $output = "<div class=\"poll\">\n";
   $output .= drupal_render($form);
-  if($message) {
+  if ($message) {
     $output .= "<p class=\"message\">$message</p>\n";
   }
   $output .= "</div>\n";
