// ==UserScript==
// @name          ASIN to UPC converter.
// @namespace     http://chopac.org/tools/
// @description	  Finds the UPC for the ASIN.
// @include       http://*.amazon.*/*
// ==/UserScript==

var searchKey = document.getElementById("ASIN");
var chopac = "http://chopac.org/cgi-bin/tools/asin2upc.pl?" + searchKey.value;
var infosoup = "http:/infosoup.org/search/i";
if (searchKey.value.match(/^[0-9]/)) {
	infoSearch(searchKey.value)
}
else {
	getUPC()
}

function getUPC() {
	GM_xmlhttpRequest({
    		method: 'GET',
    		url: chopac,
    		onload: function(responseDetails) { infoSearch(responseDetails.responseText) }
	});
}
function infoSearch(standardNum) {
	GM_xmlhttpRequest({
	    method: 'GET',
	    url: infosoup + standardNum,
	    onload: function(responseDetails) { parseInfo(responseDetails.responseText) }
	});
}
function parseInfo(iData) {
	var recCSS = "<style> .bibItems {margin: 20px; background-color: beige; border: solid; border-width: 1px} th {background-color: black; color: beige}</style>";
	var recLink = iData.match(/record=b[0-9]+/);
	var recItems = iData.match(/<table.+?class=.bibItems[\s\S]+?<\/table>/i);
	recItems[0] = recItems[0].replace(/<a.+?>/gm, "");
	var navbar, newElement;
	navbar = document.getElementById("handleBuy");
	if (navbar) {
	    newElement = document.createElement('div');
	    newElement.innerHTML = recCSS + "<h2>Infosoup libraries have this title... <input type='button' value='Catalog' onClick='location.href=\"http://www.infosoup.org/" + recLink[0] + "\"></h2>" + recItems[0];
	    navbar.parentNode.insertBefore(newElement, navbar);
//	    navbar.parentNode.insertBefore(newElement, navbar.nextSibling);
	}
}