Index: taxonomy_breadcrumb.inc
===================================================================
RCS file: /cvs/drupal/contributions/modules/taxonomy_breadcrumb/taxonomy_breadcrumb.inc,v
retrieving revision 1.1.2.3
diff -u -r1.1.2.3 taxonomy_breadcrumb.inc
--- taxonomy_breadcrumb.inc	31 May 2009 19:37:18 -0000	1.1.2.3
+++ taxonomy_breadcrumb.inc	5 Aug 2009 02:56:11 -0000
@@ -45,20 +45,51 @@
 }
 
 /**
- * Return lightest term for given node ($nid).
- * Similar to taxonomy_node_get_terms, but only return the lightest term in the
- * lightest vocab for the node.
+ * Return lightest term for a given node.
  */
-function _taxonomy_breadcrumb_node_get_lightest_term($nid) {
-
-  // We only want the first row of the result. This is the lightest term of the
-  // lightest vocab.
-  $result = db_query(db_rewrite_sql('SELECT t.* FROM {term_node} r INNER JOIN {term_data} t ON r.tid = t.tid INNER JOIN {term_hierarchy} h ON t.tid = h.tid INNER JOIN {vocabulary} v ON t.vid = v.vid WHERE r.nid = %d ORDER BY v.weight, h.parent DESC, t.weight, t.name', 't', 'tid'), $nid);
-
-  // Extract the first row of query.
-  $term = db_fetch_object($result);
-
-  return $term;
+function _taxonomy_breadcrumb_node_get_lightest_term($node) {
+  $terms = taxonomy_node_get_terms($node);
+  if (!empty($terms)) {
+    if (count($terms) > 1) {
+      foreach ($terms as $term) {
+        // Only consider terms in the lightest vocabulary. 
+        if (!isset($vid)) {
+          $vid = $term->vid;
+        }
+        elseif ($term->vid != $vid) continue;
+        // If the term has parents, the weight of the term is the weight of the lightest parent.
+        $parents = taxonomy_get_parents_all($term->tid);
+        $depth = count($parents);
+        if ($depth > 0) {
+          $parent = array_pop($parents);
+          $weight = $parent->weight;
+        }
+        else {
+          $weight = $term->weight;
+        }
+        if ((isset($lweight) && ($weight < $lweight)) || !isset($lweight)) {
+          $lterm = $term;
+          $lweight = $weight;
+          $ldepth = $depth;
+        }
+        elseif (isset($lweight) && ($weight == $lweight)) {
+          // If the node has multiple child terms with the same parent, choose the child with the greatest depth.
+          if ($depth > $ldepth) {
+            $lterm = $term;
+            $ldepth = $depth;
+          }
+          elseif ($depth == $ldepth) {
+            // If the terms have the same depth, pick the term with the lightest weight.
+            $lterm = ($lterm->weight < $term->weight) ? $lterm : $term;
+          }
+        }
+      }
+      return $lterm;
+    }
+    else {
+      return array_pop($terms);
+    }
+  }
 }
 
 /**
