(function($) {

/**
 * Attaches the tree behavior to the term widget form.
 */
Drupal.behaviors.termReferenceTree = {
  attach: function(context, settings) {
    // Bind the term expand/contract button to slide toggle the list underneath.
    $('.term-reference-tree-button', context).once('term-reference-tree-button').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).once('term-reference-tree').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 cascading selection.
      if($(this).hasClass('term-reference-tree-select-parents')) {
        $(this).find('.form-checkbox').parent().addClass('select-parents');
      }

      //On page load, check if the user wants a cascading selection.
      if($(this).hasClass('term-reference-tree-cascading-selection')) {
        var mode_select = $(this).hasClass('term-reference-tree-cascading-selection-mode-select');
        var mode_deselect = $(this).hasClass('term-reference-tree-cascading-selection-mode-deselect');

        //Check children when checkboxes are clicked.
        $(this).find('.form-checkbox').change(function(event) {
          var event_target = $(event.target);
          var event_target_checked = event_target.is(':checked');
          var control_id = event_target.attr('id');
          var children = event_target.parent().next().children().find('> :not(ul) > input[id^="' + control_id + '-children"]');

          if (!mode_select && !mode_deselect) {
            if(event_target_checked) {
              $(children).filter(':not(:checked)').click().trigger('change');
            }
            else {
              $(children).filter(':checked').click().trigger('change');
            }
          } else if (mode_select && event_target_checked) {
            $(children).filter(':not(:checked)').click().trigger('change');
          } else if (mode_deselect && !event_target_checked) {
            $(children).filter(':checked').click().trigger('change');
          }
        });
        //End process checkbox changes.
      } //End Want a cascading checking.

    });

    // track_list
    // just unselect items in tree on track_list button remove click
    // let builtin ajax form do the heavy work
    $('.term-reference-tree-track-list input[type="submit"][value="remove"]', context).click(function(e){
      e.preventDefault();
      var key = $(this).attr('term-reference-tree-key');
      $('input[type="checkbox"][value="'+key+'"]', $(this).parents('.term-reference-tree'))
        .prop('checked', false)
        .trigger('change');
      return false;
    });

  }
};

// 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) {
  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('term-reference-tree-select-parents')) {

      if(checkbox.prop('checked')) {
        checkbox.parents('ul.term-reference-tree-level li').children('div.form-item').find('input[type=checkbox]').each(function() {
          $(this).prop('checked', true);
        });
      }
    }
  }
}

})(jQuery);
