$(function() {
    // this var will be used to tell the system whether or not
    // other sections will respond to clicking on a headline
    var closeOthers = true;

    // check which sections are open
    function checkOpen() {
      // how many sections are open
      var openCount = $('#accordion .ui-accordion-content:visible').length;
      // how many sections are there
      var totalCount = $('#accordion .ui-accordion-content').length;

      // set closeOthers var based on if there are 1 or 0 sections open
      if (openCount < 2) closeOthers = true;
      // change the text in the expand link based on if
      // there are more or less than half of the sections open
      if (openCount > totalCount/2) {
	$('#expand_sfx').html("Collapse All");
      }
      else {
	$('#expand_sfx').html("Expand All");
      }


      
    }
    // hide all sections
    $('#accordion .ui-accordion-content').hide();
    // show the first section
    $('#accordion .ui-accordion-content:first').show();
    // actions taken upon clicking any headline
    $('#accordion h3').click( function() {
				       // set checkSection to the section next to the headline clicked
				       var checkSection = $(this).next();
				       // if the section is open, close it, and call checkOpen
				       if(checkSection.is(':visible')) {
					 checkSection.slideUp('normal', checkOpen());
					 return false;
				       }
				       // if the section is closed and closeOthers
				       // is true, close all other open sections
				       else {
					 if (closeOthers) {
					   $('#accordion .ui-accordion-content:visible').slideUp('normal');
					 }
					 // open the section and call checkOpen
					 checkSection.slideDown('normal', checkOpen());
					 return false;
				 }
				     });
    // actions taken upon clicking the expand link
    $('#expand_sfx').click( function() {
				     // if the expand link's text is 'expand all', set closeOthers
				     // to false, open all sections and call checkOpen
				     if ($('#expand_sfx').text() == "Expand All") {
				       closeOthers = false;
				       $('#accordion .ui-accordion-content').slideDown('normal', checkOpen());
				     }
				     // else if the expand link's text is 'collapse all', set closeOthers
				     // to true, hide all sections, and call checkOpen
				     else {
				       closeOthers = true;
				       // the 1 prevents nasty flickering in some browsers
				       $('#accordion .ui-accordion-content').hide(1, checkOpen());
				     }
				     return false;
				   });
});


