/* Random Book Finder, version [0.0.4a-r2]
Originally from: http://en.wikibooks.org/wiki/User:Splarka/randbook.js
Based roughly on http://en.wikibooks.org/w/index.php?title=MediaWiki:RandomBook.js&oldid=1209572 by Darklama.

Grabs 10 random pages from the API, checks if any are books. Repeats until it finds a book.

Notes:
* Don't try to grab more than 10 random pages, callback is limited to 10 at a time.
* As 10.5% of pages are books, most queries should take no more than 2 iterations.
* Setting window.location.href eats history in some browsers.
* curid point to the correct book even if the book title is renamed in the mean time.
* To append links instead use: mw.config.set( 'random_book_list, true ); (users can set this in their individual common.js too);
*/

$(document).ready( function($) {
	var	reqid = 0, random_list = mw.config.get( 'random_book_list', false ),
		randbookLink = mw.util.addPortletLink( 'p-Navigation', '#', 'Random book', 'n-randbook', 'Show me a random book', 'x' );

	function fetch_categories( id, callback ) {
		$.getJSON( mw.util.wikiScript( 'api' ), {
			format:		'json',
			action:		'query',
			prop:		'categories',
			cllimit:	100,
			generator:	'random',
			grnnamespace:	'0|110',
			grnlimit:	10,
			requestid:	id
		}, callback );
	}

	function showRandBookCB(obj) {
		var pages, found = [];

		if ( !obj.query || !obj.query.pages ) {
			$(randbookLink).append('<span class="error">error</span>');
			if ( random_list ) {
				removeSpinner( 'randbook' );
			}
			return false;
		}

		pages = obj.query.pages

		for ( var page in pages ) {
			found = found.concat( $.map( pages[page].categories || [], function( cat ) {
				if ( cat.title.indexOf( 'Category:Alphabetical/' ) === 0 ) {
					return { id: page, title: pages[page].title };
				}
			} ) );
		}

		if ( !found.length ) {
			// didn't find any, try again
			fetch_categories( reqid, showRandBookCB );
			++reqid;
		} else {
			var link = mw.config.get( 'wgServer' ) + mw.config.get( 'wgScript' ) + '?curid=';

			if ( random_list ) {
				removeSpinner( 'randbook' );
				$.each( found, function() {
					$(randbookLink).append('<div><a href="' + link + this.id + '"> \u2022\u00A0' + this.title + '</a></div>');
				});
			} else {
				found = found[ Math.floor( Math.random()*found.length ) ];
				window.location.assign( link + found.id );
			}
		}
		return true;
	}

	$(randbookLink).click( function() {
		if ( random_list ) {
			injectSpinner( this, 'randbook' );
		}
		fetch_categories( reqid, showRandBookCB );
		++reqid;
	});
});