// Doubleclick Relinker
// version 1.0
// 26NOV2007

/*
    Rewrite doubleclick links so they
    don't redirect your browser through doubleclcik
    Scott Kingery, scott@techlifeweb.com
    http://www.techlifeweb.com

    Many thanks to Albert Bachand who wrote the
    No middle man script. I have borrowed
    some of his code here
    http://fivethreenine.blogspot.com/2006/03/no-middle-man.html

    Copy, use, modify, spread as you see fit.
*/
//
// This is a Greasemonkey user script.  To install it, you need
// Greasemonkey: http://www.greasespot.net/
// Then restart Firefox and revisit this script.
// Under Tools, there will be a new menu item to "Install User Script".
// Accept the default configuration and install.
//
// To uninstall, go to Tools/Manage User Scripts,
// select "Doubleclick Relinker", and click Uninstall.
//

// ==UserScript==
// @name          Doubleclick Relinker
// @namespace     http://www.techlifeweb.com
// @description	  Rewrites any links that contain references to doubleclick.net
// @include       *
// ==/UserScript==

var pageAddr, links, a, href;
links = document.evaluate(
    "//a[contains(@href,'doubleclick.net')]",
    document,
    null,
    XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
    null);

for (var i = 0; i < links.snapshotLength; i++) {
    a = links.snapshotItem(i);
    href = a.href.toLowerCase();

    // we look for the real url contained at the end of the redirecting URL
    start = Math.max(href.lastIndexOf('http:'),
	href.lastIndexOf('https:'),
	href.lastIndexOf('http%3a'),
	href.lastIndexOf('https%3a'),
	href.lastIndexOf('https%253a'),
	href.lastIndexOf('https%253a'));

  // we are most likely looking at a redirection link
  if (start > 0) {
    url = href.substring(start);

  // now we do the rewriting of the urls
    a.href = url.replace(/&amp;/g, '&');

}
}
