/*
 * Adjust year-links for a better flow. The idea is to pull all anchors from
 * the containing table and format as nicely spaced spans, format the spans,
 * and remove the table.
 *
 * Note that the html source html was buggy.  I fixed the html, but I'm 
 * concerned that it may degrade over time (end-user edits), so I code
 * defensively here.
 */

/*global $ */
/*jslint white: true, onevar: true, browser: true, devel: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, strict: true, newcap: true, immed: true, indent: 2 */

"use strict";

$(document).ready(function () {
  var 
      // Configurable:
      sh = 25,  // padding width to be added to year-links
      sv = 10,  // padding width to be added to year-links

      // target year link box
      box = $('#link-box.link-box-year'),

      // box model dimensions
      W = box.width(),
      w = 0,    // maximum width of year-links
      h = 0,    // maximum height of year-links
      n = 0,    // maximum number of year-links per line
      l = 0     // number of year-links lines
      ;

  // selectively collect anchors and calc max width
  $('table:first a', box).each(function () {
    // I found some links were mysteriously empty, so
    if ($.trim($(this).text()) === '') {
      return;
    }
    
    // I found some links had inner html (illegal), so...
    $(this).html($(this).text());

    // use css styling
    $(box).append(this);
    $(this).wrap('<span class="year-link"/>')

    // calulate max dimensions
    w = Math.max(w, $(this).width());
    h = Math.max(h, $(this).height());
  });

  if (w === 0) {
    // nothing to do
    return;
  }

  // clean up html and add links as spans
  $('table:first', box).remove();

  // calc number of anchors per line based on max anchor width (s + w + s)
  // and container width (W).  Use clear on first element on line to 
  // reflow next row to next line.
  n = parseInt((W / (sh + w + sh)), 10);
  $('a', box).each(function (i) {
    if ((i % n === 0)) {
      $(this).addClass('year-link-clear');
      l += 1;
    }
  });

  // fix clear on sibling divs
  $('.node .content').addClass('year-link-clear');

  // now style the element
  $('.year-link', box).css({
    'height' : h,
    'width': w,
    'padding-left': sh,
    'padding-right': sh,
    'padding-top': sv,
    'padding-bottom': sv
  });
  h = l * (sv + h + sv);
  box.css({
    'height' : h,
    'min-height': h
  });
});
