// RosaIndex BrReg linkify
// Version: 0.1
// Release: 16.10.2005
// Contact: remco at rc6 org
// License: http://creativecommons.org/licenses/by-sa/2.0/
//
// ==UserScript==
// @name           RosaIndex BrReg linkify
// @namespace      http://brink.st/config/files/userjs/
// @description    (v0.1) Looks for BrReg organization numbers on rosaindex.no and links them to brreg.no
// @include http://rosaindex.no/*
// @include http://www.rosaindex.no/*
// ==/UserScript==

if( 
		(window.location.hostname.match(/rosaindex\.no/)) && 
		((window.location.href.match(/cpyid=/)) && (window.location.href.match(/saction=view/)) || (window.location.href.match(/sitemap\/profile\.asp/)) && (window.location.href.match(/id=/)) )
	){ 

(function () {
	const BrRegex = /\b(\d\d\d\d\d\d\d\d\d)\b/ig;

	function BrRegURL(t) {
		return "http://w2.brreg.no/enhet/sok/detalj.jsp?orgnr=" + 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 BrReg');
        a.appendChild(document.createTextNode(match[0]));
        span.appendChild(a);

        lastLastIndex = BrRegex.lastIndex;
      }

      span.appendChild(document.createTextNode(source.substring(lastLastIndex)));
      span.normalize();
    }
	}

})();
}
