// ==UserScript==
// @name     Google-Search Track Link Remover
// @version  2.0
// @grant    none
// @include  *://www.google.*/search*
// ==/UserScript==
setTimeout(function(){
  console.log("Applying Track Link Remover");
  let counter = 0;
  
  let searchResultsContainer = getElementByXPath("//*[@id='search']/div[./h1]/div");
  if (searchResultsContainer == null) {
    console.warn("Search Results Container not found");
  } else {
    let seachLinks = getElementsByXPath(".//div//a[not(@href='') and ./h3]", searchResultsContainer);
    seachLinks.forEach(elem => {
      elem.addEventListener("click", e => {
        e.preventDefault();
        let url = getUrlFromElement(elem);
        console.log("Left-Click intercepted: " + url);
      	document.location.href = url;
      });
      elem.addEventListener("auxclick", e => {
        e.preventDefault();
        let url = getUrlFromElement(elem);
        console.log("Middle-Mouse intercepted: " + url);
      	window.open(url, "_blank");
      });
      counter++;
    });
    console.log("Patched " + counter + " links");
  }
  
  let searchBarBackground = getElementByXPath("//form[@action='/search']//div[contains(@class, 'logo')]/following-sibling::div[.//input]");
  if (counter > 0) {
  	searchBarBackground.style.backgroundColor = "#c9ffc940";
  } else {
  	searchBarBackground.style.backgroundColor = "#ffc9c940";
  }
  
}, 1000);
function getUrlFromElement(elem) {
	if (typeof elem != "object")
    return elem;
  if (typeof elem.href != "string" || !elem.href.startsWith("https://www.google.com/url"))
    return elem.href;
  try {
    let trackingUrl = new URL(elem.href);
    let cleanUrl = trackingUrl.searchParams.get("url");
    return cleanUrl;
  } catch (err) {
		return elem.href;
	}
}
function getElementByXPath(path, root) {
  return document.evaluate(path, root || document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}
function getElementsByXPath(xpath, parent) {
  let results = [];
  let query = document.evaluate(xpath, parent || document,
                                null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  for (let i = 0, length = query.snapshotLength; i < length; ++i) {
    results.push(query.snapshotItem(i));
  }
  return results;
}
/*
PREVIOUS VERSION
// ==UserScript==
// @name     Google-Search Track Link Remover
// @version  1
// @grant    none
// @include  *://www.google.*<REMOVE ME>/search*
// ==/UserScript==
setTimeout(function(){
  console.log("Applying Track Link Remover");
  var counter = 0;
  Array.from(document.getElementsByTagName("A")).forEach( function(elem, index, list) {  
    if (elem.getAttribute("data-arwt") != null){
      var clone = elem.cloneNode(true);
      clone.onclick = null;
      clone.setAttribute("onclick", null);
      clone.onmousedown = null;
      clone.setAttribute("onmousedown", null);
      clone.ontouchstart = null;
      clone.setAttribute("ontouchstart", null);
      clone["data-arwt"] = null;
      clone["data-ved"] = null;
      elem.parentElement.replaceChild(clone, elem);
      counter++;
    } else if (elem.href != null && elem.onmousedown != null){
      var clone = elem.cloneNode(true);
      clone.onmousedown = null;
      clone.setAttribute("onmousedown", null);
      clone.onclick = null;
      clone.setAttribute("onclick", null);
      elem.parentElement.replaceChild(clone, elem);
      counter++;
    }
  });
  console.log("Patched " + counter + " links");
  
  Array.from(document.getElementsByTagName("FORM")).forEach( function(elem, index, list) {
    var action = elem.getAttribute("action");
    if(action != null && action.includes("search")){
	  console.log(list);
      Array.from(elem.getElementsByTagName("INPUT")).forEach( function(elemInner) {
        var innerRole = elemInner.getAttribute("role");
        console.log(innerRole);
        if(innerRole != null && innerRole == "combobox" && elemInner.getAttribute("title") != null) {
		  if(counter > 0){
            elemInner.parentElement.parentElement.parentElement.style.backgroundColor = "#c9ffc9";
		  }else{
	        elemInner.parentElement.parentElement.parentElement.style.backgroundColor = "#ffc9c9";
	      }
        }
      });
    }
  });
  
  
}, 1000);
*/