/*
	
	BeBib 0.1 - A library lookup greasemonkey script.
	by Boris Terzic (aggregat4+bebib@gmail.com)

	Requires the Greasemonkey extension for Firefox: http://greasemonkey.mozdev.org/

	I was becoming envious of all the nice American library integration scripts 
	that would check whether books on amazon were available in the library. Then
	it hit me. I could just write something myself!

	Specifically created for Gent library lookups.
	But theoretically easily extendable to other similar engines. <sic>

	Very hackish and heavily "inspired" by John Udell's library lookup script and "Book Burro".

*/
// ==UserScript==
// @name          BeBib
// @namespace     http://boris.terzic.be/bebib/
// @description   Lookup books in Gent library when on amazon.co.uk or amazon.com
// @include       http://*amazon.com*
// @include       http://*amazon.co.uk*
// ==/UserScript==

(function() {

var baseUrlGent = "http://www.bibliotheek.gent.be/webopac/";
var bibSearchUrlBeforePatternGent = "http://www.bibliotheek.gent.be/webopac/List.csp?Index1=Index19&Index2=Index1&Index3=Index1&Database=2&Year1=&Year2=&PublicationType=NoPreference&SearchMethod=Find_5&SearchTerm1="
var bibSearchUrlAfterPatternGent = "&SearchTerm2=&SearchTerm3=&OpacLanguage=dut&Profile=Default&Source=SysQR&PageType=Start&PreviousList=RecordListFind&WebPageNr=1&NumberToRetrieve=25&WebAction=NewSearch&StartValue=0&RowRepeat=2&ExtraInfo="

var libraryLookup = 
{
    insertLink: function(title, bookUrl, bookLabel)
    {
        var libraryUrl = document.createElement('div');
        libraryUrl.setAttribute('style','font: 12pt Verdana; padding: 4px;');

        var link = document.createElement('a');
        link.setAttribute ('title', bookLabel );
        link.setAttribute('href', bookUrl);

        var label = document.createTextNode(title + ": " + bookLabel);
        link.appendChild(label);

        libraryUrl.appendChild(link);

        var parent = titleNode.parentNode;
        parent.insertBefore(libraryUrl, titleNode.NextSibling);
    },

    doGentLookup: function ( bookTitle )
    {
        GM_xmlhttpRequest
        ({
            method:'GET',
            url: bibSearchUrlBeforePatternGent + bookTitle + bibSearchUrlAfterPatternGent,
            onload:function(results)
            {
				page = results.responseText;
				// Gent Bibliotheek results are embedded in a frame, we need the second one
				secondFrameUrl = page.match(/(ListBody[^']*)/)[1];
				GM_xmlhttpRequest
				({
					method:'GET',
					url: baseUrlGent + secondFrameUrl,
					onload:function(secondResults)
					{
						// extract results from that one
						resultPage = secondResults.responseText;
						firstHitUrl = resultPage.match(/(FullBB.csp\?WebAction=ShowFullBB[^']*)/)[1];
						if (firstHitUrl && firstHitUrl != null)
							libraryLookup.insertLink("Bibliotheek Gent", baseUrlGent + firstHitUrl, bookTitle);
					}
				});
            }
        });
    }


}

var titleNode = null;

if (document.location.href.match('amazon.com')) 
{
	titleNode = document.evaluate("//b[@class='sans']", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue;
}
if (document.location.href.match('amazon.co.uk'))
{
	titleNode = document.evaluate("//font[@face='verdana, helvetica, arial']/b", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue;
}

if (titleNode == null)
	return;

// we have a book, do the search query to gent bibliotheek
var searchTitle = titleNode.firstChild.nodeValue;
libraryLookup.doGentLookup(searchTitle);

})();
