/*
This script fixes a few styles that are hard-coded into the PHP code of phpBB.
*/

/*
Searches for all elements with class "pagination" and rewrites their contents to
get rounded corners.

In general, each "pagination" element has a child "span" element which contains
the page numbers.  Everything before the "span" element will be placed in a new
"div.vcdc-paginationleft" element.  The "span" element itself originally looks
similar to this:

  span
    a
    a
    strong
    a
    a
    ...
    a

Note that the ellipsis (...) is a literal ellipsis.

Each "a" and "strong" element will have a new "span" element appended to them,
and the "..." text node will be wrapped in a "span.vcdc-dotted" element.
*/
function vcdc_fixPagination() {
  var elements = document.getElementsByTagName('*');
  var numElements = elements.length;
  var paginationElements = [];
  for (var i = 0; i < numElements; ++i) {
    var element = elements.item(i);
    if (/(?:^|\s)pagination(?:\s|$)/.test(element.className)) {
      paginationElements.push(element);
    }
  }

  numElements = paginationElements.length;
  for (i = 0; i < numElements; ++i) {
    var paginationElement = paginationElements[i];
    var childNodes = paginationElement.childNodes;
    var numChildNodes = childNodes.length;
    var j;
    var childNode;
    var tagName;
    for (j = 0; j < numChildNodes; ++j) {
      childNode = childNodes.item(j);
      if (childNode.nodeType !== 1) {
        continue;
      }
      tagName = childNode.tagName.toLowerCase();
      if (tagName === 'span') {
        break;
      }
    }

    if (j < numChildNodes) {
      var span = childNode;
      var leftDiv = document.createElement('div');
      leftDiv.className = 'vcdc-paginationleft';
      span.className = 'vcdc-rounded';
      for (var k = j - 1; k >= 0; --k) {
        childNode = childNodes.item(k);
        leftDiv.insertBefore(childNode, leftDiv.firstChild);
      }
      paginationElement.insertBefore(leftDiv, span);

      // insert the spans
      childNodes = span.childNodes;
      numChildNodes = childNodes.length;
      for (j = 0; j < numChildNodes; ++j) {
        childNode = childNodes.item(j);
        switch (childNode.nodeType) {
        case 1:
          tagName = childNode.tagName.toLowerCase();
          if (tagName !== 'a' && tagName !== 'strong') {
            break;
          }
          childNode.appendChild(document.createElement('span'));
          var div = document.createElement('div');
          div.className = 'vcdc-roundedpage';
          span.replaceChild(div, childNode);
          div.appendChild(childNode);
          break;
        case 3:
          var dotted = document.createElement('div');
          dotted.className = 'vcdc-dotted';
          span.replaceChild(dotted, childNode);
          dotted.appendChild(childNode);
          break;
        default:
          break;
        }
      }
    }
  }
}

vcdc_fixPagination();
