// BrReg Phonenumber linkify
// Version: 0.1
// Release: 16.10.2005
// Contact: remco at rc6 org
// License: http://creativecommons.org/licenses/by-sa/2.0/
//
// ==UserScript==
// @name           BrReg Phonenumber linkify
// @namespace      http://brink.st/config/files/userjs/
// @description    (v0.1) Looks for phonenumbers on the BrReg pages and links them to Gule Sider.
// @include *
// ==/UserScript==

if( (window.location.hostname.match(/brreg\.no/)) 
		&& (window.location.href.match(/orgnr=/)) 
		){ 

(function () {
	const BrRegex = /\b(\d\d \d\d \d\d \d\d)\b/ig;

	function BrRegURL(t) {
		return "http://www.gulesider.no/gsi/numberSearch.do?tel=" + String(t).replace(/ /g, "");
	}

  // tags we will scan looking for un-hyperlinked urls
  var allowedParents = [ "td", "tr" ];
    
  var xpath = "//text()[(parent::" + allowedParents.join(" or parent::") + ")" +
		//" and contains(translate(., 'HTTP', 'http'), 'http')" + 
		"]";

  var candidates = document.evaluate(xpath, document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);

  for (var cand = null, i = 0; (cand = candidates.snapshotItem(i)); i++) {

		// Replace organization number with a link
		if (BrRegex.test(cand.nodeValue)) {
			var span = document.createElement("span");
      var source = cand.nodeValue;
            
      cand.parentNode.replaceChild(span, cand);

      BrRegex.lastIndex = 0;
      for (var match = null, lastLastIndex = 0; (match = BrRegex.exec(source)); ) {
      	span.appendChild(document.createTextNode(source.substring(lastLastIndex, match.index)));
                
        var a = document.createElement("a");
        a.setAttribute("href", BrRegURL(match[0]));
				a.setAttribute("title", 'Linkified to Gule Sider');
        a.appendChild(document.createTextNode(match[0]));
        span.appendChild(a);

        lastLastIndex = BrRegex.lastIndex;
      }

      span.appendChild(document.createTextNode(source.substring(lastLastIndex)));
      span.normalize();
    }
	}

})();
}

