// ==UserScript==
// @name               Bookmania
// @namespace     http://www.longhighway.com/greasemonkey
// @description    Add search links for Hennepin County, Ramsey County, St. Paul, and MnLINK library catalogs to Barnes & Noble and Amazon book, DVD, and CD pages. Add links to ISBNdb.com and WorldCat. Also add link to bookmark page in del.icio.us with non-shared tag "_booktoread". // @include http://search.barnesandnoble.com*
// @include           http://search.barnesandnoble.com*
// @include           http://music.barnesandnoble.com*
// @include           http://video.barnesandnoble.com*
// @include           http://www.amazon.com*
// ==/UserScript==

var hook;
var isbn;
var site;
var title;

function tagIt(postUrl) {
  GM_xmlhttpRequest({
      method: 'GET',
      url: postUrl,
      onload: function(response) {
        var parser = new DOMParser();
        var doc = parser.parseFromString(response.responseText, "text/xml");
        elements = doc.getElementsByTagName("result");
        if ((elements.length == 0) || (elements[0].getAttribute("code") != "done")) {
          alert("Post to del.icio.us failed.");
        }
      }
  });
}

function createDelicioiusTagDiv() {
  var deliciousLink = document.createElement("a");
  deliciousLink.innerHTML = "del.icio.us";
  deliciousLink.setAttribute("title", "Tag with \"_booktoread\" at del.icio.us");

  var deliciousPostURL = "https://api.del.icio.us/v1/posts/add?&url=" + encodeURIComponent(window.location.href) + "&description=" + encodeURIComponent(document.title) + "&tags=_booktoread" + "&shared=no";
  deliciousLink.href = deliciousPostURL; 
  deliciousLink.addEventListener(
    "click", 
    function (event) { 
      tagIt(event.originalTarget.toString()); 
      this.style.color = "grey";
      event.stopPropagation();
      event.preventDefault();
    }, 
    false);

  var newDiv = document.createElement("div");
  var comment = document.createElement("strong");
  comment.innerHTML = "Bookmark: ";
  newDiv.appendChild(comment);
  newDiv.appendChild(deliciousLink);
  return newDiv;
}

function createTitleSearchDiv(title) {
  var hennLink = document.createElement("a");
  hennLink.setAttribute("href", "http://catalog.hclib.org/ipac20/ipac.jsp?menu=search&aspect=subtab13&npp=20&ipp=20&spp=20&profile=elibrary&ri=&index=.TW&term=" + encodeURIComponent(title));
  hennLink.setAttribute("title", "Lookup title at the Hennepin County Library");
  hennLink.innerHTML = "HCL";
  
  var ramsLink = document.createElement("a");
  ramsLink.setAttribute("href", "http://ipac.ramsey.lib.mn.us/ipac20/ipac.jsp?menu=search&aspect=numeric&npp=10&ipp=20&spp=20&profile=zz&ri=&index=ALLTI&term=" + encodeURIComponent(title));
  ramsLink.setAttribute("title", "Lookup title at the Ramsey County Library");
  ramsLink.innerHTML = "RCL";

  var stpLink = document.createElement("a");
  stpLink.setAttribute("href", "http://alpha.stpaul.lib.mn.us/search/t=" + encodeURIComponent(title));
  stpLink.setAttribute("title", "Lookup title at the St. Paul Public Library");
  stpLink.innerHTML = "SPPL";

  var mnLink = document.createElement("a");
  mnLink.setAttribute("href", "https://www.mnlinkgateway.org/zportal/zengine?VDXaction=ZSearchAdvanced&attr_type1_row1=0&search_term_row1=" + encodeURIComponent(title) + "&sourceid=Mozilla-search");
  mnLink.setAttribute("title", "Lookup title in MnLINK");
  mnLink.innerHTML = "MnLINK"

  var newDiv = document.createElement("div");
  var comment = document.createElement("strong");
  comment.innerHTML = "Search for title: ";
  newDiv.appendChild(comment);
  newDiv.appendChild(hennLink);
  newDiv.appendChild(document.createTextNode("\u00a0\u00a0"));
  newDiv.appendChild(ramsLink);
  newDiv.appendChild(document.createTextNode("\u00a0\u00a0"));
  newDiv.appendChild(stpLink);
  newDiv.appendChild(document.createTextNode("\u00a0\u00a0"));
  newDiv.appendChild(mnLink);   
  return newDiv;
}

function createIsbnSearchDiv(isbn) {
  var hennLink = document.createElement("a");
  hennLink.setAttribute("href", "http://catalog.hclib.org/ipac20/ipac.jsp?menu=search&aspect=power&npp=20&ipp=20&spp=20&profile=elibrary&ri=&index=ISBN&term=" + isbn + "&x=14&y=10&aspect=power#focus");
  hennLink.setAttribute("title", "Lookup ISBN at the Hennepin County Library");
  hennLink.setAttribute("style", "color:red");
  hennLink.innerHTML = "HCL";
  
  var ramsLink = document.createElement("a");
  ramsLink.setAttribute("href", "http://ipac.ramsey.lib.mn.us/ipac20/ipac.jsp?menu=search&aspect=numeric&npp=10&ipp=20&spp=20&profile=zz&ri=&index=ISBNE&term=" + isbn);
  ramsLink.setAttribute("title", "Lookup ISBN at the Ramsey County Library");
  ramsLink.innerHTML = "RCL";

  var stpLink = document.createElement("a");
  stpLink.setAttribute("href", "http://alpha.stpaul.lib.mn.us/search/i=" + isbn);
  stpLink.setAttribute("title", "Lookup ISBN at the St. Paul Public Library");
  stpLink.innerHTML = "SPPL";

  var mnLink = document.createElement("a");
  var longHrefStart = "http://www.mnlinkgateway.org/zportal/zengine?default_VDXaction=ZSearchAdvanced&FormName=adv_search_form&show_collections=0&VDXaction=ZSearchAdvanced&";
  var longHrefEnd = "collection_id=&attr_type1_row1=7&logic_row1=%40and&attr_type2_row1=3&attr_type3_row1=&attr_type4_row1=&attr_type5_row1=&attr_type6_row1=&attr_type1_row2=1003&search_term_row2=&logic_row2=%40and&attr_type2_row2=3&attr_type3_row2=&attr_type4_row2=&attr_type5_row2=&attr_type6_row2=&attr_type1_row3=21&search_term_row3=&attr_type2_row3=3&attr_type3_row3=&attr_type4_row3=&attr_type5_row3=&attr_type6_row3=&filter_specific=&filter_from=&filter_to=&PeerReviewed=N&refine=off&pagesize=20&ZSearch.x.x=29&ZSearch.x.y=7&ZSearch.x=Search+Now%21&current_profile=1&collections=1&collections=2&collections=3&collections=4&collections=5&collections=6&collections=7&collections=8&collections=66&collections=59&collections=9&collections=50&collections=28&collections=45&collections=13&collections=67&collections=14&collections=15&collections=16&collections=34&collections=19&collections=20&collections=21&search_term_row1=";
  mnLink.setAttribute("href", longHrefStart + longHrefEnd + isbn);
  mnLink.setAttribute("title", "Lookup ISBN in MnLINK");
  mnLink.innerHTML = "MnLINK"

  var isbndbLink = document.createElement("a");
  isbndbLink.setAttribute("href", "http://isbndb.com/search-all.html?kw=" + isbn);
  isbndbLink.setAttribute("title", "Lookup ISBN at ISBNdb.com");
  isbndbLink.innerHTML = "ISBNdb.com";

  var worldcatLink = document.createElement("a");
  worldcatLink.setAttribute("href", "http://www.worldcat.org/search?q=" + isbn);
  worldcatLink.setAttribute("title", "Lookup ISBN in WorldCat");
  worldcatLink.innerHTML = "WorldCat";

  var newDiv = document.createElement("div");
  var comment = document.createElement("strong");
  comment.innerHTML = "Search for ISBN: ";
  newDiv.appendChild(comment);
  newDiv.appendChild(hennLink);
  newDiv.appendChild(document.createTextNode("\u00a0\u00a0"));
  newDiv.appendChild(ramsLink);
  newDiv.appendChild(document.createTextNode("\u00a0\u00a0"));
  newDiv.appendChild(stpLink);
  newDiv.appendChild(document.createTextNode("\u00a0\u00a0"));
  newDiv.appendChild(mnLink);
  newDiv.appendChild(document.createTextNode("\u00a0\u00a0"));
  newDiv.appendChild(isbndbLink);
  newDiv.appendChild(document.createTextNode("\u00a0\u00a0"));
  newDiv.appendChild(worldcatLink);
  return newDiv;
}

if (location.hostname.search(/barnesandnoble.com/) != -1) {
  site = "Barnes & Noble";
  var isbnMatch = document.evaluate("id('tab-overview')/div/div/div[1]/div/div/div[2]/ul/li[3]/a", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
  if (isbnMatch) {
    isbn=isbnMatch.textContent
  } else {
	var isbnMatch = document.evaluate("id('tab-overview')/div/div/div[1]/div/div/div[2]/ul/li[2]/a", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
	if (isbnMatch) {
		isbn=isbnMatch.textContent
	}
  }
  var titleMatch = document.evaluate("id('product-info')/div/h1", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;  
  if (titleMatch) {
    var titleAndAuthor = titleMatch.textContent;
	var lastBy = titleAndAuthor.lastIndexOf('by');
	if (lastBy != -1) {
		var longTitle = titleAndAuthor.substring(0, lastBy);
	} else {
		var longTitle = titleAndAuthor;
	}
	title = longTitle.replace(/\[.*\]|\(.*\)/g, '');
  }
  hook = document.evaluate("id('product-wrap')", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

} else {
  site = "Amazon";
  var isbnMatch = location.href.match(/\d{9}[\d|X]/);
  if (isbnMatch) {
    isbn = isbnMatch[0];
  }
  var titleMatch = document.evaluate("id('btAsinTitle')", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

  if (!titleMatch) {    // Not a book, might be DVD or CD
    titleMatch = document.evaluate("id('handleBuy')/div/div/div/b", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
  }
  var longTitle = titleMatch.textContent;
  var title = longTitle.replace(/\[.*\]|\(.*\)/g, '');
  
  hook = document.evaluate("id('handleBuy')/div[1]", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}

if (hook && title) {
  if (isbn) {
    hook.appendChild(createIsbnSearchDiv(isbn));
  }
hook.appendChild(createTitleSearchDiv(title));
}
hook.appendChild(createDelicioiusTagDiv());

