// ==UserScript==
// @name        Lists of Bests
// @namespace   http://blogs.sun.con/richb/
// @description Script to improve Lists of Bests lists display
// @include     http://www.listsofbests.com/list/*
// ==/UserScript==

// Version: 0.4 - 1st October 2007.
// Author:  Rich Burridge - Sun Microsystems Inc.
//          with considerable help from Tyler Trafford (thanks!)

// Each x element is the HTML built from .../?page=x
var pageArray = new Array();

if (typeof GM_xmlhttpRequest != 'function') {
    // do nothing
} else {
    if (window == top) {
        var start = 1;
        var end = 1;

        // Determine how many pages are in the list.
        var pages = document.evaluate(
            'string(//div[@id="items"]/p[position()=1])',
            document,
            null,
            XPathResult.STRING_TYPE,
            null).stringValue;

        if (pages && pages.match(/^Pages:/)) {
            start = parseInt(pages.match(/\d+/)[0]);
            end = parseInt(pages.match(/\d+\s*$/));
        } 

        // Construct a new web page just containing the list as a
        // single numbered table, by iterating of all the web pages
        // that make up this list.
        var newHTML = '<div id="the_list" style="margin:0 auto 0 auto; ' +
                    'text-align:left; position:absolute; ' +
                    'left:15px; top:15px; margin: 5px; padding: 5px; ">' +
                      '<h2>' + document.title +
                      '</h2>\n<p>\n<ol>\n'

        // Add in the header/footer for the array
	pageArray[0] = newHTML;
	pageArray[end+1] = '</ol>\n<p>\n</div>\n';

        for (var j = start; j <= end; j++) {
            // See if there is a "?" character in the URL. If not
            // then it's the first page of the list. Set the pageUrl
            // accordingly.
            var last = document.baseURI.lastIndexOf("?");
            if (last == -1) {
                last = document.baseURI.length;
            }
            var pageUrl = document.baseURI.substring(0, last) + 
                          "?page=" +  j.toString();

            // Passing in 'j' to use as the array index for the page data.
            // We don't know what order the callbacks will finish, or even 
            // start, so this keeps everything in order.
            process_url(j, pageUrl);
        }
    }
}

function process_url(index, pageUrl) {
    GM_xmlhttpRequest({
        method:'GET',
        url:pageUrl,
        onload:function(responseDetails){
            thisPage = document.createElement("div");
            thisPage.innerHTML = responseDetails.responseText

            // Find out the list entries on the page.
            var allDivs = document.evaluate(
            ".//div[@class='position']",
            thisPage,
            null,
            XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
            null);

            var newHTML = "";

            for (var k = 0; k < allDivs.snapshotLength; k++) {
                thisDiv = allDivs.snapshotItem(k);

                // Get the position of this item in the list.
                tokens = thisDiv.textContent.split('.')
                position = tokens[0];

                thisDiv = thisDiv.parentNode
                var title = document.evaluate(
                    ".//*[@class='item-title']/a/text()",
                    thisDiv,
                    null,
                    XPathResult.STRING_TYPE,
                    null).stringValue;

                var creator = document.evaluate(
                    ".//*[@class='item-creator']/text()",
                    thisDiv,
                    null,
                    XPathResult.STRING_TYPE,
                    null).stringValue;

                newHTML = newHTML +
                          '  <li value=' + position + '>' + title +
                          ' ' + creator + '</li>\n'
            }

            // The page is rebuilt as new data arrives (each time the 
            // callback runs).
            pageArray[index] = newHTML;
            document.body.innerHTML = pageArray.join('');
        }
    });
}

// ChangeLog
//  1st Sept 2007 - 0.4 - Tyler Trafford - improved page start/end code.
// 29th Sept 2007 - 0.3 - richb - Initial version posted to blog.
