// ==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.5 - 25th January 2008.
// Author:  Rich Burridge - Sun Microsystems Inc.
// Author:  Tyler Trafford


function xpstr(xpath, contextNode) {
    var document = contextNode.ownerDocument || contextNode;
    return document.evaluate(xpath, contextNode, null, 
                             XPathResult.STRING_TYPE, null).stringValue;
}

if (typeof GM_xmlhttpRequest != 'function') {
    // do nothing
} else {
    if (window == top) {

        var start = 1, end = 1;
        var pages = xpstr('//div[@id="items"]/p/strong[text()="Pages:"]/..',
                          document);
        if (pages) {
            var p = pages.match(/\d+/g);
            start = parseInt(p[0]);
            end = parseInt(p[p.length-1]);
        }

        var link = document.getElementsByTagName("link");
        for (var i = link.length-1; i >= 0; i--)
            link[i].parentNode.removeChild(link[i]);
        var script = document.getElementsByTagName("script");
        for (var i = script.length-1; i >= 0; i--)
            script[i].parentNode.removeChild(script[i]);

        var list = document.createElement("body");
        list.appendChild(document.createElement("h2"));
        list.firstChild.appendChild(document.createTextNode(document.title));
        list.appendChild(document.createElement("p"));
        document.body = list;

        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();

            var ol = document.createElement("ol");
            ol.id = "page" + j.toString();
            ol.style.marginTop = ol.style.marginBottom = "0px";
            list.appendChild(ol);

            process_url(j, pageUrl);
        }
    }
}

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

            // Find out the list entries on the page.
            var items = document.evaluate(
                './/td[starts-with(@class,"your-item")]',
                page, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

            var ol = document.getElementById("page" + pageNumber);

            for (var i = 0; i < items.snapshotLength; i++) {
                var item = items.snapshotItem(i);
                var position = xpstr('.//div[@class="position"]/text()', item);
                var title = xpstr('.//span[@class="item-title"]/a/text()', item);
                var creator = xpstr('.//div[@class="item-creator"]/text()', item);
                var pic = xpstr('.//img[@class="item-image"]/@src', item);

                if (!pic)
                    pic = "http://ec1.images-amazon.com/images/G/01/x-site/icons/no-img-sm._V47056216_.gif";

                ol.appendChild(createLI(position, pic, title, creator));
            }
        }
    });
}

function createLI(position, pic, title, creator) {
    var li = document.createElement("li");
    var a = document.createElement("a");

    if ( /amazon/.test(pic) && /_SCMZZZZZZZ_/.test(pic) ) {
        var asin = pic.match(/[^\/]*$/)[0].match(/^[^\.]+/);
        a.href = "http://www.amazon.com/exec/obidos/ASIN/" + asin + "/am841-20";
        //a.href = "http://www.amazon.com/gp/product/" + asin;
    } else {
        a.href = "http://www.amazon.com/gp/search/ref=sr_adv_b/?" +
                 "search-alias=stripbooks" +
                 "&author=" + escape(creator.replace(/^\s*by\s*/, "")) +
                 "&select-author=field-author-exact" +
                 "&title=" + escape(title) +
                 "&select-title=field-title";
    }

    a.appendChild(document.createElement("img"));
    a.firstChild.src = pic;
    a.firstChild.width = "50";
    a.appendChild(document.createTextNode(" " + title));
    li.appendChild(a);
    li.appendChild(document.createTextNode(creator));
    li.value = position;

    return li;
}

// ChangeLog
// 25th Jan 2008  - 0.5 - Tyler Trafford - Added support for Amazon links.
//  1st Oct 2007  - 0.4 - Tyler Trafford - improved page start/end code.
// 29th Sept 2007 - 0.3 - richb - Initial version posted to blog.
