$(function(){
  $('#nav a[@href="' + location.pathname + '"]').attr('class', 'selected');
  
  var match = /_bg=(\d+)/.exec(window.location.search);
  var background = (match && match[1] >= 1 && match[1] <= 4 && match[1]) || (Math.floor(Math.random() * 4) + 1);
  
  $("#bg-left").removeClass().addClass("left bg_" + background);
  $("#bg-right").removeClass().addClass("right bg_" + background);
  
  var categories = $('#categories ul li:gt(5)');
  var archives = $('#archives ul li:gt(2)');
  var items_per_row = 2;
  
  var rows = Math.ceil($('#categories ul li').length / items_per_row);
  var footer = $('#footer');
  var row_height = $('#footer ul li').height();
  var original_height = 70; //footer.height(); there's a safari bug where this is too big?
  var sections = $('#footer > div:gt(0)');
  
  $('#categories h4').append(' <a href="#" id="view-all">(view all)</a>');
  
  categories.hide();
  archives.hide();
  
  archives = archives.filter(':lt(' + (rows - items_per_row) + ')');
  
  $('#view-all').data('open',false).click(function() {
    var open = $(this).data('open');
    var target_height;
    var filter;
    var state;
    var mod;
    
    if( open ) {
      target_height = original_height;
      state = 'visible';
      filter = 'gt';
      mod = -1;
    } else {
      target_height = original_height + ((rows - items_per_row) * row_height);
      state = 'hidden';
      filter = 'lt';
      mod = 0;
    }
    
    footer.animate( {height: target_height}, { duration: 500, step: function(now, fx ) {
      var rows = Math.floor((now - original_height) / row_height) + mod;
      
      categories.filter(':' + filter + '(' + (rows * items_per_row) + '):' + state).toggle();
      archives.filter(':' + filter + '(' + rows + '):' + state).toggle();
      sections.height(now);
    }});

    $(this).data('open', !open).text( !open ? '(view some)' : '(view all)' ).toggleClass('open');
  });
});