// ==UserScript==

// @name          Google Links Cleanser

// @namespace     http://pogopixels.com

// @description   Convert the redirection links in Google's search results to direct links.

// @include       http://*.google.*
// @include       https://*.google.*

// ==/UserScript==

// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License
function parseUri(a){var b=parseUri.options,c=b.parser[b.strictMode?"strict":"loose"].exec(a),d={},e=14;while(e--)d[b.key[e]]=c[e]||"";d[b.q.name]={};d[b.key[12]].replace(b.q.parser,function(a,c,e){if(c)d[b.q.name][c]=e});return d}parseUri.options={strictMode:false,key:["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],q:{name:"queryKey",parser:/(?:^|&)([^&=]*)=?([^&]*)/g},parser:{strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}}

function isMangledLink(url) {
	var parsed = parseUri(url);
	if (parsed.host.indexOf("google.") < 0) return false;
	if (url.indexOf("/url?") < 0) return false;
	if (url.indexOf("&url=") < 0) return false;
	return true;
}

// Get all the anchors
var tags = document.getElementsByTagName('a');

for (i = 0; i < tags.length; i++) {
	var tag = tags[i];
	var href = tag.getAttribute("href");
	
	// Remove the onmousedown events used for tracking
	var onmousedownAttribute = tag.getAttribute("onmousedown");
	if (onmousedownAttribute && onmousedownAttribute.indexOf("return rwt") >= 0) tag.removeAttribute("onmousedown");
	
	if (!isMangledLink(href)) continue;	
	
	// Try to extract the real URL
	var parsed = parseUri(href);	
	var realUrl = "";
	var query = parsed.query.split("&");
	for (var j = 0; j < query.length; j++) {
		var items = query[j].split("=");
		if (items[0] == "url") { // We found the real URL
			realUrl = unescape(items[1]);
			break;
		}
	}
	
	if (realUrl == "") continue; // Skip it if we didn't find the real URL
	
	tag.setAttribute("href", realUrl);
}
