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	8 Sep 2007 17:58:35 -0000
@@ -18,21 +18,21 @@ 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()) {
+    // Set focus at next or previous Remove link.
+    if (nextRemoveLink.html()) {
       nextRemoveLink[0].focus();
     }
     else {
@@ -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	8 Sep 2007 17:58:35 -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	8 Sep 2007 17:58:35 -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().
  */
@@ -13,13 +12,13 @@ function advpoll_install() {
         nid int(10) NOT NULL,
         quorum int(10) NOT NULL default '0',
         mode varchar(32) NOT NULL,
-        uselist tinyint default '0',
+        use_list tinyint default '0',
         active tinyint default '1',
-        maxchoices int unsigned NOT NULL default '0',
+        max_choices int unsigned NOT NULL default '0',
         algorithm VARCHAR(100),
-        showvotes tinyint,
-        startdate int NOT NULL default '0',
-        enddate int NOT NULL default '0',
+        show_votes tinyint,
+        start_date int NOT NULL default '0',
+        end_date int NOT NULL default '0',
         writeins tinyint NOT NULL default '0',
         show_writeins tinyint NOT NULL default '0',
         PRIMARY KEY (nid)
@@ -46,13 +45,13 @@ function advpoll_install() {
         nid integer NOT NULL,
         quorum integer NOT NULL DEFAULT '0',
         mode varchar(32) NOT NULL,
-        uselist smallint DEFAULT '0',
+        use_list smallint DEFAULT '0',
         active smallint DEFAULT '1',
-        maxchoices integer NOT NULL DEFAULT '0',
+        max_choices integer NOT NULL DEFAULT '0',
         algorithm varchar(100),
-        showvotes smallint,
-        startdate integer NOT NULL DEFAULT '0',
-        enddate integer NOT NULL DEFAULT '0',
+        show_votes smallint,
+        start_date integer NOT NULL DEFAULT '0',
+        end_date integer NOT NULL DEFAULT '0',
         writeins smallint NOT NULL DEFAULT '0',
         show_writeins smallint NOT NULL DEFAULT '0',
         PRIMARY KEY (nid)
@@ -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));
@@ -205,3 +204,46 @@ function advpoll_update_4() {
   }
   return $ret;
 }
+
+/**
+ * Conform to Drupal coding standards.
+ */
+function advpoll_update_5() {
+  $ret = array();
+  switch ($GLOBALS['db_type']) {
+    case 'mysql':
+    case 'mysqli':
+      $ret[] = update_sql("ALTER TABLE {advpoll} CHANGE uselist use_list tinyint default '0'");
+      $ret[] = update_sql("ALTER TABLE {advpoll} CHANGE startdate start_date tinyint NOT NULL default '0'");
+      $ret[] = update_sql("ALTER TABLE {advpoll} CHANGE enddate end_date integer NOT NULL default '0'");
+      $ret[] = update_sql("ALTER TABLE {advpoll} CHANGE maxchoices max_choices integer NOT NULL default '0'");
+      $ret[] = update_sql("ALTER TABLE {advpoll} CHANGE showvotes show_votes tinyint");
+      break;
+    case 'pgsql':
+      db_change_column($ret, 'advpoll', 'uselist', 'use_list', 'smallint', array('default' => '0'));
+      db_change_column($ret, 'advpoll', 'startdate', 'start_date', 'integer', array('not null' => TRUE, 'default' => '0'));
+      db_change_column($ret, 'advpoll', 'enddate', 'end_date', 'integer', array('not null' => TRUE, 'default' => '0'));
+      db_change_column($ret, 'advpoll', 'maxchoices', 'max_choices', 'integer', array('not null' => TRUE, 'default' => '0'));
+      db_change_column($ret, 'advpoll', 'showvotes', 'show_votes', 'smallint');
+      break;
+  }
+  // Migrate per-content type variables that changed names.
+  $content_types = array('advpoll_binary', 'advpoll_ranking');
+  $settings = array('maxchoices' => 'max_choices', 'showvotes' => 'show_votes');
+  foreach ($content_types as $type) {
+    foreach ($settings as $old => $new) {
+      $old_name = 'advpoll_'. $old .'_'. $type;
+      if (!is_null($value = variable_get($old_name, NULL))) {
+        variable_set('advpoll_'. $new .'_'. $type, $value);
+        variable_del($old_name);
+      }
+    }
+  }
+  // Update the block name.
+  $ret[] = update_sql('UPDATE {blocks} SET delta = "latest_poll" WHERE delta = "mostrecent"');
+  // Update Voting API cache.
+  $ret[] = update_sql('UPDATE {votingapi_cache} SET function = "view_score" WHERE function = "viewscore"');
+  $ret[] = update_sql('UPDATE {votingapi_cache} SET function = "raw_score" WHERE function = "rawscore"');
+
+  return $ret;
+}
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	8 Sep 2007 17:58:35 -0000
@@ -6,16 +6,35 @@
  * Advanced Poll - a sophisticated polling module for voting, elections, and group decision-making.
  */
 
-define('ADVPOLL_MAXCHOICES', 0);
+define('ADVPOLL_MAX_CHOICES', 0);
 define('ADVPOLL_RUNTIME', 0);
 define('ADVPOLL_ELECTORAL_LIST', 0);
-define('ADVPOLL_SHOWVOTES', 1);
+define('ADVPOLL_SHOW_VOTES', 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,16 +51,152 @@ 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->show_votes) {
+          $items[] = array(
+            'path' => 'node/'. $nid .'/votes',
+            'title' => t('Votes'),
+            'callback' => 'advpoll_votes_page',
+            'access' => user_access('inspect all votes'),
+            'weight' => 3,
+            'type' => MENU_LOCAL_TASK,
+          );
+        }
+
+        // Show electoral list tab if using the functionality.
+        if ($node->use_list) {
+          $items[] = array(
+            'path' => 'node/'. $nid .'/electoral_list',
+            'title' => t('Electoral list'),
+            'callback' => 'advpoll_electoral_list_page',
+            '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_writeins_page',
+              'access' => user_access('administer polls'),
+              'weight' => 3,
+              'type' => MENU_LOCAL_TASK,
+            );
+          }
+        }
+      }
+    }
+  }
+
+  return $items;
+}
+
+/**
  * Implementation of hook_block().
  */
 function advpoll_block($op = 'list') {
   switch ($op) {
     case 'list':
-      $blocks['mostrecent']['info'] = t('Latest poll');
+      $blocks['latest_poll']['info'] = t('Latest poll');
       return $blocks;
     case 'view':
       $block['subject'] = t('Latest poll');
-      $block['content'] = theme('advpoll_block_mostrecent');
+      $block['content'] = theme('advpoll_block_most_recent');
       return $block;
   }
 }
@@ -49,8 +204,8 @@ function advpoll_block($op = 'list') {
 /**
  * Content of the block, as returned by advpoll_block('view').
  */
-function theme_advpoll_block_mostrecent() {
-  $node = advpoll_mostrecent();
+function theme_advpoll_block_latest_poll() {
+  $node = advpoll_latest_poll();
   $output = '';
   if ($node) {
     $output .= '<h3>'. check_plain($node->title) .'</h3>';  
@@ -62,8 +217,8 @@ function theme_advpoll_block_mostrecent(
   return $output;
 }
 
-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');
+function advpoll_latest_poll() {
+  $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'],
@@ -237,12 +344,12 @@ function advpoll_form($node, $form_value
     $max_choice_list[$i] = ($i == 0 ? t('No limit') : $i);
   }
 
-  $form['settings']['maxchoices'] = array(
+  $form['settings']['max_choices'] = array(
     '#type' => 'select',
     '#title' => t('Maximum choices'),
-    '#default_value' => ($node->maxchoices? $node->maxchoices : variable_get('advpoll_maxchoices_'. $type->type, ADVPOLL_MAXCHOICES)),
+    '#default_value' => ($node->max_choices ? $node->max_choices : variable_get('advpoll_max_choices_'. $type->type, ADVPOLL_MAX_CHOICES)),
     '#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.')
   );
 
@@ -265,43 +372,41 @@ function advpoll_form($node, $form_value
     '#default_value' => isset($node->active) ? !$node->active : 0,
   );
 
-  $default_startdate = '';
-  $default_enddate = '';
+  $default_start_date = '';
+  $default_end_date = '';
   $time = format_date(time(), 'custom', 'Y-m-d H:i:s O');
   // Specify default dates if default duration is set and we are creating a node.
   if (variable_get('advpoll_runtime_'. $type->type, FALSE) && !isset($node->nid)) {
-    $default_startdate = $time;
-    $default_enddate = format_date(time() + variable_get('advpoll_runtime_'. $type->type, ''), 'custom', 'Y-m-d H:i:s O');
+    $default_start_date = $time;
+    $default_end_date = format_date(time() + variable_get('advpoll_runtime_'. $type->type, ''), 'custom', 'Y-m-d H:i:s O');
   }
   
-  $form['settings']['startdate'] = array(
+  $form['settings']['start_date'] = array(
     '#type' => 'textfield',
     '#title' => t('Starting date'),
     '#description' => t('The date that the poll opens. Format: %time. Leave blank if you want the poll to open now.', array('%time' => $time)),
     '#size' => 25,
     '#maxlength' => 25,
-    '#default_value' => $node->startdate ? format_date($node->startdate, 'custom', 'Y-m-d H:i:s O') : $default_startdate,
+    '#default_value' => $node->start_date ? format_date($node->start_date, 'custom', 'Y-m-d H:i:s O') : $default_start_date,
   );
-  
-  $form['settings']['enddate'] = array(
+  $form['settings']['end_date'] = array(
     '#type' => 'textfield',
     '#title' => t('Ending date'),
     '#description' => t('The date that the poll closes. Format: %time. Leave blank if you do not want the poll to close automatically.', array('%time' => $time)),
     '#size' => 25,
     '#maxlength' => 25,
-    '#default_value' => $node->enddate ? format_date($node->enddate, 'custom', 'Y-m-d H:i:s O') : $default_enddate,
+    '#default_value' => $node->end_date ? format_date($node->end_date, 'custom', 'Y-m-d H:i:s O') : $default_end_date,
   );
   
   // 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_use_list = isset($node->use_list) ? $node->use_list : variable_get('advpoll_electoral_list_'. $type->type, ADVPOLL_ELECTORAL_LIST);
+  $default_show_votes = isset($node->show_votes) ? $node->show_votes : variable_get('advpoll_show_votes_'. $type->type, ADVPOLL_SHOW_VOTES);
+  $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,19 +422,17 @@ function advpoll_form($node, $form_value
       '#prefix' => '<div class="edit-settings-show-writeins">',
       '#suffix' => '</div>',
     );
-
-    $form['settings']['uselist'] = array(
+    $form['settings']['use_list'] = 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,
+      '#default_value' => $default_use_list,
     );
-  
-    $form['settings']['showvotes'] = array(
+    $form['settings']['show_votes'] = array(
       '#type' => 'checkbox',
       '#title' => t('Show individual votes'),
       '#description' => t('Users with the appropriate permissions will be able to see how each person voted.'),
-      '#default_value' => $default_showvotes,
+      '#default_value' => $default_show_votes,
     );
     
     // Only show when editing a poll, not creating.
@@ -342,8 +444,8 @@ function advpoll_form($node, $form_value
     }
   }
   else {
-    // 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);
+    // Just pass the values for users without the "administer polls" permission.
+    $defaults = array('use_list' => $default_use_list, 'show_votes' => $default_show_votes, 'writeins' => $default_writeins, 'show_writeins' => $default_show_writeins);
     foreach ($defaults as $name => $value) {
       $form['settings'][$name] = array(
         '#type' => 'value',
@@ -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,12 +475,11 @@ function advpoll_form_alter($form_id, &$
         '#title' => t('Poll settings'),
         '#collapsible' => TRUE,
       );
-      
-      $form['advpoll']['advpoll_maxchoices'] = array(
+      $form['advpoll']['advpoll_max_choices'] = array(
         '#type' => 'select',
         '#title' => t('Default maximum choices'),
         '#options' => array(0 => t('No limit')) + drupal_map_assoc(array(1, 2, 3, 4, 5)),
-        '#default_value' => variable_get('advpoll_maxchoices_'. $node_type, ADVPOLL_MAXCHOICES),
+        '#default_value' => variable_get('advpoll_max_choices_'. $node_type, ADVPOLL_MAX_CHOICES),
         '#description' => t('The default number of maximum choices for new polls. This setting can be overridden on the poll edit page.'),
       );
       
@@ -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,19 +518,17 @@ 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(
+      $form['advpoll']['advpoll_show_votes'] = array(
         '#type' => 'checkbox',
         '#title' => t('Show individual votes by default'),
         '#description' => t('Let users with appropriate permissions see how each person voted 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_showvotes_'. $node_type, ADVPOLL_SHOWVOTES),
+        '#default_value' => variable_get('advpoll_show_votes_'. $node_type, ADVPOLL_SHOW_VOTES),
       );
     
       $view_results = array(
@@ -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;
@@ -485,8 +571,170 @@ function advpoll_load($node) {
     $poll->votes = 0;
   }
 
-  list($poll->voted, $poll->cancel_vote) = _advpoll_user_voted($node->nid);
-  return $poll;
+  list($poll->voted, $poll->cancel_vote) = _advpoll_user_voted($node->nid);
+  return $poll;
+}
+
+/**
+ * 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.
+    $real_choices = 0;
+    foreach ($node->choice as $i => $choice) {
+      if ($choice['label'] != '') {
+        $real_choices++;
+      }
+    }
+
+    if ($real_choices < 2) {
+      form_set_error("choice][$real_choices][label", t('You must fill in at least two choices.'));
+    }
+
+    // Validate max choices since it has #DANGEROUS_SKIP_CHECK set to true.
+    if ($node->settings['max_choices'] < 0) {
+      form_set_error('settings][max_choices]', t('Maximum choices must be a non-negative integer.'));
+    }
+
+    if ($node->settings['max_choices'] > count($node->choice)) {
+      form_set_error('settings][max_choices]', t('Maximum choices cannot be larger than the number of choices submitted.'));
+    }
+    
+    // Validate dates.
+    if (!empty($node->settings['start_date']) && strtotime($node->settings['start_date']) <= 0) {
+      form_set_error('settings][start_date', t('You have to specify a valid starting date.'));
+    }
+    if (!empty($node->settings['end_date']) && strtotime($node->settings['end_date']) <= 0) {
+      form_set_error('settings][end_date', t('You have to specify a valid ending date.'));
+    }
+    if (!empty($node->settings['end_date']) && $node->settings['end_date'] < $node->settings['start_date']) {
+      form_set_error('settings][end_date', t('Ending date cannot be before the starting date.'));
+    }
+  }
+}
+
+/**
+ * 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, use_list, active, max_choices, algorithm, show_votes, start_date, end_date, writeins, show_writeins) VALUES (%d, '%s', %d, %d, %d, '%s', %d, '%s', '%s', %d, %d)", $node->nid, $mode, $node->settings['use_list'], !$node->settings['close'], $node->settings['max_choices'], $node->settings['algorithm'], $node->settings['show_votes'], $node->settings['start_date'] ? strtotime($node->settings['start_date']) : 0, $node->settings['end_date'] ? strtotime($node->settings['end_date']) : 0, $node->settings['writeins'], $node->settings['show_writeins']);
+
+  // Insert the choices.
+  _advpoll_insert_choices($node->nid);
+}
+
+/**
+ * Implementation of hook_update().
+ *
+ * This is called upon node edition.
+ */
+function advpoll_update($node) {
+
+  db_query("UPDATE {advpoll} SET active = %d, max_choices = %d, algorithm = '%s', use_list = %d, show_votes = %d, start_date = '%s', end_date = '%s', writeins = %d, show_writeins = %d WHERE nid = %d", !$node->settings['close'], $node->settings['max_choices'], $node->settings['algorithm'], $node->settings['use_list'], $node->settings['show_votes'], $node->settings['start_date'] ? strtotime($node->settings['start_date']) : 0, $node->settings['end_date'] ? strtotime($node->settings['end_date']) : 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),
+    );
+  }
+  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);
+}
+
+/**
+ * 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);
+}
+
+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();
+  }
 }
 
 /**
@@ -513,7 +761,7 @@ function _advpoll_user_voted($nid) {
 
     // 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);
+    $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;
@@ -523,136 +771,16 @@ function _advpoll_user_voted($nid) {
 }
 
 /**
- * Implementation of hook_menu().
- */
-function advpoll_menu($may_cache) {
-  global $user;
-
-  // 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();
-
-  $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;
-}
-
-/**
- * Display the electoral list tab.
+ * Display the electoral list page.
  */
-function advpoll_tab_electoral_list() {
+function advpoll_electoral_list_page() {
   if ($node = node_load(arg(1))) {
-    if (!$node->uselist) {
+    // Bail out if electoral list isn't available for this node.
+    if (!$node->use_list) {
       drupal_not_found();
       return;
     }
+    
     drupal_set_title(check_plain($node->title));
     
     if (user_access('administer polls')) {
@@ -663,20 +791,20 @@ 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);
-    $eligible_voters = array();
+    $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);
+    $table_rows = array();
     while ($voter = db_fetch_object($result)) {
-      $temp = array(
+      $row = array(
         theme('username', $voter),
       );
 
       if (user_access('administer polls')) {
-        $temp[] = l(t('remove'), 'node/'. $node->nid .'/remove/'. $voter->uid);
+        $row[] = l(t('remove'), 'node/'. $node->nid .'/remove/'. $voter->uid);
       }
 
-      $eligible_voters[] = $temp;
+      $table_rows[] = $row;
     }
-    $output .= theme('table', $header, $eligible_voters);
+    $output .= theme('table', $header, $table_rows);
     $output .= theme('pager', NULL, 20, 0);
     print theme('page', $output);
   }
@@ -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,18 +933,18 @@ 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)));
   }
 }
 
 /**
- * Display the votes tab.
+ * Display the votes page.
  */
-function advpoll_tab_votes() {
+function advpoll_votes_page() {
   if ($node = node_load(arg(1))) {
-    if (!$node->showvotes) {
-      // Advanced Poll is set to not allow viewing of votes
+    if (!$node->show_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,61 +1013,22 @@ 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) {
   $active = TRUE;
   $status = 'open';
-  $startdate = $node->startdate;
-  $enddate = $node->enddate;
+  $start_date = $node->start_date;
+  $end_date = $node->end_date;
 
   // Check if poll is closed.
   if (!$node->active) {
@@ -951,26 +1036,20 @@ function _advpoll_is_active($node, $retu
     $status = 'closed';
   }
 
-  if ($active && $startdate > 0) {
-    // Check that startdate is in the past.
-    if (!$active = time() >= $startdate) {
+  if ($active && $start_date > 0) {
+    // Check that start date is in the past.
+    if (!$active = time() >= $start_date) {
       $status = 'pending';
     }
   }
 
-  if ($active && ($enddate > 0)) {
-    // Check that enddate is in the future.
-    if (!$active = time() < $enddate) {
+  if ($active && ($end_date > 0)) {
+    // Check that end date is in the future.
+    if (!$active = time() < $end_date) {
       $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);
   }  
@@ -1286,9 +1254,8 @@ function advpoll_eligible($node, $uid = 
     $uid = $user->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;
+  if ($node->use_list) {
+    $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>'));
@@ -1386,7 +1352,7 @@ function _advpoll_writeins_voting_form_v
  * Voting form submission logic specific to writeins. This has been abstracted 
  * away from includes in the modes directory.
  */
-function _advpoll_writeins_voting_form_submit($node, $form_values, &$vote, $vote_value) {
+function _advpoll_writeins_voting_form_submit($node, $form_values, &$votes, $vote_value) {
   // A write-in vote is being made.
   if ($form_values['writein_choice']) {
     // Check if someone has previously voted for this choice.
@@ -1402,11 +1368,11 @@ function _advpoll_writeins_voting_form_s
       $obj = db_fetch_object($result);
       $existing_vote_offset = $obj->vote_offset;
       // Set a vote
-      unset($temp);
-      $temp->value = $vote_value;
-      $temp->tag = $existing_vote_offset;
-      $temp->value_type = 'option';
-      $vote[] = $temp;
+      $vote = new stdClass();
+      $vote->value = $vote_value;
+      $vote->tag = $existing_vote_offset;
+      $vote->value_type = 'option';
+      $votes[] = $vote;
     }
     // This write-in choice has not been previously voted for.
     else {
@@ -1418,16 +1384,16 @@ function _advpoll_writeins_voting_form_s
       db_query("INSERT INTO {advpoll_choices} (nid, label, vote_offset, writein) VALUES (%d, '%s', %d, 1)", $node->nid, check_plain($form_values['writein_choice']), $next_offset);
       
       // Add vote
-      unset($temp);
-      $temp->value = $vote_value;
-      $temp->tag = $next_offset;
-      $temp->value_type = 'option';
-      $vote[] = $temp;
+      $vote = new stdClass();
+      $vote->value = $vote_value;
+      $vote->tag = $next_offset;
+      $vote->value_type = 'option';
+      $votes[] = $vote;
     }
   }
 }
 
-function advpoll_tab_writeins() {
+function advpoll_writeins_page() {
   $node = node_load(arg(1));
   drupal_set_title(check_plain($node->title));
   $output .= drupal_get_form('advpoll_writein_promote_form', $node);
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	8 Sep 2007 17:58:35 -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,13 +54,9 @@ function advpoll_voting_binary_form(&$no
       '#suffix' => '</div>',
     );
 
-    if ($node->in_preview) {
-      $maxchoices = $node->settings['maxchoices'];
-    }
-    else {
-      $maxchoices = $node->maxchoices; 
-    }
-    if ($maxchoices == 1) {
+    $max_choices = $node->in_preview ? $node->settings['max_choices'] : $node->max_choices; 
+
+    if ($max_choices == 1) {
       // Plurality voting
       $form['choice']['#type'] = 'radios';
       $form['choice']['#default_value'] = -1;
@@ -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)));
@@ -120,23 +117,23 @@ function advpoll_view_results_binary($no
   $results = votingapi_get_voting_results($content_type, $content_id);
   $votes = array();
   foreach ($results as $result) {
-    $voteval = $result->tag;
+    $vote_value = $result->tag;
     if ($voteval == '_advpoll') {
       if ($result->function == 'total_votes') {
         $total_votes = $result->value;
       }
     }
-    else if (isset($node->choice[$voteval])) {
-      if (!$votes[$voteval]) {
-        $votes[$voteval] = 0;
+    else if (isset($node->choice[$vote_value])) {
+      if (!$votes[$vote_value]) {
+        $votes[$vote_value] = 0;
       }
-      $votes[$voteval] = $result->value;
+      $votes[$vote_value] = $result->value;
     }
   }
 
   if ($node->choice && $total_votes > 0) {
     // Add in any choices that received no votes.
-    foreach ($node->choice as $i => $ch) {
+    foreach ($node->choice as $i => $choice) {
       if (!isset($votes[$i])) {
         $votes[$i] = 0;
       }
@@ -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);
     }
   }
 
@@ -174,40 +171,40 @@ function advpoll_calculate_results_binar
  * Registers the vote as a key for this node using votingapi_set_vote().
  */
 function advpoll_voting_binary_form_submit($form_id, $form_values) {
-  $vote = array();
+  $votes = array();
   $node = node_load($form_values['nid']);
 
   // Do submission specific to writeins.
-  _advpoll_writeins_voting_form_submit($node, $form_values, $vote, 1);
+  _advpoll_writeins_voting_form_submit($node, $form_values, $votes, 1);
 
-  if ($node->maxchoices == 1) {
+  if ($node->max_choices == 1) {
     // Plurality voting
     // Ignore write-in choice that has already been taken care of.
     if (!$node->writeins || !$form_values['choice'][$form_values['writein_key']]) {
-      $temp->value = 1;
-      $temp->tag = $form_values['choice'];
-      $temp->value_type = 'option';
-      $vote[] = $temp;
+      $vote->value = 1;
+      $vote->tag = $form_values['choice'];
+      $vote->value_type = 'option';
+      $votes[] = $vote;
     }
   }
   else {
     // Approval voting
     foreach ($form_values['choice'] as $choice => $selected) {
+      $vote = new stdClass();
       // Ignore write-in choice that has already been taken care of.
       if (!$node->writeins || $choice != $form_values['writein_key']) {
-        unset($temp);
-        $temp->value = $choice;
+        $vote->value = $choice;
         if ($selected) {
-          $temp->value_type = 'option';
-          $temp->tag = $choice;
-          $temp->value = 1;
-          $vote[] = $temp;
+          $vote->value_type = 'option';
+          $vote->tag = $choice;
+          $vote->value = 1;
+          $votes[] = $vote;
         }
       }
     }
   }
 
-  votingapi_set_vote('advpoll', $form_values['nid'], $vote);
+  votingapi_set_vote('advpoll', $form_values['nid'], $votes);
   _advpoll_vote_response($node, $form_values);
 }
 
@@ -241,7 +238,7 @@ function advpoll_voting_binary_form_vali
     _advpoll_form_set_error('choice[', t('You have already voted in this poll.'), $ajax);
   }
 
-  if ($node->maxchoices == 1) {
+  if ($node->max_choices == 1) {
     // Plurality voting
     // Write-ins are enabled, user has permission, and it's the write-in option.
     if ($node->writeins && user_access('add write-ins') && ($form_values['choice'] == $form_values['writein_key'])) {
@@ -249,39 +246,39 @@ 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
-    $numchoices = 0;
+    // Approval voting.
+    $num_choices = 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++;
+        $num_choices++;
       }
     }
 
     // Write-ins are enabled, user has permission, and the write-in box is checked.
     if ($node->writeins && user_access('add write-ins') && $form_values['choice'][$form_values['writein_key']]) {
       // Add one to number of choices for check on min/max boxes checked.
-      $numchoices++;
+      $num_choices++;
       // Set the flag to true for additional checks.
       $writein_option = TRUE;
     }
   
-    // 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));
+    // Too many choices ranked.
+    if ($node->max_choices != 0 && $numchoices > $node->max_choices) {
+      $message = t('%num choices were selected but only %max are allowed.', array('%num' => $num_choices, '%max' => $node->max_choices));
       _advpoll_form_set_error('choice[', $message, $ajax);
 
     }
 
-    // Not enough choices ranked
-    $minchoices = 1;
-    if ($numchoices < $minchoices) {
+    // Not enough choices ranked.
+    $min_choices = 1;
+    if ($num_choices < $min_choices) {
       _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	8 Sep 2007 17:58:35 -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,13 +175,13 @@ 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) {
         $ranking[$i]->choices[] = $choice_i;
-        $ranking[$i]->viewscore = $choices[$choice_i]['viewscore'];
-        $ranking[$i]->rawscore = $choices[$choice_i]['rawscore'];
+        $ranking[$i]->view_score = $choices[$choice_i]['view_score'];
+        $ranking[$i]->raw_score = $choices[$choice_i]['raw_score'];
         if ($choices[$choice_i]['percentage']) {
           $ranking[$i]->percentage = $choices[$choice_i]['percentage'];
         }    
@@ -195,40 +190,38 @@ 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);
-
+        $output .= theme('advpoll_bar', $this_rank, $percentage, $ranking->view_score);
       }
     }
     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)
-        if ($ranking[$i]->viewscore) {
-          $output .= ' ('. $ranking[$i]->viewscore .'%)';
+        // Show the ranking's score if it exists (depends on algorithm).
+        if ($ranking[$i]->view_score) {
+          $output .= ' ('. $ranking[$i]->view_score .'%)';
         }
         $output .= '</li>';
       }
@@ -261,6 +254,7 @@ function advpoll_view_results_ranking($n
     }
   }
   $output .= $round_table;
+  
   return array('results' => $output, 'votes' => $poll['total_votes']);
 }
 
@@ -285,20 +279,20 @@ 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) {
       $cache[$choice][0]['ranking'] = $i;
-      $cache[$choice][0]['rawscore'] = $results->ranking[$i]['rawscore'];
-      $cache[$choice][0]['viewscore'] = $results->ranking[$i]['viewscore'];
+      $cache[$choice][0]['raw_score'] = $results->ranking[$i]['raw_score'];
+      $cache[$choice][0]['view_score'] = $results->ranking[$i]['view_score'];
       if (isset($results->ranking[$i]['percentage'])) {
         $cache[$choice][0]['percentage'] = $results->ranking[$i]['percentage'];
       }
     }
   }
 
-  // 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]['raw_score'] = $total;
+    $ranking[$cur_result]['view_score'] = 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,50 +462,48 @@ 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);
 
-    foreach ($node->choice as $chi => $temp) {
-      $cur_round[$chi] = array();
+    foreach ($node->choice as $key => $data) {
+      $cur_round[$key] = 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;
     }
 
     if ($round == 0) {
       // This is the first round.
       // Any choices with no first-place votes are considered eliminated.
-      foreach ($cur_round as $ch => $choice_votes) {
+      foreach ($cur_round as $key => $choice_votes) {
         if (count($choice_votes) == 0) {
-          unset($cur_round[$ch]);
-          $reverse_ranking[0]['choices'][] = $ch;
+          unset($cur_round[$key]);
+          $reverse_ranking[0]['choices'][] = $key;
         }
       }
     }
 
-
-    // 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,21 +554,21 @@ 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
       $reverse_ranking[]['choices'] = array($cur_winner);
       $index = count($reverse_ranking) - 1;
-      $reverse_ranking[$index]['rawscore'] = round(count($revmat[0][$cur_winner]) * 100 / count($user_votes), 1);
-      $reverse_ranking[$index]['viewscore'] = $reverse_ranking[$index]['rawscore'] .'%';
+      $reverse_ranking[$index]['raw_score'] = round(count($revmat[0][$cur_winner]) * 100 / count($user_votes), 1);
+      $reverse_ranking[$index]['view_score'] = $reverse_ranking[$index]['raw_score'] .'%';
 
       $result_obj->matrix = $round_log;
       $result_obj->total_votes = $total_votes;
@@ -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;
@@ -635,27 +623,27 @@ function _advpoll_calculate_instantrunof
  * This takes care of registering the vote in runoff nodes.
  */
 function advpoll_voting_ranking_form_submit($form_id, $form_values) {
-  $vote = array();
+  $votes = array();
   $node = node_load($form_values['nid']);
 
   // Do submission specific to writeins.
-  _advpoll_writeins_voting_form_submit($node, $form_values, $vote, $form_values['choice'][$form_values['writein_key']]);
+  _advpoll_writeins_voting_form_submit($node, $form_values, $votes, $form_values['choice'][$form_values['writein_key']]);
 
   foreach ($form_values['choice'] as $choice => $rank) {
+    $vote = new stdClass();
     // Ignore write-in choice that has already been taken care of.
     if (!$node->writeins || $choice != $form_values['writein_key']) {
-      unset($temp);
-      $temp->value = $rank;
+      $vote->value = $rank;
       // A zero value indicates they didn't rank that choice.
-      if ($temp->value != 0) {
-        $temp->value_type = 'option';
-        $temp->tag = $choice;
-        $vote[] = $temp;
+      if ($vote->value != 0) {
+        $vote->value_type = 'option';
+        $vote->tag = $choice;
+        $votes[] = $vote;
       }
     }
   }
 
-  votingapi_set_vote('advpoll', $form_values['nid'], $vote);
+  votingapi_set_vote('advpoll', $form_values['nid'], $votes);
   _advpoll_vote_response($node, $form_values);
 }
 
@@ -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,50 +673,49 @@ 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
-  $setvalues = array();
-  
-  $numchoices = 0;
+  // Array used to check which values are set.
+  $set_values = array();
+
+  $num_choices = 0;
 
   // Write-ins are enabled, user has permission, and the write-in box is checked.
   if ($node->writeins && user_access('add write-ins') && $form_values['choice'][$form_values['writein_key']]) {
-    $numchoices++;
+    $num_choices++;
     // Set a flag for additional checks.
     $writein_option = TRUE;
   }
 
   foreach ($node->choice as $key => $choice) {
-    
     // Count the number of choices that are ranked.
     if ($form_values['choice'][$key]) {
-      $numchoices++;
+      $num_choices++;
     }
-    $intvalue = intval($form_values['choice'][$key]);
+    $int_value = intval($form_values['choice'][$key]);
     // Mark this value as seen
-    $setvalues[$intvalue]++;
+    $set_values[$intvalue]++;
     // Check range
-    if ($intvalue > count($node->choice) || $intvalue < 0) {
+    if ($int_value > count($node->choice) || $int_value < 0) {
       // TODO: clean up this error message
-      $message = "Illegal rank for choice $key: $intvalue (min: 1, max: ". count($node->choice) .')';
+      $message = "Illegal rank for choice $key: $int_value (min: 1, max: ". count($node->choice) .')';
       _advpoll_form_set_error('choice]['. $key, $message, $ajax);
     }
   }
 
   // Write-ins are enabled, user has permission, and the write-in box is checked.
   if ($writein_option) {
-    $intvalue = intval($form_values['choice'][$form_values['writein_key']]);
+    $int_value = intval($form_values['choice'][$form_values['writein_key']]);
     // Mark this value as seen
-    $setvalues[$intvalue]++;
+    $set_values[$int_value]++;
     // Check range
-    if ($intvalue > count($node->choice) || $intvalue < 0) {
+    if ($int_value > count($node->choice) || $int_value < 0) {
       // TODO: clean up this error message
-      $message = "Illegal rank for the write-in choice: $intvalue (min: 1, max: ". count($node->choice) .')';
+      $message = "Illegal rank for the write-in choice: $int_value (min: 1, max: ". count($node->choice) .')';
       _advpoll_form_set_error('choice]['. $form_values['writein_key'], $message, $ajax);
       $ok = FALSE;
     }
@@ -737,20 +724,20 @@ 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
-  if ($node->maxchoices != 0 && $numchoices > $node->maxchoices) {
-    $message = t('%num choices were selected but only %max are allowed.', array('%num' => $numchoices, '%max' => $node->maxchoices));
+  // Too many choices ranked.
+  if ($node->max_choices != 0 && $num_choices > $node->max_choices) {
+    $message = t('%num choices were selected but only %max are allowed.', array('%num' => $num_choices, '%max' => $node->max_choices));
     _advpoll_form_set_error('choice', $message, $ajax);
   }
 
-  // Not enough choices ranked
-  $minchoices = 1;
-  if ($numchoices < $minchoices) {
+  // Not enough choices ranked.
+  $min_choices = 1;
+  if ($num_choices < $min_choices) {
     _advpoll_form_set_error('choice', t('At least one choice must be selected.'), $ajax);
   }
 
   // Check that multiple choices are not set to the same value.
-  foreach ($setvalues as $val => $count) {
+  foreach ($set_values as $val => $count) {
     if ($val != 0 && $count > 1) {
       $message = t('Multiple choices given the rank of %value.', array('%value' => $val));
       _advpoll_form_set_error('choice', $message, $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";
