// ==UserScript== // @foo Viewing in a browser?
// @name	Amazon Kent library search
// @author	paulypopex+php+library@gmail.com
// @namespace	http://www.clarkeology.com
// @description v0.1 Add Kent library search to Amazon pages. Free books!
// @see		http://www.clarkeology.com/m/12639/Kent+libraries+Amazon+Firefox+Greasemonkey+mashup
// @see		This is a Greasemonkey script, see https://addons.mozilla.org/en-US/firefox/addon/748
// @see		Based on http://userscripts.org/scripts/show/1396
// @see		jquery load from http://joanpiedra.com/jquery/greasemonkey/
// @include	http://*.amazon.*
// @changelog	v0.3 No longer needs json conversion via my site
// @changelog	v0.4 Monetize!
// @todo	stop being lazy, no need to include jquery...
// ==/UserScript==

(function(){

	var GM_JQ = document.createElement('script');
	GM_JQ.src = 'http://code.jquery.com/jquery-latest.js';
	GM_JQ.type = 'text/javascript';
	document.getElementsByTagName('head')[0].appendChild(GM_JQ);

	function GM_wait() { // Check if jQuery's loaded
		if ( typeof unsafeWindow.jQuery == 'undefined' ) {
			window.setTimeout( GM_wait, 100 );
		}
		else {	$ = unsafeWindow.jQuery;
			letsJQuery();
		}
	}
	GM_wait();
	return;
	
	function letsJQuery() { // All your GM code must be inside this function
		var isbn = getIsbn( window.content.location.href );
		if ( isbn != 0 ) {
			var div = $( '<'+'div class="libraryMonkey"><'+'/div>' );
			$('h1:first').after( div );
			$(div).html( 'Looking up ISBN ' + isbn + ' in Kent libraries... ' );
			var url = 'https://kent.spydus.co.uk/cgi-bin/spydus.exe/ENQ/OPAC/BIBENQ?ENTRY4_NAME=SBN&ENTRY4=' + isbn;
			try {	GM_xmlhttpRequest( { // to get htmlcross domain
					method: 'GET',
					url: url,
					headers: {
						'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey/0.3'
					},
					onload: function( response ) {
						$('a[href]').each( function () {
							$(this).attr('href', $(this).attr('href').replace(/ref=.*/,'?tag=clarkeology-21'));
						} );
						var xml = $( response.responseText );
						$(div).empty();
						var table = $('table.clsTab1', xml );
						if ( table.length ) {
							var available = [];
							var unavailable = [];
							$('tr', table ).each( function () {
								var availability = $('td', this ).eq(3).text( ).toLowerCase( );
								var library = $('td', this ).eq(0).text( );
								var html = '<'+'a href="' + url + '" title="' + availability + '">' + library + '<'+'/a>';
								if ( availability == 'available' ) {
									available.push( html );
								}		
								else if ( availability != '' ) {
									unavailable.push( html );
								}
							} );
							available.length || unavailable.length || $(div).append( error( 'Seemingly not available :-( ', isbn ));
							available.length && $(div).append( available + ' ' + ( available.length > 1 ? 'have' : 'has' ) + ' this. ' );
							unavailable.length && $(div).append( unavailable + ' can get it. ' );
							// window.console && console.log( unavailable );
							$(div).append( ' <'+'a href="' + url + '" title="Reserve this book, see more details etc">Look, reserve, etc<'+'/a>. ' );
						}
						else {	$(div).append( error( 'Cannot find this book in any library. ', isbn ));
						}
					}
				} );
			}
			catch ( e ) {
				$(div).append( error( 'Error: ' + e, isbn )); 
			}
		}
	}
	function error ( err, isbn ) {
		$.getJSON( 'http://www.clarkeology.com/php/library.php?isbn=' + isbn + '&callback=?&version={version}&error=' + escape( err ) + '&h1=' + escape( $('h1:first').text( )));
		return err;
	}
	function getIsbn ( url ) {
		var isbn = 0;
		try {	// match if there is a / followed by a 7-9 digit number followed by either another number or an x followed by a / or end of url 
			isbn = url.match(/\/(\d{7,9}[\d|X])(\/|$)/)[1]; 
		} catch ( e ) {
			isbn = 0;
		}
		return isbn;
	}
} )();