// ==UserScript==
// @name Clean URI
// @author TarquinWJ 
// @namespace http://www.howtocreate.co.uk/ 
// @version 1.2.2
// @description  Attempts to replace redirected links with a direct
//			link to the final page.
// @ujs:category general: enhancements
// @ujs:published 2005-05-30 21:42
// @ujs:modified 2005-09-29 11:22
// @ujs:documentation http://userjs.org/scripts/general/enhancements/clean-uri 
// @ujs:download http://userjs.org/scripts/download/general/enhancements/clean-uri.js
// ==/UserScript==


/* 
 * Please see
 * http://www.howtocreate.co.uk/operaStuff/userJavaScript.html#terms
 * for License and Terms of Use
 */

document.addEventListener(
	'load',
	function ujsenabledCleanURI() {

		/****************************************************************************************
		                                   Options can be set here
		****************************************************************************************/

		var useSeparateLink = false; //true to create 'CleanURL' links, false to replace existing
		var fixLinkType = 0; //1 = redirect links, 2 = JavaScript window.open links, 0 = both

		/***************************************************************************************/

		for( var x = 0, urlMatch = /window\.open\s*\(\s*["']([^"']*)["']/, httpMatch = /https?(:|%3a)(\/|%2f)(\/|%2f)/i; x < document.links.length; x++ ) {
			var newHref = '', curLink = document.links[x];
			if( ( fixLinkType != 1 ) && curLink.protocol.toLowerCase() == 'javascript:' && curLink.href.match(urlMatch) ) {
				newHref = (RegExp.$1).replace(/\\\//g,'\/');
			} else if( ( fixLinkType != 1 ) && ( curLink.protocol.toLowerCase() == 'javascript:' || curLink.hash == '#' ) && curLink.getAttribute('onclick').match(urlMatch) ) {
				newHref = (RegExp.$1).replace(/\\\//g,'\/');
			} else if( ( fixLinkType != 2 ) && curLink.hostname && !curLink.hostname.match(/w3c?.org$/) && ( pos = curLink.search.match(httpMatch) ) ) {
				newHref = unescape(curLink.search.substr(pos.index).replace(/[&#].*$/g,''));
			}
			if( newHref ) {
				var oRel = curLink.getAttribute('rel');
				oRel = oRel ? ( oRel + ' ' ) : '';
				curLink.setAttribute('rel',oRel+'redirect');
				if( useSeparateLink ) {
					var oLink = document.createElement('a');
					oLink.setAttribute('href',newHref);
					oLink.appendChild(document.createTextNode('[CleanURL]'));
					curLink.parentNode.insertBefore(document.createTextNode(' '),curLink.nextSibling);
					curLink.parentNode.insertBefore(oLink,curLink.nextSibling.nextSibling);
					x++;
				} else {
					curLink.setAttribute('replacedurl',curLink.href);
					curLink.title = ( curLink.title ? ( curLink.title + ' - ' ) : '' ) + 'Old URL: ' + curLink.href;
					curLink.href = newHref;
				}
			}
		}
	},
	false
);