// ==UserScript==
// @name        First Off
// @description "first off" links for the LJ entries
// @namespace   http://wagner.pp.ru/~slobin/firefox/
// @include     http://*.livejournal.com/*
// ==/UserScript==

// Idea by Andrzej Novosiolov, implementation by Cyril Slobin
// 24 Jun 2008, after midnight

var wording = [[1, "первыйнах!"], [2, "второйнах!"], [3, "третийнах!"],
               [10, "фдисятке!"], [20, "фдвацатке!"], [30, "фтрицатке!"]];
var toomany = "аффтар жжот!";
               
function lookup(n)
{
    for (var i = 0; i < wording.length; i++) {
        if (wording[i][0] > n) {
            return wording[i][1];
        }
    }
    return toomany;
}

var mainviewPattern = /livejournal\.com\/(friends\/?)?(\?|$)/;
var recordPattern = /livejournal\.com\/(.*?\/)?[0-9]+\.html/;
var replyPattern = /livejournal\.com\/(.*?\/)?[0-9]+\.html\?mode\=reply/;

var cmatch, commenttext, counter, allAnchors, prevAnchor, thisAnchor;

cmatch = /\&counter\=([0-9]+)$/.exec(window.location.href);
commenttext = document.getElementById("commenttext");

if (cmatch && commenttext) {
    commenttext.value = lookup(cmatch[1]) + "\n";
    return;
}

if (! mainviewPattern.test(window.location.href)) {
    return;
}

allAnchors = document.getElementsByTagName("a");

for (var i = 0; i < allAnchors.length; i++) {
    prevAnchor = thisAnchor;
    thisAnchor = allAnchors[i];
    if (replyPattern.test(thisAnchor.href)) {
        if (recordPattern.test(prevAnchor.href)) {
            cmatch = /[0-9]+/.exec(prevAnchor.innerHTML);
            counter = cmatch ? cmatch[0] : 0;
        } else {
            counter = 0;
        }
        thisAnchor.href += "&counter=" + counter;
        thisAnchor.innerHTML = lookup(counter);
    }
}
