// ==UserScript==
// @name           Google Scholar via Cornell Library
// @namespace      http://www.physics.cornell.edu/~shicks/
// @description    Adds a link "Access through Cornell Library" to Google Scholar results
// @include        http://scholar.google.com/scholar?*
// ==/UserScript==

// Mostly ripped from http://userscripts.org/scripts/source/9275

window.addEventListener("load", addResultLinks, false);

function addResultLinks() {

  var xpAnchor = "//p[@class='g']/span[@class='w']/a";
  var nlAnchors = $x(xpAnchor);
  
  // Iterate through the results, acting on blocked results, and adding
  // a link to block each result
  for (var i = 0; i < nlAnchors.length; i++) {
    // Find the main <div> that contains the result
    var nodeDiv = nlAnchors[i].parentNode.parentNode;
    var strHref = nlAnchors[i].toString();
    
    addLink(nodeDiv, strHref);
  }
}

function addLink(node, href) {
  
  // Find the node to which we will append the control link
  var nodeCorrectPlace = node.getElementsByTagName("font")[0];
  if (!nodeCorrectPlace) return;  

  // Check for existing control link, if exists, remove - otherwise, add
  // a text hyphen
  var nodeControl = nodeCorrectPlace.lastChild;
  if (nodeControl && nodeControl.nodeName == "SPAN" && nodeControl.hasAttribute("href")) {
    removeNode(nodeControl);
  } else {
    var nodeTextHyphen = document.createTextNode(" - ");
    nodeCorrectPlace.appendChild(nodeTextHyphen);
  }
  
  nodeControl = document.createElement("a");
  nodeControl.className = "fl";
  nodeControl.setAttribute("href", processHref(href));
  nodeControl.textContent = "Access via Cornell";
  
  nodeCorrectPlace.appendChild(nodeControl);

// Make a second link for "fast" access
  nodeCorrectPlace.appendChild(document.createTextNode(" "));
  nodeControl = document.createElement("a");
  nodeControl.className = "fl";
  nodeControl.textContent = "[login]";
  nodeControl.setAttribute("href", "http://encompass.library.cornell.edu/cgi-bin/checkIP.cgi?access=gateway_standard&url="+href);
  nodeCorrectPlace.appendChild(nodeControl);
  
}

function processHref(e) {
  var reDomain = /^https?:\/\/(?:www\d*\.)?(?:[\w-]+\.)*(?:\w+)(?=\/)/
//  var arrDomain = reDomain.exec(this.getAttribute("href"));
  var arrDomain = reDomain.exec(e);
  var arrPath   = e.substr(arrDomain[0].length);
  
  // Sanity check
  if (arrDomain && arrDomain.length == 1) {
    return arrDomain+".proxy.library.cornell.edu:2048"+arrPath;
  } else {
    GM_log("Error! Domain is malformed (or this script is broken)");
  }
  
}

/* ----- Helper function -------------------------------------------- */

// XPath helper
function $x(p, context) {
  if (!context) context = document;
  var i, arr = [], xpr = document.evaluate(p, context, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
  for (i = 0; item = xpr.snapshotItem(i); i++) arr.push(item);
  return arr;
}

// Remove DOM node
function removeNode(element) {
  element.parentNode.removeChild(element);
}
