$.fn.clearForm = function() {
  return this.each(function() {
    var type = this.type, tag = this.tagName.toLowerCase();
    
    if (type == 'text' || type == 'password' || tag == 'textarea') {
      this.value = '';
    } else if (type == 'checkbox' || type == 'radio') {
      this.checked = false;
    } else if (tag == 'select') {
      this.selectedIndex = -1;
    } else {
      return $(':input', this).clearForm();
    }
  });
};


$(function () {
  /* Remove initial 'search' label from search box on click */
  $('input[class=search]').click(function () {
    if (this.value == 'Search') {
      this.value = '';
    }
  });
  
  /* Open links with rel=external in a new window */
  $('a[rel=external]').click(function() {
    window.open(this.href);
    return false;
  })

  /* On pages with filters (search/tags), collapse the filter initially */
  if (window.open_filters) {
    var open_filters = window.open_filters;  
  } else {
    var open_filters = 0;  
    $('fieldset.filter ol').hide();
    $(".hideable").hide();
  }
  
  /* Control opening and closing of option lists on search page */
  $('fieldset.filter legend').toggle(
    function () { 
      open_filters++;
      $(this).parent().find('ol').show(); 
      if (open_filters == 1) {
        $(this).parent().siblings('fieldset:last').find(".hideable").show();
      }
      $(this).parent().removeClass('collapsed');
      $(this).parent().addClass('expanded');
    },
    function () { 
      open_filters--;
      $(this).parent().find('ol').hide(); 
      if (open_filters == 0) {
        $(this).parent().siblings('fieldset:last').find(".hideable").hide();
      }
      $(this).parent().addClass('collapsed');
      $(this).parent().removeClass('expanded');
    }
  );
  
  /* Add bulk update checkboxes in admin */
  $('ul.bulk-update').prepend('<li class="selectall"><input type="checkbox" name="bulk" class="bulk-button" title="Select all" /></li>');
  $('table.bulk-update thead tr td').append('<input type="checkbox" name="bulk" class="bulk-button" title="Select all" />');
  $('input.bulk-button').change(function () {
    if (this.parentNode.tagName == 'LI') {
      var $table = $(this).closest('ul').prev('table:first');
    } else {
      var $table = $(this).closest('table');
    }
    
    $('tbody td input[type=checkbox]', $table).attr('checked', this.checked);
  });
});
