// ==UserScript==
// @name Anchorize
// @author Jakub Roztocil  <jakub@webkitchen.cz>
// @version 0.1.6
// @ujs:published 2007-01-15
// @ujs:modified 2008-04-03
// @ujs:download http://www.webkitchen.cz/lab/opera/anchorize/anchorize.js
// @ujs:documentation http://www.operacesky.net/forum/viewtopic.php?t=3316
// @exclude *.googlesyndication.com*
// ==/UserScript==
window.addEventListener('DOMContentLoaded', function() {

	if (window.opera.anchorizeOff) {
		return;
	}

	var frag, node, tn, endOfLast, a, re, result, url, xpath, closeBracket;
	xpath = "//text()[(contains(.,'www.') or contains(.,'http://') or contains(.,'https://') or contains(.,'ftp://')) and not(ancestor::a or ancestor::script or ancestor::style or parent::textarea or parent::head)]";
	result = document.evaluate(xpath,  document.body || document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);

	re = {
		uri: /((https?|ftp):\/\/|www\.)([a-z0-9-]+\.)+[a-z0-9]+(\/[^\s<>"',;]*)?/gi,
		//                              \___________/  \_____/  \___________/
		//                                    |          |         |
		//                                subdomains    TLD       path
		//                               \___________________/
		//                                          |
		//                                        or IP
		openBracket: /[\{\(\[<]/,
		closeBracket: /[\}\)\]>]/
	}

	var i = 0;
	while (node = result.snapshotItem(i++)) {
		frag = document.createDocumentFragment();
		endOfLast = 0;
		url = null;
		while (url = re.uri.exec(node.data)) {

			if (url.index > 0 && re.openBracket.test(node.data.charAt(url.index - 1))) {
				closeBracket = re.closeBracket.exec(url);
				if (closeBracket) {
					// the URL seems to be inside brackets,
					// use the part before the closing one only
					url[0] = url[0].substring(0, closeBracket.index);
				}
			}

			if (endOfLast != url.index) {
				tn = document.createTextNode(node.data.substring(endOfLast, url.index));
				frag.appendChild(tn)
			}


			a = document.createElement('a');
			a.appendChild(document.createTextNode(url[0]));
			a.setAttribute('href', url[0].indexOf('www.') == 0 ? 'http://' + url[0] : url[0]);
			a.setAttribute('title', '{ANCHORIZED}');
			a.setAttribute('class', 'x-opera-anchorized');
			frag.appendChild(a)
			endOfLast = url.index + url[0].length;
		}
		if (endOfLast < node.data.length) {
			tn = document.createTextNode(node.data.substring(endOfLast, node.data.length));
			frag.appendChild(tn)
		}
		node.parentNode.replaceChild(frag, node);
	}

}, false);


