/**
 * JQuery plugin for "accordions" of fieldsets. Based on drupal's collapse.js
 * 
 * Behaves like ordinary collapsible fieldsets that drupal has, except only one may be open at a time.
 * Automatically applies to all fieldsets on a page. The first field is the one open by default.
 */

/**
 *
 */
function toggleFieldset(fieldset) {
  if ($(fieldset).is('.collapsed')) {
    $(fieldset).parent().siblings().find('> fieldset.collapsible').each(function() {
      if (!($(this).is('.collapsed'))) {
        toggleFieldset(this);
      }
    });
    
    var content = $('> div', fieldset).hide();
    $(fieldset).removeClass('collapsed');
    content.slideDown({
      duration: 300,
      complete: function() {
        // Make sure we open to height auto
        $(this).css('height', 'auto');
        this.parentNode.animating = false;
        setTimeout(function() {
          $.smartScrollTo(fieldset, 300);
        }, 150);
      },
      step: function() {}
    });
  }
  else {
    var content = $('> div', fieldset).slideUp('medium', function() {
      $(this.parentNode).addClass('collapsed');
      this.parentNode.animating = false;
    });
  }
}

/**
 *
 */
function mkaccord(asd) {
  var fieldset = $(this.parentNode);
  
  // Set collapsible class
  fieldset.addClass('collapsible');
  
  // Turn the legend into a clickable link and wrap the contents of the fieldset
  // in a div for easier animation
  var text = this.innerHTML;
  $(this).empty().append($('<a href="#">'+ text +'</a>').click(function() {
    var fieldset = $(this).parents('fieldset:first')[0];
    // Don't animate multiple times
    if (!fieldset.animating) {
      fieldset.animating = true;
      toggleFieldset(fieldset);
    }
    return false;
  })).after($('<div class="fieldset-wrapper"></div>').append(fieldset.children(':not(legend)')));
  fieldset.filter('.collapsed').children('.fieldset-wrapper')
    .css({height: 'auto', display: 'inline'});

  var needsCollapseAll = fieldset.parent().nextAll(':visible :first').is('.fieldset') &&
                         !fieldset.parent().prevAll(':visible :last').is('.fieldset') &&
                         !fieldset.parent().parent().is('.fieldset-wrapper') &&
                         !fieldset.is('.fieldset-accordion-exclusive') &&
                         fieldset.is(':visible');
  if (needsCollapseAll) {
    fieldset.parent().expandall(function () {
      fieldset.parent().parent().children().find('> fieldset.collapsible').each(function() {
        $(this).removeClass('collapsed');
        $('> div', $(this)).show()
      });
    }, function() {
      fieldset.parent().parent().children().find('> fieldset.collapsible').each(function() {
        $(this).addClass('collapsed');
        $('> div', $(this)).hide()
      });
    });
  }
}

(function($) {
  jQuery.fn.accordion = function() {
    $('fieldset.collapsible > legend').each(mkaccord);
    return this;
  };
})(jQuery);

