// ------------------------------------------------
// Automatically splits div content into columns
// like a newspaper. 
// (c)2007 Take 1 Creative 
// ------------------------------------------------

function columnMagic() {
  var matches, i, j, k, divs = document.getElementsByTagName('div');
  var pattern = new RegExp(/^columnmagic([0-9]+)$/);
  g = 20;                                      // Default gutter width

  for(i=0; i<divs.length; i++) {
    matches = divs[i].className.match(pattern);
    if(matches != null) {
      var n       = matches[1];                // Number of columns
      var w       = divs[i].offsetWidth;       // Width of div
      var colWidth= Math.floor( (w - (n * g) + g) / n);

      // Remove contents
      var html = divs[i].innerHTML;
      divs[i].innerHTML = '';


      // Split HTML into bits at HR tag (manual)
      var splitPattern = new RegExp(/<hr[^>]*?>/i);
      if(html.match(splitPattern) == null) {
        // Autosplit if no HR detected
        var splitPattern = new RegExp(/<\/p>|<\/h1>|<\/h2>|<\/h3>|<br \>|<\/li>|<img [^>]+>/ig);
        var tags     = html.match(splitPattern);
      }

      var htmlbits = html.split(splitPattern);

      // Calculate bits per new column
      bitspercol = Math.floor(htmlbits.length / n);

      // Add new columns
      for(j=0; j<n; j++) {
        var divhtml = '';
        for(k=(j*bitspercol); k<((j+1)*bitspercol); k++) {

          // Add html
          if(htmlbits[k])
            divhtml += htmlbits[k];

          // Add opening tag for bulleted lists
          if(tags)
            if(tags[k])
              if(tags[k] == '</li>' & k==j*bitspercol)
                divhtml = '<ul>' + divhtml;


          // Add closing tag
          if(tags)
            if(tags[k])
              divhtml += tags[k];
        }
        // Add any bits left at the end of last column
        if(j==n-1) {
          while(htmlbits[k]) {
            divhtml += htmlbits[k];
            k++;
          }
        }
        var newDiv = document.createElement('div');
        newDiv.style.width    = colWidth + 'px';

        // Float - Standards compliant
        newDiv.style.cssFloat = "left";
        // IE
        newDiv.style.styleFloat = "left";

        newDiv.innerHTML = divhtml;

        // Add gutter to columns
        if(j > 0)
          newDiv.style.marginLeft = g + 'px';

        divs[i].appendChild(newDiv);
      }
    }
  }
}
