// ==UserScript==
// @name           replace amazon associate
// @namespace      http://fuba.moaningnerds.org/
// @include        *
// @version        0.20081120.5
// ==/UserScript==

// You MUST read http://fuba.jottit.com/give_me_money or uninstall this script.

(function () {
var source_url = 'http://fuba.jottit.com/give_me_money';

var now = function () {
    return (new Date()).getTime()
};

var set_associate_id = function () {
    var associate_id = window.prompt('input your associate id', GM_getValue('myid'));
    GM_setValue('myid', associate_id);
    return associate_id;
};

var update = function () {
    GM_log('update cache');
    GM_xmlhttpRequest({
        method: 'get',
        url: source_url,
        onload: function (resp) {
            var txt = resp.responseText;
            
            var associate_id = GM_getValue('myid');
            if (typeof(associate_id) == 'undefined') {
                associate_id = set_associate_id();
            }
            
            txt.match(/<pre id=\"amazon\">\s*([^<]+?)\s*<\/pre>/);
            var list_txt = RegExp.$1;
            var idlist = list_txt.split("\n") || [list_txt];
            idlist = idlist.filter(function(elem){
                return (elem != '') && (elem != associate_id);
            });
            
            GM_setValue('cache', {
                list: idlist,
                expire: now() + 360000000,
            }.toSource());
        },
    });
    return eval(GM_getValue('cache'));
};

var load_data = function () {
    var data_text = GM_getValue('cache');
    var data = ('undefined' != typeof(data_text)) ? eval(data_text) : update();
    if (data.expire < now()) data = update();
    return data;
};

var random_list = function () {
    var data = load_data();
    var ids = data.list;
    return ids[Math.floor(ids.length * Math.random())];
};

GM_registerMenuCommand('replace amazon associate - init', function() {
    set_associate_id();
    update();
    document.location.reload();
});

var replace_id = function (doc) {
    var replaced_id = random_list();
    var associate_id = GM_getValue('myid');
    var associate_regexp = new RegExp(associate_id, 'g');
    
    var ancs = doc.getElementsByTagName('A');
    for (var i=0;i<ancs.length;i++) {
        if (ancs[i] && ancs[i].href && (
                ancs[i].href.match(/amazon\.co\.jp/i)
                || ancs[i].href.match(/d\.hatena\.ne\.jp\/asin/i)
            )
        ) {
            ancs[i].href = ancs[i].href.replace(associate_regexp, replaced_id);
        }
    }
};

replace_id(document);
if (window.AutoPagerize)
    window.AutoPagerize.addFilter(function(docs){docs.forEach(replace_id);});

})();

