Browse Source

merged term_reference_tree submodule

Bachir Soussi Chiadmi 9 years ago
parent
commit
c2252c8f9a
16 changed files with 2375 additions and 0 deletions
  1. 339 0
      sites/all/modules/contrib/taxonomy/term_reference_tree/LICENSE.txt
  2. 5 0
      sites/all/modules/contrib/taxonomy/term_reference_tree/images/README.txt
  3. BIN
      sites/all/modules/contrib/taxonomy/term_reference_tree/images/bullet_delete.png
  4. BIN
      sites/all/modules/contrib/taxonomy/term_reference_tree/images/bullet_move.png
  5. BIN
      sites/all/modules/contrib/taxonomy/term_reference_tree/images/bullet_toggle_minus.png
  6. BIN
      sites/all/modules/contrib/taxonomy/term_reference_tree/images/bullet_toggle_plus.png
  7. BIN
      sites/all/modules/contrib/taxonomy/term_reference_tree/images/dotted_corner.png
  8. BIN
      sites/all/modules/contrib/taxonomy/term_reference_tree/images/dotted_line.png
  9. 34 0
      sites/all/modules/contrib/taxonomy/term_reference_tree/term_reference_tree-missing-vocabulary-machine-name.patch.txt
  10. 157 0
      sites/all/modules/contrib/taxonomy/term_reference_tree/term_reference_tree.css
  11. 89 0
      sites/all/modules/contrib/taxonomy/term_reference_tree/term_reference_tree.field.inc
  12. 13 0
      sites/all/modules/contrib/taxonomy/term_reference_tree/term_reference_tree.info
  13. 375 0
      sites/all/modules/contrib/taxonomy/term_reference_tree/term_reference_tree.js
  14. 238 0
      sites/all/modules/contrib/taxonomy/term_reference_tree/term_reference_tree.module
  15. 226 0
      sites/all/modules/contrib/taxonomy/term_reference_tree/term_reference_tree.module.orig
  16. 899 0
      sites/all/modules/contrib/taxonomy/term_reference_tree/term_reference_tree.widget.inc

+ 339 - 0
sites/all/modules/contrib/taxonomy/term_reference_tree/LICENSE.txt

@@ -0,0 +1,339 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                    GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+  2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) Accompany it with the complete corresponding machine-readable
+    source code, which must be distributed under the terms of Sections
+    1 and 2 above on a medium customarily used for software interchange; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable.  However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+  5. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+  7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded.  In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation.  If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission.  For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this.  Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+                            NO WARRANTY
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License along
+    with this program; if not, write to the Free Software Foundation, Inc.,
+    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+    Gnomovision version 69, Copyright (C) year name of author
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+  `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+  <signature of Ty Coon>, 1 April 1989
+  Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.

+ 5 - 0
sites/all/modules/contrib/taxonomy/term_reference_tree/images/README.txt

@@ -0,0 +1,5 @@
+The icons contained in this directory are from the FatCow "Farm-Fresh Web Icons" 
+collection, available under the Creative Commons Attribution 3.0 license.  They
+can be downloaded here:
+
+http://www.fatcow.com/free-icons

BIN
sites/all/modules/contrib/taxonomy/term_reference_tree/images/bullet_delete.png


BIN
sites/all/modules/contrib/taxonomy/term_reference_tree/images/bullet_move.png


BIN
sites/all/modules/contrib/taxonomy/term_reference_tree/images/bullet_toggle_minus.png


BIN
sites/all/modules/contrib/taxonomy/term_reference_tree/images/bullet_toggle_plus.png


BIN
sites/all/modules/contrib/taxonomy/term_reference_tree/images/dotted_corner.png


BIN
sites/all/modules/contrib/taxonomy/term_reference_tree/images/dotted_line.png


+ 34 - 0
sites/all/modules/contrib/taxonomy/term_reference_tree/term_reference_tree-missing-vocabulary-machine-name.patch.txt

@@ -0,0 +1,34 @@
+diff --git a/htdocs/sites/default/modules/contrib/term_reference_tree/term_reference_tree.module b/htdocs/sites/default/modules/contrib/term_reference_tree/term_reference_tree.module
+index f479a0e..70343fc 100644
+--- a/htdocs/sites/default/modules/contrib/term_reference_tree/term_reference_tree.module
++++ b/htdocs/sites/default/modules/contrib/term_reference_tree/term_reference_tree.module
+@@ -82,10 +82,17 @@ function _term_reference_tree_get_term_hierarchy($tid, $vid, &$allowed, $filter,
+
+   $result = array();
+
++  $vocab = taxonomy_vocabulary_load( $vid );
++
+   if ($filter != '') {
+     foreach($allowed as $k => $v) {
+       if (array_key_exists($k, $terms)) {
+         $term =& $terms[$k];
++
++        if ( !isset($term->vocabulary_machine_name) && !empty($vocab) ) {
++          $term->vocabulary_machine_name = $vocab->machine_name;
++        }
++
+         $children = _term_reference_tree_get_term_hierarchy($term->tid, $vid, $allowed, $filter, $label, $default);
+         if (is_array($children)) {
+           $term->children = $children;
+@@ -102,6 +109,11 @@ function _term_reference_tree_get_term_hierarchy($tid, $vid, &$allowed, $filter,
+   else {
+     foreach($terms as &$term) {
+       if ($filter == '' || array_key_exists($term->tid, $allowed)) {
++
++        if ( !isset($term->vocabulary_machine_name) && !empty($vocab) ) {
++          $term->vocabulary_machine_name = $vocab->machine_name;
++        }
++
+         $children = _term_reference_tree_get_term_hierarchy($term->tid, $vid, $allowed, $filter, $label, $default);
+         if (is_array($children)) {
+           $term->children = $children;

+ 157 - 0
sites/all/modules/contrib/taxonomy/term_reference_tree/term_reference_tree.css

@@ -0,0 +1,157 @@
+.item-list .field-widget-term-reference-tree ul,
+.block .field-widget-term-reference-tree ul,
+.field-widget-term-reference-tree ul
+{
+  list-style-type: none; 
+  margin-top: 0;
+  margin-bottom: 0;
+  margin-left: 0;
+}
+
+.item-list .field-widget-term-reference-tree ul ul,
+.block .field-widget-term-reference-tree ul ul,
+.field-widget-term-reference-tree ul ul
+{
+  margin-left: 1.5em;
+}
+
+.item-list .field-widget-term-reference-tree ul .form-item,
+.block .field-widget-term-reference-tree ul .form-item,
+.field-widget-term-reference-tree ul .form-item {
+  margin: 0;
+  padding: 0;
+}
+
+.term-reference-tree-button,
+.no-term-reference-tree-button {
+  width: 16px;
+  height: 16px;
+  display: inline-block;
+  *display: inline;
+  zoom: 1;
+  vertical-align: middle;
+  margin-right: 4px;
+}
+
+.term-reference-tree-button {
+  background-image: url('images/bullet_toggle_minus.png');
+}
+
+.no-term-reference-tree-button {
+  background-color: #ddd;
+}
+
+.term-reference-tree-button.term-reference-tree-collapsed {
+  background-image: url('images/bullet_toggle_plus.png');
+}
+
+.field-widget-term-reference-tree .form-item {
+  display: inline-block;
+  *display: inline;
+  zoom: 1;
+}
+
+.field-widget-term-reference-tree .disabled {
+  opacity: .5;
+}
+
+.field-widget-term-reference-tree .parent-term {
+  display: inline-block;
+  *display: inline;
+  zoom: 1;
+  font-weight: bold;
+}
+
+.form-type-checkbox-tree .error {
+  background-image: none;
+  border: 2px solid red;
+  padding: 3px;
+}
+
+.region-content ul.term-reference-tree-level,
+.term-reference-tree-level
+{
+  padding: 0;
+}
+
+/*
+ * Styles for track list of selected options.
+ */
+
+.term-reference-tree-track-list li {
+  list-style-type: none;
+  list-style-image: none;
+  margin-left: 10px;
+  padding-left: 20px;
+  min-height: 16px;
+  cursor: pointer;
+}
+
+.term-reference-tree-track-list li.track-item:hover {
+  color: red;
+  background-image: url("images/bullet_delete.png");
+  background-repeat: no-repeat;
+  background-position: middle left;
+}
+
+.term-reference-tree-track-list.order-list li.track-item {
+	padding-left:0;
+}
+
+.term-reference-tree-track-list.order-list li.track-item:hover {
+	color:#000;
+	background-image: none;
+}
+
+.term-reference-tree-track-list.order-list .term-reference-tree-button-move, .term-reference-tree-track-list.order-list .term-reference-tree-button-delete{
+	display:inline-block; vertical-align:middle; zoom:1;
+	width:16px; height:16px;
+	background-repeat: no-repeat;
+	background-position: bottom center;
+	margin:0 5px;
+}
+
+
+.term-reference-tree-track-list.order-list li.track-item .term-reference-tree-button-move{
+	background-image: url("images/bullet_move.png");
+}
+.term-reference-tree-track-list.order-list li.track-item .term-reference-tree-button-move:hover{
+	cursor:move;
+}
+.term-reference-tree-track-list.order-list li.track-item .term-reference-tree-button-delete{
+	background-image: url("images/bullet_delete.png"); float:right;
+}
+.term-reference-tree-track-list.order-list li.track-item .term-reference-tree-button-:hover{
+	cursor:pointer;
+}
+
+.term-reference-tree-track-list li.term_ref_tree_nothing_message {
+  list-style-type: none;
+  list-style-image: none;
+  font-style: italic;
+  cursor: default;
+}
+
+.term-reference-track-list-container {
+  padding: 5px;
+}
+
+.term-reference-track-list-label {
+  font-weight: bold;
+}
+
+/*
+ * Styles for display element
+ */
+
+.field-widget-term-reference-tree .selected {
+  font-weight: bold;
+}
+
+.field-widget-term-reference-tree .unselected {
+  font-weight: normal;
+}
+
+.field-widget-term-reference-tree ul {
+  margin-top: 0;
+}

+ 89 - 0
sites/all/modules/contrib/taxonomy/term_reference_tree/term_reference_tree.field.inc

@@ -0,0 +1,89 @@
+<?php
+
+/**
+ * Implements hook_field_formatter_info().
+ */
+function term_reference_tree_field_formatter_info() {
+  return array(
+    'term_reference_tree' => array(
+      'label' => 'Term reference tree',
+      'field types' => array('taxonomy_term_reference'),
+      'settings' => array(
+        'token_display_selected' => '',
+        'token_display_unselected' => '',
+      ),
+    ),
+  );
+}
+
+
+/**
+ * Implements hook_field_formatter_view().
+ */
+function term_reference_tree_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
+  $element = array();
+
+  switch ($display['type']) {
+    case 'term_reference_tree':
+      $element[] = array(
+        '#theme' => 'term_tree_list',
+        '#data' => $items,
+        '#display' => $display,
+        '#attached' => array('css' => array(drupal_get_path('module', 'term_reference_tree') . '/term_reference_tree.css')),
+      );
+      break;
+  }
+
+  return $element;
+}
+
+
+/**
+ * Implements hook_field_formatter_settings_form().
+ */
+function term_reference_tree_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
+  $display = $instance['display'][$view_mode];
+  $settings = $display['settings'];
+
+  $element = array();
+  if ($display['type'] == 'term_reference_tree' && module_exists('token')) {
+    $element['token_display_selected'] = array(
+      '#type' => 'textarea',
+      '#title' => 'Custom Term Label',
+      '#description' => t("Use tokens to change the term label.  Leave this field blank to use the term name linked to its taxonomy page."),
+      '#default_value' => $settings['token_display_selected'],
+    );
+
+    $element['token_display_unselected'] = array(
+      '#type' => 'textarea',
+      '#title' => 'Custom Term Label (unselected)',
+      '#description' => t("Use tokens to change the term label for unselected parent terms.  Leave this field blank to use the same tokens as above."),
+      '#default_value' => $settings['token_display_unselected'],
+    );
+
+    $element['tokens_list'] = array(
+      '#theme' => 'token_tree',
+      '#token_types' => array('term'),
+    );
+  }
+  
+  return $element;
+}
+
+
+/**
+ * Implements hook_field_formatter_settings_summary().
+ */
+function term_reference_tree_field_formatter_settings_summary($field, $instance, $view_mode) {
+  $display = $instance['display'][$view_mode];
+  $settings = $display['settings'];
+
+  $summary = '';
+
+  if ($display['type'] == 'term_reference_tree') {
+    $summary = t('Uses tokens: ') . t($settings['token_display_selected'] != '' ? 'Yes' : 'No');
+  }
+
+  return $summary;
+}
+

+ 13 - 0
sites/all/modules/contrib/taxonomy/term_reference_tree/term_reference_tree.info

@@ -0,0 +1,13 @@
+name = Term Reference Tree
+description = An expanding/collapsing tree widget for selecting terms in a taxonomy term reference field
+package = Other
+core = 7.x
+
+dependencies[] = taxonomy
+
+; Information added by drupal.org packaging script on 2012-03-26
+version = "7.x-1.9"
+core = "7.x"
+project = "term_reference_tree"
+datestamp = "1332793846"
+

+ 375 - 0
sites/all/modules/contrib/taxonomy/term_reference_tree/term_reference_tree.js

@@ -0,0 +1,375 @@
+(function($) {
+  Drupal.behaviors.termReferenceTree = {
+    attach: function(context, settings) {
+      // Bind the term expand/contract button to slide toggle the list underneath.
+      $('.term-reference-tree-button', context).click(function() {
+        $(this).toggleClass('term-reference-tree-collapsed');
+        $(this).siblings('ul').slideToggle('fast');
+      });
+
+      // An expand all button (unimplemented)
+      /*
+      $('.expandbutton').click(function() {
+        $(this).siblings('.term-reference-tree-button').trigger('click');
+      });
+      */
+
+
+      $('.term-reference-tree', context).each(function() {
+        // On page load, check whether the maximum number of choices is already selected.
+        // If so, disable the other options.
+        var tree = $(this);
+        checkMaxChoices(tree, false);
+        $(this).find('input[type=checkbox]').change(function() {
+          checkMaxChoices(tree, $(this));
+        });
+        
+        //On page load, check if the user wants a track list. If so, add the 
+        //currently selected items to it.
+        if($(this).hasClass('term-reference-tree-track-list-shown')) {
+          var track_list_container = $(this).find('.term-reference-tree-track-list');
+          var tracklist_is_orderable = track_list_container.is('.order-list');
+					if(tracklist_is_orderable){
+						// track_list_container.sortable({
+						// 	update: function(event, ui) {
+						// 		console.log('sort update : event', event);
+						// 		// console.log('sort update : ui', ui);
+						// 
+						// 		$.each(event.target.children, function(index, val) {
+						// 			var $item = $(val),
+						// 		// event.target = ul.list
+						// 		// ui.item = li.track-item
+						// 					control_id = $item.data('control_id'),
+						// 					$hiddenInput = $('#'+control_id).parent('.form-item').next('input[type=hidden]');
+						// 					// $hiddenInput.attr('value', $item.index());
+						// 					$hiddenInput.val($item.index());
+						// 		});
+						// 	},
+						// });
+						
+						track_list_container.sortable();
+						
+						track_list_container.bind('sortupdate', function(event, ui) {
+							console.log('sort update : event', event);
+							// console.log('sort update : ui', ui);
+
+							$.each(event.target.children, function(index, val) {
+								var $item = $(val),
+							// event.target = ul.list
+							// ui.item = li.track-item
+										control_id = $item.data('control_id'),
+										$hiddenInput = $('#'+control_id).parent('.form-item').next('input[type=hidden]');
+										// $hiddenInput.attr('value', $item.index());
+										$hiddenInput.val($item.index());
+							});
+						});
+						
+					}
+					
+          //Var to track whether using checkboxes or radio buttons.
+          var input_type =
+            ( $(this).has('input[type=checkbox]').size() > 0 ) ? 'checkbox' : 'radio';
+            
+          //Find all the checked controls.
+          var checked_controls = $(this).find('input[type=' + input_type + ']:checked');
+
+          //Get their labels.
+          var labels = checked_controls.next();
+          var label_element;
+          
+					//get delta
+					if(tracklist_is_orderable){
+						var weights = checked_controls.parent('.form-item').next('input[type=hidden]');
+					}
+
+          //For each label of the checked boxes, add item to the track list.
+          labels.each(function(index) {
+            label_element = $(labels[index]);
+						delta = tracklist_is_orderable ? $(weights[index]).val() : -1;
+						
+            addItemToTrackList(
+              track_list_container,         //Where to add new item.
+              label_element.html(),         //Text of new item.
+              $(label_element).attr('for'), //Id of control new item is for.
+              input_type,                   //checkbox or radio
+							delta													//delta
+            );
+          }); //End labels.each
+          
+          //Show "nothing selected" message, if needed.
+          showNothingSelectedMessage(track_list_container);
+          
+          //Event - when an element on the track list is clicked on:
+          //  1. Delete it.
+          //  2. Uncheck the associated checkbox.
+          //The event is bound to the track list container, not each element.
+          $(track_list_container).click(function(event){
+            //Remove the "nothing selected" message if showing - add it later if needed.
+            //removeNothingSelectedMessage(track_list_container);
+            var event_target = $(event.target);
+						var event_parent_list = event_target.parent('li');
+            var control_id = event_parent_list.data('control_id');
+						// console.log('event', event);
+						// console.log('event_target.parent("li")', event_target.parent('li'));
+						// console.log('control_id', control_id);
+						// console.log('event_target.is(term-reference-tree-delete)', event_target.is('term-reference-tree-delete'));
+            if(event_target.is('.term-reference-tree-button-delete') && control_id) {
+              event_parent_list.remove();
+
+              var checkbox = $('#' + control_id);
+              checkbox.removeAttr('checked');
+              checkMaxChoices(tree, checkbox);
+
+              //Show "nothing selected" message, if needed.
+              showNothingSelectedMessage(track_list_container);
+            }
+          });
+          
+          //Change track list when controls are clicked.
+          $(this).find('.form-' + input_type).change(function(event){
+            //Remove the "nothing selected" message if showing - add it later if needed.
+            removeNothingSelectedMessage(track_list_container);
+            var event_target = $(event.target);
+            var control_id = event_target.attr('id');
+            if ( event_target.attr('checked') ) {
+              //Control checked - add item to the track list.
+              label_element = event_target.next();
+              addItemToTrackList(
+                track_list_container,         //Where to add new item.
+                label_element.html(),         //Text of new item.
+                $(label_element).attr('for'), //Id of control new item is for.
+                input_type,                   //checkbox or radio
+								-1													// delta
+              );
+            }
+            else {
+              //Checkbox unchecked. Remove from the track list.
+              $('#' + control_id + '_list').remove();
+            }
+            
+            //Show "nothing selected" message, if needed.
+            showNothingSelectedMessage(track_list_container);
+          }); //End process checkbox changes.
+        } //End Want a track list.
+        
+        //On page load, check if the user wants a cascading selection.
+        if($(this).hasClass('term-reference-tree-cascading-selection')) {
+
+          //Check children when checkboxes are clicked.
+          $(this).find('.form-checkbox').change(function(event) {
+            var event_target = $(event.target);
+            var control_id = event_target.attr('id');
+            var children = event_target.parent().next().children().children('div.form-type-checkbox').children('input[id^="' + control_id + '-children"]');
+            if(event_target.attr('checked')) {
+              //Checkbox checked - check children if none were checked.
+              if(!$(children).filter(':checked').length) {
+                $(children).click().trigger('change');
+              }
+            }
+            else {
+              //Checkbox unchecked. Uncheck children if all were checked.
+              if(!$(children).not(':checked').length) {
+                $(children).click().trigger('change');
+              }
+            }
+
+          });
+          //End process checkbox changes.
+        } //End Want a cascading checking.
+
+      });
+    }
+  };
+  
+  /**
+   * Add a new item to the track list. 
+   * If more than one item can be selected, the new item is positioned to 
+   * match the order of the terms in the checkbox tree.
+   * 
+   * @param track_list_container Container where the new item will be added.
+   * 
+   * @param item_text Text of the item to add.
+   * 
+   * @param control_id Id of the checkbox/radio control the item matches.
+   * 
+   * @param control_type Control type - 'checkbox' or 'radio'.
+   */
+  function addItemToTrackList(track_list_container, item_text, control_id, control_type, delta) {
+		// console.log('addItemToTrackList');
+    var new_item = $('<li class="track-item" delta="'+ delta +'"><div class="term-reference-tree-button-move"></div>' + item_text + '<div class="term-reference-tree-button-delete"></div></li>');
+    new_item.data('control_id', control_id);
+    
+    //Add an id for easy finding of the item.
+    new_item.attr('id', control_id + '_list');
+    
+    //Process radio controls - only one item can be selected.
+    if ( control_type == 'radio') {
+      //Find the existing element on the track list, if there is one.
+      var current_items = track_list_container.find('li');
+      
+      //If there are no items on the track list, add the new item.
+      if ( current_items.size() == 0 ) {
+        track_list_container.append(new_item);
+      }
+      else {
+        //There is an item on the list.
+        var current_item = $(current_items.get(0));
+        
+        //Is the item we want to add different from what is there?
+        if ( current_item.data('control_id') != control_id ) {
+          //Remove exiting element from track list, and add the new one.
+          current_item.remove();
+          track_list_container.append(new_item);
+        }
+      }
+      return;
+    }
+
+		//Using checkboxes, so there can be more than one selected item.
+    //Find the right place to put the new item, 
+		// to match the order of the checkboxes.
+		// OR order of delta
+    var list_items = track_list_container.find('li');
+    var item_comparing_to;
+  
+    //Flag to tell whether the item was inserted.
+    var inserted_flag = false;
+
+		if(!track_list_container.is('.order-list')){
+	    
+	    list_items.each(function(index){
+	      item_comparing_to = $(list_items[index]);
+      
+	      //If item is already on the track list, do nothing.
+	      if ( control_id == item_comparing_to.data('control_id') ) {
+	        inserted_flag = true;
+	        return false; //Returning false stops the loop.
+	      }
+	      else if ( control_id < item_comparing_to.data('control_id') ) {
+	        //Add it here.
+	        item_comparing_to.before(new_item);
+	        inserted_flag = true;
+	        return false; //Returning false stops the loop.
+	      }
+	    });
+    
+	    //If not inserted yet, add new item at the end of the track list.
+	    if ( ! inserted_flag ) {
+      	track_list_container.append(new_item);
+	    }
+		
+		}else{
+			if( ! track_list_container.find('#'+new_item.attr('id')).size() ){
+				
+				if(delta == -1){
+					track_list_container.append(new_item);				
+					inserted_flag = true;
+					$hiddenInput = $('#'+control_id).parent('.form-item').next('input[type=hidden]');
+					// console.log('$hiddenInput',$hiddenInput);
+					$hiddenInput.val(new_item.index());
+					
+				}else{
+					list_items.each(function(index){
+			      item_comparing_to = $(this);
+						if ( parseInt(delta) < parseInt(item_comparing_to.attr('delta')) ) {
+			        //Add it here.
+			        item_comparing_to.before(new_item);
+			        inserted_flag = true;
+			        return false; //Returning false stops the loop.
+			      }
+			    });
+			    //If not inserted yet, add new item at the end of the track list.
+			    if ( ! inserted_flag )
+		      	track_list_container.append(new_item);
+		    
+				}
+				
+				
+				track_list_container.sortable('refresh');
+				track_list_container.trigger( "sortupdate");
+			}
+		}
+		
+  }
+  
+  /**
+   * Show the 'nothing selected' message if it applies.
+   * 
+   * @param track_list_container Where the message is to be shown.
+   */
+  function showNothingSelectedMessage(track_list_container) {
+    //Is the message there already?
+    var message_showing = 
+        (track_list_container.find('.term_ref_tree_nothing_message').size() != 0);
+        
+    //Number of real items showing.
+    var num_real_items_showing = 
+        message_showing 
+        ? track_list_container.find('li').size() - 1
+        : track_list_container.find('li').size();
+    if ( num_real_items_showing == 0 ) {
+      //No items showing, so show the message.
+      if ( ! message_showing ) {
+        track_list_container.append(
+            '<li class="term_ref_tree_nothing_message">' + termReferenceTreeNothingSelectedText + '</li>'
+        );
+      }
+    }
+    else { // !(num_real_items_showing == 0)
+      //There are real items.
+      if ( message_showing ) {
+        track_list_container.find('.term_ref_tree_nothing_message').remove();
+      }
+    }
+  }
+
+  /**
+   * Remove the 'nothing selected' message. Makes processing easier.
+   * 
+   * @param track_list_container Where the message is shown.
+   */
+  function removeNothingSelectedMessage(track_list_container) {
+    track_list_container.find('.term_ref_tree_nothing_message').remove();
+  }
+
+  // This helper function checks if the maximum number of choices is already selected.
+  // If so, it disables all the other options.  If not, it enables them.
+  function checkMaxChoices(item, checkbox, order_list) {
+    var maxChoices = -1;
+    try {
+      maxChoices = parseInt(Drupal.settings.term_reference_tree.trees[item.attr('id')]['max_choices']);
+    }
+    catch (e){}
+    var count = item.find(':checked').length;
+    
+    if(maxChoices > 0 && count >= maxChoices) {
+      item.find('input[type=checkbox]:not(:checked)').attr('disabled', 'disabled').parent().addClass('disabled');
+    } else {
+      item.find('input[type=checkbox]').removeAttr('disabled').parent().removeClass('disabled');
+    }
+
+    if(checkbox) {
+      if(item.hasClass('select-parents')) {
+        var track_list_container = item.find('.term-reference-tree-track-list');
+        var input_type =
+            ( item.has('input[type=checkbox]').size() > 0 ) ? 'checkbox' : 'radio';
+            
+        if(checkbox.attr('checked')) {
+          checkbox.parents('ul.term-reference-tree-level li').children('div.form-item').children('input[type=checkbox]').each(function() {
+            $(this).attr('checked', checkbox.attr('checked'));
+            
+            if(track_list_container) {
+              label_element = $(this).next();
+              addItemToTrackList(
+                track_list_container,         //Where to add new item.
+                label_element.html(),         //Text of new item.
+                $(label_element).attr('for'), //Id of control new item is for.
+                input_type                    //checkbox or radio
+              );
+            }
+          });
+        }
+      }
+    }
+  }
+})(jQuery);

+ 238 - 0
sites/all/modules/contrib/taxonomy/term_reference_tree/term_reference_tree.module

@@ -0,0 +1,238 @@
+<?php
+
+module_load_include('inc', 'term_reference_tree', 'term_reference_tree.field');
+module_load_include('inc', 'term_reference_tree', 'term_reference_tree.widget');
+
+/**
+ * Implements hook_element_info().
+ */
+function term_reference_tree_element_info() {
+  $types = array(
+    'checkbox_tree' => array(
+      '#input' => true,
+      '#process' => array('term_reference_tree_process_checkbox_tree'),
+      '#theme' => array('checkbox_tree'),
+      '#pre_render' => array('form_pre_render_conditional_form_element'),
+    ),
+    'checkbox_tree_level' => array(
+      '#input' => false,
+      '#theme' => array('checkbox_tree_level'),
+      '#pre_render' => array('form_pre_render_conditional_form_element'),
+    ),
+    'checkbox_tree_item' => array(
+      '#input' => false,
+      '#theme' => array('checkbox_tree_item'),
+      '#pre_render' => array('form_pre_render_conditional_form_element'),
+    ),
+    'checkbox_tree_label' => array(
+      '#input' => false,
+      '#theme' => array('checkbox_tree_label'),
+      '#pre_render' => array('form_pre_render_conditional_form_element'),
+    ),
+    'checkbox_tree_track_list' => array(
+      '#input' => false,
+      '#theme' => array('checkbox_tree_track_list'),
+      '#pre_render' => array('form_pre_render_conditional_form_element'),
+    )
+  );
+  
+  return $types;
+}
+
+/**
+ * Implements hook_theme().
+ */
+function term_reference_tree_theme() {
+  return array(
+    'checkbox_tree' => array(
+      'render element' => 'element',
+    ),
+    'checkbox_tree_level' => array(
+      'render element' => 'element',
+    ),
+    'checkbox_tree_item' => array(
+      'render element' => 'element',
+    ),
+    'checkbox_tree_label' => array(
+      'render element' => 'element',
+    ),
+    'checkbox_tree_track_list' => array(
+      'render element' => 'element',
+    ),
+    'term_tree_list' => array(
+      'render element' => 'element',
+    ),
+  );
+}
+
+
+/**
+ * This function returns a taxonomy term hierarchy in a nested array.
+ *
+ * @param $tid
+ *   The ID of the root term.
+ * @param $vid
+ *   The vocabulary ID to restrict the child search.
+ *
+ * @return
+ *   A nested array of the term's child objects.  
+ */
+function _term_reference_tree_get_term_hierarchy($tid, $vid, &$allowed, $filter, $label, $default = array()) {
+  $terms = _term_reference_tree_get_children($tid, $vid, $default);
+  
+  $result = array();
+
+  $vocab = taxonomy_vocabulary_load( $vid );
+
+  if ($filter != '') {
+    foreach($allowed as $k => $v) {
+      if (array_key_exists($k, $terms)) {
+        $term =& $terms[$k];
+
+        if ( !isset($term->vocabulary_machine_name) && !empty($vocab) ) {
+          $term->vocabulary_machine_name = $vocab->machine_name;
+        }
+
+        $children = _term_reference_tree_get_term_hierarchy($term->tid, $vid, $allowed, $filter, $label, $default);
+        if (is_array($children)) {
+          $term->children = $children;
+          $term->children_selected = _term_reference_tree_children_selected($term, $default); 
+        } 
+        else {
+          $term->children_selected = FALSE;
+        }
+        $term->TEST = $label;
+        array_push($result, $term);
+      }      
+    }
+  }
+  else {
+    foreach($terms as &$term) {
+      if ($filter == '' || array_key_exists($term->tid, $allowed)) {
+
+        if ( !isset($term->vocabulary_machine_name) && !empty($vocab) ) {
+          $term->vocabulary_machine_name = $vocab->machine_name;
+        }
+
+        $children = _term_reference_tree_get_term_hierarchy($term->tid, $vid, $allowed, $filter, $label, $default);
+        if (is_array($children)) {
+          $term->children = $children;
+          $term->children_selected = _term_reference_tree_children_selected($term, $default);        
+        } 
+        else {
+          $term->children_selected = FALSE;
+        }
+        $term->TEST = $label;
+        array_push($result, $term);
+      }
+    }
+  }
+  
+  return $result;
+}
+
+/**
+ * This function is like taxonomy_get_children, except it doesn't load the entire term.
+ *
+ * @param $tid
+ *   The ID of the term whose children you want to get.
+ * @param $vid
+ *   The vocabulary ID.
+ *
+ * @return
+ *   An array of taxonomy terms, each in the form array('tid' => $tid, 'name' => $name)
+ */
+function _term_reference_tree_get_children($tid, $vid) {
+  // DO NOT LOAD TAXONOMY TERMS HERE
+  // Taxonomy terms take a lot of time and memory to load, and this can be
+  // very bad on large vocabularies.  Instead, we load the term as necessary
+  // in cases where it's needed (such as using tokens or when the locale
+  // module is enabled).
+  $select = db_select('taxonomy_term_data', 'd');
+  $select->join('taxonomy_term_hierarchy', 'h', 'd.tid = h.tid');
+  $result = $select->fields('d', array('tid', 'vid', 'name'))
+    ->condition('d.vid', $vid, '=')
+    ->condition('h.parent', $tid, '=')
+    ->orderBy('weight')
+    ->orderBy('name')
+    ->orderBy('tid')
+    ->execute();
+
+  $terms = array();
+  while($term = $result->fetchAssoc()) {
+    $terms[$term['tid']] = (object) $term;
+  }
+
+  return $terms;
+}
+
+function _term_reference_tree_children_selected($terms, $default) {
+  foreach($terms->children as $term) {
+    if(isset($default[$term->tid]) || $term->children_selected) {
+      return true;
+    }
+  }
+  return false;
+}
+
+function _term_reference_tree_get_parent($tid) {
+  $q = db_query_range("select h.parent from {taxonomy_term_hierarchy} h where h.tid = :tid", 0, 1, array(':tid'  => $tid));
+
+  $t = 0;
+  foreach($q as $term) {
+    $t = $term->parent;
+  }
+
+  return $t;
+}
+
+/**
+ * Recursively go through the option tree and return a flat array of
+ * options
+ */
+function _term_reference_tree_flatten($element, &$form_state) {
+  $output = array();
+  $children = element_children($element);
+  foreach($children as $c) {
+    $child = $element[$c];
+		// dsm($child, '$child');
+    if (array_key_exists('#type', $child) && ($child['#type'] == 'radio' || $child['#type'] == 'checkbox')) {
+      $output[] = $child;
+    }
+    else {
+      $output = array_merge($output, _term_reference_tree_flatten($child, $form_state));
+    }
+  }
+  return $output;
+}
+
+/**
+ * Return an array of options.
+ * 
+ * This function converts a list of taxonomy terms to a key/value list of options.
+ * 
+ * @param $terms
+ *   An array of taxonomy term IDs.
+ * @param $allowed
+ *   An array containing the terms allowed by the filter view
+ * @param $filter
+ *   A string defining the view to filter by (only used to detect whether view
+ *   filtering is enabled
+ * 
+ * @return
+ *   A key/value array of taxonomy terms (name => id)
+ */
+function _term_reference_tree_get_options(&$terms, &$allowed, $filter) {
+  $options = array();
+
+  if (is_array($terms) && count($terms) > 0) {
+    foreach($terms as $term) {
+      if (!$filter || (is_array($allowed) && $allowed[$term->tid])) {
+        $options[$term->tid] = entity_label('taxonomy_term', $term);
+        $options += _term_reference_tree_get_options($term->children, $allowed, $filter);
+      }
+    }
+  }
+  return $options;
+}
+

+ 226 - 0
sites/all/modules/contrib/taxonomy/term_reference_tree/term_reference_tree.module.orig

@@ -0,0 +1,226 @@
+<?php
+
+module_load_include('inc', 'term_reference_tree', 'term_reference_tree.field');
+module_load_include('inc', 'term_reference_tree', 'term_reference_tree.widget');
+
+/**
+ * Implements hook_element_info().
+ */
+function term_reference_tree_element_info() {
+  $types = array(
+    'checkbox_tree' => array(
+      '#input' => true,
+      '#process' => array('term_reference_tree_process_checkbox_tree'),
+      '#theme' => array('checkbox_tree'),
+      '#pre_render' => array('form_pre_render_conditional_form_element'),
+    ),
+    'checkbox_tree_level' => array(
+      '#input' => false,
+      '#theme' => array('checkbox_tree_level'),
+      '#pre_render' => array('form_pre_render_conditional_form_element'),
+    ),
+    'checkbox_tree_item' => array(
+      '#input' => false,
+      '#theme' => array('checkbox_tree_item'),
+      '#pre_render' => array('form_pre_render_conditional_form_element'),
+    ),
+    'checkbox_tree_label' => array(
+      '#input' => false,
+      '#theme' => array('checkbox_tree_label'),
+      '#pre_render' => array('form_pre_render_conditional_form_element'),
+    ),
+    'checkbox_tree_track_list' => array(
+      '#input' => false,
+      '#theme' => array('checkbox_tree_track_list'),
+      '#pre_render' => array('form_pre_render_conditional_form_element'),
+    )
+  );
+  
+  return $types;
+}
+
+/**
+ * Implements hook_theme().
+ */
+function term_reference_tree_theme() {
+  return array(
+    'checkbox_tree' => array(
+      'render element' => 'element',
+    ),
+    'checkbox_tree_level' => array(
+      'render element' => 'element',
+    ),
+    'checkbox_tree_item' => array(
+      'render element' => 'element',
+    ),
+    'checkbox_tree_label' => array(
+      'render element' => 'element',
+    ),
+    'checkbox_tree_track_list' => array(
+      'render element' => 'element',
+    ),
+    'term_tree_list' => array(
+      'render element' => 'element',
+    ),
+  );
+}
+
+
+/**
+ * This function returns a taxonomy term hierarchy in a nested array.
+ *
+ * @param $tid
+ *   The ID of the root term.
+ * @param $vid
+ *   The vocabulary ID to restrict the child search.
+ *
+ * @return
+ *   A nested array of the term's child objects.  
+ */
+function _term_reference_tree_get_term_hierarchy($tid, $vid, &$allowed, $filter, $label, $default = array()) {
+  $terms = _term_reference_tree_get_children($tid, $vid, $default);
+  
+  $result = array();
+
+  if ($filter != '') {
+    foreach($allowed as $k => $v) {
+      if (array_key_exists($k, $terms)) {
+        $term =& $terms[$k];
+        $children = _term_reference_tree_get_term_hierarchy($term->tid, $vid, $allowed, $filter, $label, $default);
+        if (is_array($children)) {
+          $term->children = $children;
+          $term->children_selected = _term_reference_tree_children_selected($term, $default); 
+        } 
+        else {
+          $term->children_selected = FALSE;
+        }
+        $term->TEST = $label;
+        array_push($result, $term);
+      }      
+    }
+  }
+  else {
+    foreach($terms as &$term) {
+      if ($filter == '' || array_key_exists($term->tid, $allowed)) {
+        $children = _term_reference_tree_get_term_hierarchy($term->tid, $vid, $allowed, $filter, $label, $default);
+        if (is_array($children)) {
+          $term->children = $children;
+          $term->children_selected = _term_reference_tree_children_selected($term, $default);        
+        } 
+        else {
+          $term->children_selected = FALSE;
+        }
+        $term->TEST = $label;
+        array_push($result, $term);
+      }
+    }
+  }
+  
+  return $result;
+}
+
+/**
+ * This function is like taxonomy_get_children, except it doesn't load the entire term.
+ *
+ * @param $tid
+ *   The ID of the term whose children you want to get.
+ * @param $vid
+ *   The vocabulary ID.
+ *
+ * @return
+ *   An array of taxonomy terms, each in the form array('tid' => $tid, 'name' => $name)
+ */
+function _term_reference_tree_get_children($tid, $vid) {
+  // DO NOT LOAD TAXONOMY TERMS HERE
+  // Taxonomy terms take a lot of time and memory to load, and this can be
+  // very bad on large vocabularies.  Instead, we load the term as necessary
+  // in cases where it's needed (such as using tokens or when the locale
+  // module is enabled).
+  $select = db_select('taxonomy_term_data', 'd');
+  $select->join('taxonomy_term_hierarchy', 'h', 'd.tid = h.tid');
+  $result = $select->fields('d', array('tid', 'vid', 'name'))
+    ->condition('d.vid', $vid, '=')
+    ->condition('h.parent', $tid, '=')
+    ->orderBy('weight')
+    ->orderBy('name')
+    ->orderBy('tid')
+    ->execute();
+
+  $terms = array();
+  while($term = $result->fetchAssoc()) {
+    $terms[$term['tid']] = (object) $term;
+  }
+
+  return $terms;
+}
+
+function _term_reference_tree_children_selected($terms, $default) {
+  foreach($terms->children as $term) {
+    if(isset($default[$term->tid]) || $term->children_selected) {
+      return true;
+    }
+  }
+  return false;
+}
+
+function _term_reference_tree_get_parent($tid) {
+  $q = db_query_range("select h.parent from {taxonomy_term_hierarchy} h where h.tid = :tid", 0, 1, array(':tid'  => $tid));
+
+  $t = 0;
+  foreach($q as $term) {
+    $t = $term->parent;
+  }
+
+  return $t;
+}
+
+/**
+ * Recursively go through the option tree and return a flat array of
+ * options
+ */
+function _term_reference_tree_flatten($element, &$form_state) {
+  $output = array();
+  $children = element_children($element);
+  foreach($children as $c) {
+    $child = $element[$c];
+		// dsm($child, '$child');
+    if (array_key_exists('#type', $child) && ($child['#type'] == 'radio' || $child['#type'] == 'checkbox')) {
+      $output[] = $child;
+    }
+    else {
+      $output = array_merge($output, _term_reference_tree_flatten($child, $form_state));
+    }
+  }
+  return $output;
+}
+
+/**
+ * Return an array of options.
+ * 
+ * This function converts a list of taxonomy terms to a key/value list of options.
+ * 
+ * @param $terms
+ *   An array of taxonomy term IDs.
+ * @param $allowed
+ *   An array containing the terms allowed by the filter view
+ * @param $filter
+ *   A string defining the view to filter by (only used to detect whether view
+ *   filtering is enabled
+ * 
+ * @return
+ *   A key/value array of taxonomy terms (name => id)
+ */
+function _term_reference_tree_get_options(&$terms, &$allowed, $filter) {
+  $options = array();
+
+  if (is_array($terms) && count($terms) > 0) {
+    foreach($terms as $term) {
+      if (!$filter || (is_array($allowed) && $allowed[$term->tid])) {
+        $options[$term->tid] = entity_label('taxonomy_term', $term);
+        $options += _term_reference_tree_get_options($term->children, $allowed, $filter);
+      }
+    }
+  }
+  return $options;
+}
+

+ 899 - 0
sites/all/modules/contrib/taxonomy/term_reference_tree/term_reference_tree.widget.inc

@@ -0,0 +1,899 @@
+<?php
+
+/**
+ * Implements hook_field_widget_info().
+ */
+function term_reference_tree_field_widget_info() {
+  return array(
+    'term_reference_tree' => array (
+      'label' => 'Term reference tree',
+      'field types' => array('taxonomy_term_reference'),
+      'behaviors' => array(
+        'multiple values' => FIELD_BEHAVIOR_CUSTOM, 
+        'default value' => FIELD_BEHAVIOR_DEFAULT,
+      ),
+      'settings' => array(
+        'start_minimized' => 0,
+        'leaves_only' => 0,
+        'filter_view' => '',
+        'select_parents' => 0,
+        'cascading_selection' => 0,
+        'track_list' => 0,
+        'track_list_order' => 0,
+        'token_display' => '',
+        'parent_term_id' => '',
+        'max_depth' => '',
+        'starting_depth' => 1,
+      ),
+    ),
+  );
+}
+
+/**
+ * Themes the term tree display (as opposed to the select widget).
+ */
+function theme_term_tree_list($variables) {
+  $element =& $variables['element'];
+  $data =& $element['#data'];
+
+  $tree = array();
+
+  # For each selected term:
+  foreach($data as $item) {
+    # Loop if the term ID is not zero:
+    $values = array();
+    $tid = $item['tid'];
+    $original_tid = $tid;
+    while($tid != 0) {
+      # Unshift the term onto an array
+      array_unshift($values, $tid);
+      
+      # Repeat with parent term
+      $tid = _term_reference_tree_get_parent($tid);
+    }
+    
+    $current =& $tree;
+    # For each term in the above array:
+    foreach($values as $tid) {
+      # current[children][term_id] = new array
+      if (!isset($current['children'][$tid])) {
+        $current['children'][$tid] = array('selected' => FALSE);
+      }
+      
+      # If this is the last value in the array, tree[children][term_id][selected] = true
+      if ($tid == $original_tid) {
+        $current['children'][$tid]['selected'] = TRUE;
+      }
+
+      $current['children'][$tid]['tid'] = $tid;
+      $current =& $current['children'][$tid];
+    }
+  }
+  
+  return _term_reference_tree_output_list_level($element, $tree);
+}
+
+
+/**
+ * Implements hook_field_widget_settings_form().
+ */
+function term_reference_tree_field_widget_settings_form($field, $instance) {
+  $widget = $instance['widget'];
+  $settings = $widget['settings'];
+  $form = array();
+  
+  if ($widget['type'] == 'term_reference_tree') {
+    $form['start_minimized'] = array(
+      '#type' => 'checkbox',
+      '#title' => t('Start minimized'),
+      '#description' => t('Make the tree appear minimized on the form by default'),
+      '#default_value' => $settings['start_minimized'],
+      '#return_value' => 1,
+    );
+    
+    $form['leaves_only'] = array(
+      '#type' => 'checkbox',
+      '#title' => t('Leaves only'),
+      '#description' => t("Don't allow the user to select items that have children"),
+      '#default_value' => $settings['leaves_only'],
+      '#return_value' => 1,
+    );
+
+    $form['select_parents'] = array(
+      '#type' => 'checkbox',
+      '#title' => t('Select parents automatically'),
+      '#description' => t("When turned on, this option causes the widget to automatically select the ancestors of all selected items. In Leaves Only mode, the parents will be added invisibly to the selected value.  <em>This option is only valid if an unlimited number of values can be selected.</em>"),
+      '#default_value' => $settings['select_parents'],
+      '#element_validate' => array('_term_reference_tree_select_parents_validate'),
+      '#return_value' => 1,
+    );
+
+    $form['cascading_selection'] = array(
+      '#type' => 'checkbox',
+      '#title' => t('Cascading selection'),
+      '#description' => t('On parent selection, automatically select children if none were selected. Some may then be manually unselected. In the same way, on parent unselection, unselect children if all were selected. <em>This option is only valid if an unlimited number of values can be selected.</em>'),
+      '#default_value' => $settings['cascading_selection'],
+      '#element_validate' => array('_term_reference_tree_cascading_selection_validate'),
+      '#return_value' => 1,
+    );
+
+    if (module_exists('views')) {
+      $views = views_get_all_views();
+      $options = array('' => 'none');
+      
+      foreach($views as $name => $view) {
+        if ($view->base_table == 'taxonomy_term_data') {
+          foreach($view->display as $display) {
+            $options["$name:{$display->id}"] = "{$view->human_name}: {$display->display_title}";
+          }
+        }
+      }
+
+      $form['filter_view'] = array(
+        '#type' => 'select',
+        '#title' => 'Filter by view',
+        '#description' => t("Filter the available options based on whether they appear in the selected view."),
+        '#default_value' => $settings['filter_view'],
+        '#options' => $options,
+      );
+    }
+    else {
+      $form['filter_view'] = array(
+        '#type' => 'hidden',
+        '#value' => $settings['filter_view'],
+      );
+    }
+
+    if (module_exists('token')) {
+      $form['token_display'] = array(
+        '#type' => 'textarea',
+        '#title' => 'Custom Term Label',
+        '#description' => t("Use tokens to change the term labels for the checkboxes and/or radio buttons.  Leave this field blank to use the term name."),
+        '#default_value' => $settings['token_display'],
+      );
+
+      $form['tokens_list'] = array(
+        '#theme' => 'token_tree',
+        '#token_types' => array('term'),
+      );
+    }
+    else {
+      $form['token_display'] = array(
+        '#type' => 'hidden',
+        '#value' => $settings['token_display'],
+      );
+    }    
+    
+    $form['track_list'] = array(
+      '#type' => 'checkbox',
+      '#title' => t('Track list'),
+      '#description' => t(
+          'Track what the user has chosen in a list below the tree.
+           Useful when the tree is large, with many levels.'),
+      '#default_value' => $settings['track_list'],
+      '#return_value' => 1,
+    );
+
+    $form['track_list_order'] = array(
+      '#type' => 'checkbox',
+      '#title' => t('Track list drag and drop order'),
+      '#description' => t(
+          'Allow drag and drop selected terms ordering on tracklist.'),
+      '#default_value' => $settings['track_list_order'],
+      '#return_value' => 1,
+      '#element_validate' => array('_term_reference_tree_track_list_order_validate'),
+    );
+    
+
+    $form['max_depth'] = array(
+      '#type' => 'textfield',
+      '#title' => t('Maximum Depth'),
+      '#description' => t("Only show items up to this many levels deep."),
+      '#default_value' => $settings['max_depth'],
+      '#size' => 2,
+      '#return_value' => 1,
+    );    
+    
+    $form['starting_depth'] = array(
+      '#type' => 'textfield',
+      '#title' => t('Starting Depth'),
+      '#description' => t("Only items equal and down this level will be selectable. First level is 1"),
+      '#default_value' => $settings['starting_depth'],
+      '#size' => 2,
+      '#return_value' => 1,
+    );    
+
+    $form['parent_term_id'] = array(
+      '#type' => 'textfield',
+      '#title' => t('Parent Term ID'),
+      '#description' => t("Only show items underneath the taxonomy term with this ID number.  Leave this field blank to not limit terms by parent."),
+      '#default_value' => $settings['parent_term_id'],
+      '#size' => 8,
+      '#return_value' => 1,
+    );    
+  }
+
+  return $form;
+}
+
+/**
+ * Helper function to output a single level of the term reference tree
+ * display.
+ */
+function _term_reference_tree_output_list_level(&$element, &$tree) {
+  if (isset($tree['children']) && is_array($tree['children']) && count($tree['children'] > 0)) {
+    $output = '<ul class="term">';
+    $settings = $element['#display']['settings'];
+    $tokens_selected = $settings['token_display_selected'];
+    $tokens_unselected = ($settings['token_display_unselected'] != '') ? $settings['token_display_unselected'] : $tokens_selected;
+
+    foreach($tree['children'] as &$item) {
+      $term = taxonomy_term_load($item['tid']);
+      $uri = taxonomy_term_uri($term);
+      $class = $item['selected'] ? 'selected' : 'unselected';
+      $output .= "<li class='$class'>";
+      if ($tokens_selected != '' && module_exists('token')) {
+        $replace = $item['selected'] ? $tokens_selected : $tokens_unselected;
+        $output .= token_replace($replace, array('term' => $term), array('clear' => TRUE));
+      }
+      else {
+        $output .= l(entity_label('taxonomy_term', $term), $uri['path'], array('html' => true));
+      }
+      if (isset($item['children'])) {
+        $output .= _term_reference_tree_output_list_level($element, $item);
+      }
+      $output .= "</li>";
+    }
+
+    $output .= '</ul>';
+    return $output;
+  }
+}
+
+
+/**
+ * Makes sure that cardinality is unlimited if auto-select parents is enabled.
+ */
+function _term_reference_tree_select_parents_validate($element, &$form_state) {
+  if ($form_state['values']['instance']['widget']['settings']['select_parents'] == 1 && $form_state['values']['field']['cardinality'] != -1) {
+    // This is pretty wonky syntax for the field name in form_set_error, but it's
+    // correct.
+    form_set_error('field][cardinality', t('You must select an Unlimited number of values if Select Parents Automatically is enabled.'));
+  }
+}
+
+/**
+ * Makes sure that cardinality is unlimited if cascading selection is enabled.
+ */
+function _term_reference_tree_cascading_selection_validate($element, &$form_state) {
+  if ($form_state['values']['instance']['widget']['settings']['cascading_selection'] == 1 && $form_state['values']['field']['cardinality'] != -1) {
+    // This is pretty wonky syntax for the field name in form_set_error, but it's
+    // correct.
+    form_set_error('field][cardinality', t('You must select an Unlimited number of values if Cascading selection is enabled.'));
+  }
+}
+
+function _term_reference_tree_track_list_order_validate($element, &$form_state){
+  if ($form_state['values']['instance']['widget']['settings']['track_list'] == 0 && $form_state['values']['instance']['widget']['settings']['track_list_order'] == 1) {
+    // This is pretty wonky syntax for the field name in form_set_error, but it's
+    // correct.
+    form_set_error('field][track_list_order', t('You must enable Track List if Track List Order is enabled.'));
+  }
+	/*
+		TODO check if number of values is diffrent from 1
+	*/
+}
+
+
+/**
+ * Process the checkbox_tree widget.
+ * 
+ * This function processes the checkbox_tree widget.
+ * 
+ * @param $element
+ *   The element to be drawn.$element['#field_name']
+ * @param $form_state
+ *   The form state.
+ * 
+ * @return
+ *   The processed element.
+ */
+function term_reference_tree_process_checkbox_tree($element, $form_state) {
+  if (is_array($form_state)) {
+    if (!empty($element['#max_choices']) && $element['#max_choices'] != '-1')
+      drupal_add_js(array('term_reference_tree' => array('trees' => array($element['#id'] => array('max_choices'=>$element['#max_choices'])))), 'setting');
+    $allowed = '';
+    
+    if ($element['#filter_view'] != '') {
+      $allowed = _term_reference_tree_get_allowed_values($element['#filter_view']);
+    }
+    
+    $value = !empty($element['#default_value']) ? $element['#default_value'] : array();
+
+    if (empty($element['#options'])) {
+      $element['#options_tree'] = _term_reference_tree_get_term_hierarchy($element['#parent_tid'], $element['#vocabulary'], $allowed, $element['#filter_view'], '', $value);
+      $required = $element['#required'];
+      if ($element['#max_choices'] == 1 && !$required) {
+        array_unshift($element['#options_tree'], (object) array(
+          'tid' => '',
+          'name' => 'N/A',
+          'depth' => 0
+          )
+        );
+      }
+      $element['#options'] = _term_reference_tree_get_options($element['#options_tree'], $allowed, $element['#filter_view']);
+    }
+
+    $terms = !empty($element['#options_tree']) ? $element['#options_tree'] : array();
+    $max_choices = !empty($element['#max_choices']) ? $element['#max_choices'] : 1;
+    if (array_key_exists('#select_parents', $element) && $element['#select_parents']) {
+      $element['#attributes']['class'][] = 'select-parents';
+    }
+
+    if ($max_choices != 1)
+      $element['#tree'] = TRUE;
+
+		$starting_depth = !empty($element['#starting_depth']) ? $element['#starting_depth'] : 0;
+    $tree = new stdClass;
+    $tree->children = $terms;
+    $element[] = _term_reference_tree_build_level($element, $tree, $form_state, $value, $max_choices, $starting_depth, array(), 1);
+
+    //Add a track list element?
+    $track_list = !empty($element['#track_list']) && $element['#track_list'];
+    if ( $track_list ) {
+      $element[] = array(
+        '#type' => 'checkbox_tree_track_list',
+        '#max_choices' => $max_choices,
+				'#track_list_order' => $element['#track_list_order'],
+      );
+    }
+  } 
+
+  return $element;
+}
+
+/**
+ * Returns HTML for a checkbox_tree form element.
+ *
+ * @param $variables
+ *   An associative array containing:
+ *   - element: An associative array containing the properties of the element.
+ *
+ * @ingroup themeable
+ */
+function theme_checkbox_tree($variables) {
+  $element = $variables['element'];
+  $element['#children'] = drupal_render_children($element);
+  
+  $attributes = array();
+  if (isset($element['#id'])) {
+    $attributes['id'] = $element['#id'];
+  }
+  $attributes['class'][] = 'term-reference-tree';
+  
+  if (form_get_error($element)) {
+    $attributes['class'][] = 'error';
+  }
+  
+  if (!empty($element['#required'])) {
+    $attributes['class'][] = 'required';
+  }
+
+  if (array_key_exists('#start_minimized', $element) && $element['#start_minimized']) {
+    $attributes['class'][] = "term-reference-tree-collapsed";
+  }
+
+  if (array_key_exists('#cascading_selection', $element) && $element['#cascading_selection']) {
+    $attributes['class'][] = "term-reference-tree-cascading-selection";
+  }
+
+  $add_track_list = FALSE;
+  if (array_key_exists('#track_list', $element) && $element['#track_list']) {
+    $attributes['class'][] = "term-reference-tree-track-list-shown";
+    $add_track_list = TRUE;
+  }
+
+  if (!empty($element['#attributes']['class'])) {
+    $attributes['class'] = array_merge($attributes['class'], $element['#attributes']['class']);
+  }
+  return 
+      '<div' . drupal_attributes($attributes) . '>' 
+    . (!empty($element['#children']) ? $element['#children'] : '') 
+    . '</div>';
+}
+
+
+/**
+ * This function prints a list item with a checkbox and an unordered list
+ * of all the elements inside it.
+ */
+function theme_checkbox_tree_level($variables) {
+  $element = $variables['element'];
+  $sm = '';
+  if (array_key_exists('#level_start_minimized', $element) && $element['#level_start_minimized']) {
+    $collapsed = 
+    $sm = " style='display: none;'";
+  }
+
+  $max_choices = 0;
+  if (array_key_exists('#max_choices', $element)) {
+    $max_choices = $element['#max_choices'];
+  }
+
+  $output = "<ul class='term-reference-tree-level '$sm>";
+  $children = element_children($element);
+  foreach($children as $child) {
+    $output .= "<li>";
+    $output .= drupal_render($element[$child]);
+    $output .= "</li>";
+  }
+
+  $output .= "</ul>";
+
+  return $output;
+}
+
+/**
+ * This function prints a single item in the tree, followed by that item's children
+ * (which may be another checkbox_tree_level).
+ */
+function theme_checkbox_tree_item($variables) {
+  $element = $variables['element'];
+  $children = element_children($element);
+  $output = "";
+  
+  $sm = $element['#level_start_minimized'] ? ' term-reference-tree-collapsed' : '';
+  
+  if (is_array($children) && count($children) > 1) {
+    $output .= "<div class='term-reference-tree-button$sm'></div>";
+  }
+  elseif (!$element['#leaves_only']) {
+    $output .= "<div class='no-term-reference-tree-button'></div>";
+  }
+
+  foreach($children as $child) {
+    $output .= drupal_render($element[$child]);
+  }
+  
+  return $output;
+}
+
+/**
+ * This function prints a label that cannot be selected.
+ */
+function theme_checkbox_tree_label($variables) {
+  // dsm($variables, 'variables');
+  $element = $variables['element'];
+  $output = "<div class='parent-term'>" . $element['#value'] . "</div>";
+  return $output;
+}
+
+/**
+ * Shows a list of items that have been checked.
+ * The display happens on the client-side.
+ * Use this function to theme the element's label,
+ * and the "nothing selected" message.
+ * 
+ * @param $variables Variables available for theming. 
+ */
+function theme_checkbox_tree_track_list($variables) {
+  //Should the label be singular or plural? Depends on cardinality of term field.
+  static $nothingselected;
+  // dsm($variables, 'theme_checkbox_tree_track_list : $variables');
+
+  if(!$nothingselected) {
+    $nothingselected = t('[Nothing selected]');
+    //Add the "Nothing selected" text. To style it, replace it with whatever you want.
+    //Could do this with a file instead.
+    drupal_add_js(
+      'var termReferenceTreeNothingSelectedText = "' . $nothingselected . '";',
+      'inline'
+    );
+  }
+  
+  $label = format_plural(
+      $variables['element']['#max_choices'], 
+      'Selected item (click the item to uncheck it)',
+      'Selected items (click an item to uncheck it)'
+  );
+	$order = $variables['element']['#track_list_order'] ? 'order-list' : '';
+  $output = 
+    '<div class="term-reference-track-list-container">
+       <div class="term-reference-track-list-label">' . $label . '</div>
+       <ul class="term-reference-tree-track-list '.$order.'"><li class="term_ref_tree_nothing_message">'.$nothingselected.'</li></ul>
+     </div>';
+     
+
+  return $output;
+}
+
+/**
+ * Implements hook_widget_field_form().
+ */
+function term_reference_tree_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
+  $settings = $instance['widget']['settings'];
+  $voc = taxonomy_vocabulary_machine_name_load($field['settings']['allowed_values'][0]['vocabulary']);
+  $path = drupal_get_path('module', 'term_reference_tree');
+  $value_key = key($field['columns']);
+  $type = $instance['widget']['type'];
+  
+  $default_value = array();
+  foreach($items as $item) {
+    $key = $item[$value_key];
+    if ($key === 0) {
+      $default_value[$key] = '0';
+    }
+    else {
+      $default_value[$key] = $key;
+    }
+  }
+
+  $multiple = $field['cardinality'] > 1 || $field['cardinality'] == FIELD_CARDINALITY_UNLIMITED;
+  $properties = array();
+
+  if (!array_key_exists('#value', $element))
+    $element['#value'] = array();
+
+  // A switch statement, in case we ever add more widgets to this module.
+  switch($instance['widget']['type']) {
+    case 'term_reference_tree':
+      $element['#attached']['js'] = array($path . '/term_reference_tree.js');
+      $element['#attached']['css'] = array($path . '/term_reference_tree.css');
+      $element['#type'] = 'checkbox_tree';   
+      $element['#default_value'] = $multiple ? $default_value : array(reset($default_value) => reset($default_value));
+      $element['#max_choices'] = $field['cardinality'];
+      $element['#max_depth'] = $settings['max_depth'];
+      $element['#starting_depth'] = $settings['starting_depth'];
+      $element['#start_minimized'] = $settings['start_minimized'];
+      $element['#leaves_only'] = $settings['leaves_only'];
+      $element['#filter_view'] = module_exists('views') ? $settings['filter_view'] : '';
+      $element['#select_parents'] = $settings['select_parents'];
+      $element['#cascading_selection'] = $settings['cascading_selection'];
+      $element['#track_list'] = $settings['track_list'];
+      $element['#track_list_order'] = $settings['track_list_order'];
+      $element['#parent_tid'] = $settings['parent_term_id'] || $field['settings']['allowed_values'][0]['parent'];
+      $element['#vocabulary'] = $voc->vid;
+      $element['#token_display'] = module_exists('token') ? $settings['token_display'] : '';
+      break;
+  }
+  
+  $element += array(
+    '#value_key' => $value_key,
+    '#element_validate' => array('_term_reference_tree_widget_validate'),
+    '#properties' => $properties,
+  );
+	
+	if ($settings['track_list_order']) {
+		drupal_add_library('system', 'ui.sortable');
+	}
+	
+  return $element;
+}
+
+
+/**
+ * Validates the term reference tree widgets.
+ * 
+ * This function sets the value of the tree widgets into a form that Drupal
+ * can understand, and also checks if the field is required and has been
+ * left empty.
+ * 
+ * @param $element
+ *   The element to be validated.
+ * @param $form_state
+ *   The state of the form.
+ * 
+ * @return
+ *   The validated element.
+ */
+function _term_reference_tree_widget_validate(&$element, &$form_state) {
+	// dsm($element, '$element');
+	// dsm($form_state, '$form_state');
+	# if the field was in the form
+	if(isset($form_state['input'][$element['#field_name']])){
+		
+	  $items = _term_reference_tree_flatten($element, $form_state);
+	  $value = array();
+
+	  if ($element['#max_choices'] != 1) {
+			if(!$element['#track_list_order']){
+		    foreach($items as $child) {
+		      if (array_key_exists('#value', $child) && $child['#value'] !== 0) {
+		        array_push($value, array( $element['#value_key'] => $child['#value']));
+
+		        // If the element is leaves only and select parents is on, then automatically
+		        // add all the parents of each selected value.
+		        if ($element['#select_parents'] && $element['#leaves_only']) {
+		          foreach($child['#parent_values'] as $parent_tid) {
+		            if (!in_array(array($element['#value_key'] => $parent_tid), $value)) {
+		              array_push($value, array($element['#value_key'] => $parent_tid));
+		            }
+		          }
+		        }
+
+		      } 
+		    }
+			
+			}else{
+				$selected_terms = array();			
+				$deltas = array();
+				foreach($items as $child) {
+		      if (array_key_exists('#value', $child) && $child['#value'] !== 0) {
+		        $selected_terms[] = array(
+							"delta" => $form_state['input'][$child['#value'].'-weight'],
+							"term" => array($element['#value_key'] => $child['#value']),
+						);
+				
+		        // If the element is leaves only and select parents is on, then automatically
+		        // add all the parents of each selected value.
+		        if ($element['#select_parents'] && $element['#leaves_only']) {
+		          foreach($child['#parent_values'] as $parent_tid) {
+		            if (!in_array(array($element['#value_key'] => $parent_tid), $selected_terms)) {
+					        $selected_terms[] = array(
+										"delta" => $form_state['input'][$parent_tid.'-weight'],
+										"term" => array($element['#value_key'] => $child['#value']),
+									);
+
+		            }
+		          }
+		        }
+
+		      } 
+		    }
+				// dsm($deltas, '$deltas');
+				// dsm($selected_terms, '$selected_terms before sort');
+				// reorder items
+				function delta_sort($a, $b){
+					return $a['delta'] > $b['delta'];
+				}
+				
+				usort($selected_terms, "delta_sort");
+				// dsm($selected_terms, '$selected_terms after sort');
+				
+				// record in value
+				foreach ($selected_terms as $selected_term) {
+					$value[] = $selected_term['term'];
+				}
+
+			}
+	  }
+	  else {
+	    // If it's a tree of radio buttons, they all have the same value, so we can just
+	    // grab the value of the first one.
+	    if (count($items) > 0) {
+	      $child = reset($items);
+	      if (array_key_exists('#value', $child) && $child['#value'] !== 0) {
+	        array_push($value, array($element['#value_key'] => $child['#value']));
+	      }       
+	    }
+	  }
+
+	  if ($element['#required'] && empty($value)) {
+	    // The title is already check_plained so it's appropriate to use !.
+	    form_error($element, t('!name field is required.', array('!name' => $element['#title'])));
+	  }
+	  form_set_value($element, $value, $form_state);
+		// dsm($element, '$element afetr form_set_value');
+	  return $element;
+	}else{
+		# if the field was not in the form
+    $values = array();
+		foreach ($element['#default_value'] as $tid) {
+      $values[] = (array) taxonomy_term_load($tid);
+		}
+	  form_set_value($element, $values, $form_state);
+		// dsm($element, '$element afetr form_set_value');
+	  return $element;
+		
+	}
+}
+
+/**
+ * Returns an array of allowed values defined by the given view.
+ *
+ * @param $filter
+ *   A view, in the format VIEWNAME:DISPLAYNAME
+ *
+ * @return
+ *   An array of term IDs (tid => true) returned by the view.
+ */
+function _term_reference_tree_get_allowed_values($filter) {
+  $viewname = "";
+  $displayname = "";
+  $allowed = array();
+
+  if (module_exists('views') && $filter != '') {
+    list($viewname, $displayname) = explode(":", $filter);
+    $view = views_get_view($viewname);
+    if (is_object($view)) {
+      if ($view->access($displayname)) {
+        // Save the page title first, since execute_display() will reset this to the display title.
+        $title = drupal_get_title();
+        $view->execute_display($displayname);
+        $title = drupal_set_title($title, PASS_THROUGH);
+        foreach($view->result as $item) {
+          $allowed[$item->tid] = true;
+        }
+      }
+      else {
+        drupal_set_message("Cannot access view for term reference tree widget.", 'warning');
+      }
+    }
+    else {
+      drupal_set_message("Term reference tree: no view named '$viewname'", 'warning');
+    }
+  }
+
+  return $allowed;
+}
+
+
+
+/**
+ * Builds a single item in the term reference tree widget.
+ *
+ * This function returns an element with a checkbox for a single taxonomy term.
+ * If that term has children, it appends checkbox_tree_level element that
+ * contains the children.  It is meant to be called recursively when the widget
+ * is built.
+ *
+ * @param $element
+ *   The main checkbox_tree element.
+ * @param $term
+ *   A taxonomy term object.  $term->children should be an array of the term
+ *   objects that are that term's children.
+ * @param $form_state
+ *   The form state.
+ * @param $value
+ *   The value of the element.
+ * @param $max_choices
+ *   The maximum number of allowed selections.
+ *
+ * @return
+ *   A completed checkbox_tree_item element, which contains a checkbox and
+ *   possibly a checkbox_tree_level element as well.
+ */
+function _term_reference_tree_build_item(&$element, &$term, &$form_state, &$value, $max_choices, $starting_depth, $parent_tids, $parent, $depth) {
+  $start_minimized = FALSE;
+  if (array_key_exists('#start_minimized', $element)) {
+    $start_minimized = $element['#start_minimized'];
+  }
+
+  $leaves_only = FALSE;
+  if (array_key_exists('#leaves_only', $element)) {
+    $leaves_only = $element['#leaves_only'];
+  }
+
+  $t = null;
+  // if(module_exists('locale')) {
+    // $t = taxonomy_term_load($term->tid);
+    // taxonomy_term_load return term without name, because of module title
+    // $term_name = entity_label('taxonomy_term', $term);
+    // there is a problem here with title module, title_entity_label() return empty label
+    // see http://drupal.org/node/1764354
+  // } else {
+    $term_name = $term->name;
+  // }
+  $container = array(
+    '#type' => 'checkbox_tree_item',
+    '#max_choices' => $max_choices,
+    '#leaves_only' => $leaves_only,
+    '#term_name' => $term_name,
+    '#level_start_minimized' => FALSE,
+    '#depth' => $depth,
+  );
+
+  if ((!$element['#leaves_only'] || count($term->children) == 0) && $depth >= $element['#starting_depth']) {
+    $name = "edit-" . str_replace('_', '-', $element['#field_name']);
+    $e = array(
+      '#type' => ($max_choices == 1) ? 'radio' : 'checkbox',
+      '#title' => $term_name,
+      '#on_value' => $term->tid,
+      '#off_value' => 0,
+      '#return_value' => $term->tid,
+      '#parent_values' => $parent_tids,
+      '#default_value' => isset($value[$term->tid]) ? $term->tid : NULL,
+      '#attributes' => isset($element['#attributes']) ? $element['#attributes'] : NULL,
+      '#ajax' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
+    );
+
+    if ($element['#token_display'] != '' && module_exists('token')) {
+      if(!$t) {
+        $t = taxonomy_term_load($term->tid);
+      }
+      $e['#title'] = token_replace($element['#token_display'], array('term' => $t), array('clear' => TRUE));
+    }
+
+    if ($e['#type'] == 'radio') {
+      $parents_for_id = array_merge($element['#parents'], array($term->tid));
+      $e['#id'] = drupal_html_id('edit-' . implode('-', $parents_for_id));
+      $e['#parents'] = $element['#parents'];
+    }else if($element['#track_list_order']){
+			$delta = 0;
+			$i = -1;
+			if(isset($value[$term->tid])){
+				foreach ($value as $tid) {
+					$i++;
+					if($term->tid == $tid)
+						break;
+				}
+			}
+			
+			$e_weight = array(
+			  '#type' => 'hidden',
+			  '#value' => $i,
+				'#name' => $term->tid.'-weight',
+			);
+		}
+  }
+  else {
+    $e = array(
+      '#type' => 'checkbox_tree_label',
+      '#value' => $term_name,
+    );
+  }
+
+  $container[$term->tid] = $e;  
+
+	if(isset($e_weight)){
+		$container[$term->tid.'-weight'] = $e_weight;
+	}
+
+  if (($depth + 1 <= $element['#max_depth'] || !$element['#max_depth']) && property_exists($term, 'children') && count($term->children) > 0) {
+    $parents = $parent_tids;
+    $parents[] = $term->tid;
+    $container[$term->tid . '-children'] = _term_reference_tree_build_level($element, $term, $form_state, $value, $max_choices, $starting_depth, $parents, $depth+1);
+    $container['#level_start_minimized'] = $container[$term->tid . '-children']['#level_start_minimized'];
+  }
+  
+  return $container;
+}
+
+/**
+ * Builds a level in the term reference tree widget.
+ *
+ * This function returns an element that has a number of checkbox_tree_item elements
+ * as children.  It is meant to be called recursively when the widget is built.
+ *
+ * @param $element
+ *   The main checkbox_tree element.
+ * @param $term
+ *   A taxonomy term object.  $term->children should be an array of the term
+ *   objects that are that term's children.
+ * @param $form_state
+ *   The form state.
+ * @param $value
+ *   The value of the element.
+ * @param $max_choices
+ *   The maximum number of allowed selections.
+ *
+ * @return
+ *   A completed checkbox_tree_level element.
+ */
+function _term_reference_tree_build_level(&$element, &$term, &$form_state, &$value, $max_choices, $starting_depth, $parent_tids, $depth) {
+  $start_minimized = FALSE;
+  if (array_key_exists('#start_minimized', $element)) {
+    $start_minimized = $element['#start_minimized'];
+  }
+
+  $leaves_only = FALSE;
+  if (array_key_exists('#leaves_only', $element)) {
+    $leaves_only = $element['#leaves_only'];
+  }
+  
+  $container = array(
+    '#type' => 'checkbox_tree_level',
+    '#max_choices' => $max_choices,
+    '#leaves_only' => $leaves_only,
+    '#start_minimized' => $start_minimized,
+    '#depth' => $depth,
+  );
+
+  $container['#level_start_minimized'] = $depth > 1 && $element['#start_minimized'] && !($term->children_selected);
+  
+  foreach($term->children as $t) {
+    $container[$t->tid] = _term_reference_tree_build_item($element, $t, $form_state, $value, $max_choices, $starting_depth, $parent_tids, $container, $depth);
+  }
+  
+  return $container;
+}