// ==UserScript==
// @foo		Viewing in a browser? <pre>
// @name	Amazon Kent library search
// @author	paulypopex+php+library@gmail.com
// @version	0.1
// @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		Based on http://userscripts.org/scripts/show/1396
// @see		jquery load from http://joanpiedra.com/jquery/greasemonkey/
// @include	http://*.amazon.*
// ==/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 ) {
			$('h1:first').after( '<'+'div class="libraryMonkey"><'+'/div>' );
			var div = $('div.libraryMonkey').eq(0);
			$(div).html( 'Looking up ISBN ' + isbn + ' in Kent libraries... ' );
			var url = 'http://www.clarkeology.com/php/library.php?isbn=' + isbn + '&callback=?&version={version}&h1=' + escape( $('h1:first').text( ));
			$.getJSON( url, function ( js ) {
				if (	js.availability && js.availability.available ) {
					$(div).empty();
					var i = 0;
					for ( library in js.availability.available ) {
						$(div).append( i ++ ? ' + ' : '<'+'br />' );
						$(div).append( library );
					}
					$(div).append( ' library ' + ( i > 1 ? 'have' : 'has' ) + ' this' );
					js.url && $(div).append( ' <'+'a href="' + js.url + '" title="Find out more, including other libraries who have this book out on loan.">look, reserve, etc<'+'/a>' );
				}
				else { $(div).append( 'No available copies.' );
				}
				js.message && $(div).append( '<'+'div>' + js.message + '<'+'/div>' );
			} );
	
		}
	}

	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;
	}
} )();

