/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 9/11/2008
 * @author Ariel Flesler
 * @version 1.4
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(h){var m=h.scrollTo=function(b,c,g){h(window).scrollTo(b,c,g)};m.defaults={axis:'y',duration:1};m.window=function(b){return h(window).scrollable()};h.fn.scrollable=function(){return this.map(function(){var b=this.parentWindow||this.defaultView,c=this.nodeName=='#document'?b.frameElement||b:this,g=c.contentDocument||(c.contentWindow||c).document,i=c.setInterval;return c.nodeName=='IFRAME'||i&&h.browser.safari?g.body:i?g.documentElement:this})};h.fn.scrollTo=function(r,j,a){if(typeof j=='object'){a=j;j=0}if(typeof a=='function')a={onAfter:a};a=h.extend({},m.defaults,a);j=j||a.speed||a.duration;a.queue=a.queue&&a.axis.length>1;if(a.queue)j/=2;a.offset=n(a.offset);a.over=n(a.over);return this.scrollable().each(function(){var k=this,o=h(k),d=r,l,e={},p=o.is('html,body');switch(typeof d){case'number':case'string':if(/^([+-]=)?\d+(px)?$/.test(d)){d=n(d);break}d=h(d,this);case'object':if(d.is||d.style)l=(d=h(d)).offset()}h.each(a.axis.split(''),function(b,c){var g=c=='x'?'Left':'Top',i=g.toLowerCase(),f='scroll'+g,s=k[f],t=c=='x'?'Width':'Height',v=t.toLowerCase();if(l){e[f]=l[i]+(p?0:s-o.offset()[i]);if(a.margin){e[f]-=parseInt(d.css('margin'+g))||0;e[f]-=parseInt(d.css('border'+g+'Width'))||0}e[f]+=a.offset[i]||0;if(a.over[i])e[f]+=d[v]()*a.over[i]}else e[f]=d[i];if(/^\d+$/.test(e[f]))e[f]=e[f]<=0?0:Math.min(e[f],u(t));if(!b&&a.queue){if(s!=e[f])q(a.onAfterFirst);delete e[f]}});q(a.onAfter);function q(b){o.animate(e,j,a.easing,b&&function(){b.call(this,r,a)})};function u(b){var c='scroll'+b,g=k.ownerDocument;return p?Math.max(g.documentElement[c],g.body[c]):k[c]}}).end()};function n(b){return typeof b=='object'?b:{top:b,left:b}}})(jQuery);

// Jonas Raoni Soares Silva
// http://jsfromhell.com/string/rot13

String.prototype.rot13 = function(){
    return this.replace(/[a-zA-Z]/g, function(c){
        return String.fromCharCode((c <= "Z" ? 90 : 122) >= (c = c.charCodeAt(0) + 13) ? c : c - 26);
    });
};


// Marcin G.
function generate_comment_badges()
{
    // Iterate through every comment counter
    $(".comment-num").each(function (){
        var val = parseInt($(this).text());
        if( val > 9 ){
            var badge = document.createElement("li");
            if( val > 49 )
                $(badge).addClass("t-m1");
            else if(val >= 19)
                $(badge).addClass("t-m2");
            else
                $(badge).addClass("t-m3");
            var post = $(this).parents().filter("div.post");
            $("> .post-info > .icon", post).children("ul").append(badge);
        }
    })
}

function generate_badge_info()
{
    // Informative
    $(".t-artykul").attr("title",   "Artykuł‚ lub inne ustrojstwa.");
    $(".t-ascii").attr("title",     "Post zawiera ASCII-Art lub informacje z nim związane.");
    $(".t-duszki").attr("title",    "Duszki inside");
    $(".t-mysli").attr("title",     "Przemyślenia własne.");
    $(".t-skryba").attr("title",    "Uwaga: zapędy grafomańskie.");
    $(".t-mini").attr("title",      "Zupełnie nieistotny tekst, swoim bytem przypominający dziecię minibloga.");
    $(".t-photo").attr("title",      "Nieruchomy obrazek.");
    // "Awards"
    $(".t-m3").attr("title",    "Wpis ma 10 lub więcej komentarzy. Uwaga: możliwa obecność trolli.");
    $(".t-m2").attr("title",    "Srebrny wpis: 20 lub więcej komentarzy. Uwaga: możliwa obecność spamerów.");
    $(".t-m1").attr("title",    "Złoty wpis: 50 lub więcej komentarzy. Uwaga: trolle i spamerzy gwarantowani.");
}


function on_spoiler_clicked()
{
    var rot13ed = $(this).text().rot13();
    $(this).text(rot13ed);
    if($(this).hasClass('spoiler'))
        $(this).removeClass('spoiler').addClass('spoilered');
    else
        $(this).removeClass('spoilered').addClass('spoiler');
}

function prepareSpoilers()
{
    $(".spoiler").click(on_spoiler_clicked)
        .attr("title",  "Click here to code/decode spoiler");
}

// modified http://www.jogger.pl/t/js/jogger.home.js
function generate_easy_navigation()
{
    var posts = $('div.post');
    $.each(posts, function(i){
        var next = i + 1;
        if (next < posts.size()){
            var title = "Next: " + $(posts).eq(next).find("h2.title").text();
            $(this).find('div.rightbox').append('<a href="#" class="nextpost">next &#x21B7;</a>')
                .find(".nextpost")
                .bind('click', function(e) {
                    $.scrollTo($(posts).eq(next), {speed: 1000})
                    e.preventDefault();
                })
                .attr('title', title);
        }
    });
}

function prepare_post_info()
{
    $("div.post-info > div.rightbox").append('<a class="showinfo">info &#x2199;</a>')
        .find(".showinfo").click(function(){
            $(this).parents("div.post").find("div.hide").toggle();
        });
}

function prepare_top_menu()
{
    $("#frendzel > a").click( function(){
        $("#top > .wrapper > .content").slideToggle("slow");
        $("#top").find(".wrapper").toggleClass('pad');
    });
}

function new_archive_tree(i)
{
    $(this).find("span").remove();
    var year = $(this).text().substr(-4);
    var month = $(this).text().substr(1, 3);
    if(cYear != year){ // time to add new Tree
        if(cTree){ // add existing tree
            var li = $(document.createElement("li")).append(cYear);
            li.append(cTree);
            newArch.append(li);
        }
        cTree = $(document.createElement("ul"));
        cYear = year;
    }
    var cur = $(document.createElement("li"));
    cur.append("<a href='#'>"+month+"</a>")
    cTree.append(cur);

    // is the last one?
    if ($(archie).size() == i+1){
        var li = $(document.createElement("li")).append(cYear);
        li.append(cTree);
        newArch.append(li);
    }
    return $(newArch);
}


roman = ["I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI", "XII", ""];
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
msce = ["Styczeń", "Luty", "Marzec", "Kwiecień", "Maj", "Czerwiec", "Lipiec", "Sierpień",
        "Wrzesień", "Październik", "Listopad", "Grudzień", ""];

function month_pos(month)
{
    for(x in months){
        if(months[x] == month)
            return x;
    }
    return 12;
}

function replace_archive()
{
    var newArch = $(document.createElement("ul"));
    newArch.addClass("js");
    var cYear = "";
    var cTree = null;
    var archie = $("#archiwum").find("ul.old").children().clone();
    // Prepare new archive tree
    archie.each(function(index){
        var counter = $(this).find("span").remove().text();
        var year = $(this).text().substr(-4);
        var month = $(this).text().substr(1, 3);
        var href = $(this).find("a").attr('href');
        if(cYear != year){
            // Processing new year: adding existing cTree to structure
            if(cTree != null){
                var li = $(document.createElement("li")).append(cYear+":");
                li.append(cTree);
                newArch.append(li);
            }
            cYear = year;
            cTree = $(document.createElement("ul"));
            for(i=0; i<12; i++){
                var li = $(document.createElement("li")).html(roman[i])
                    .addClass('inactive')
                    .attr('title', 'Brak aktywności dla: '+msce[i]+', '+cYear+'.');
                cTree.append(li);
            }
        }

        var pos = month_pos(month);
        var elt = cTree.children().get(pos);
        var a = $(document.createElement("a")).html(roman[pos]).attr('href', href)
                .attr('title', 'Archiwum, rok '+cYear+', miesiąc '+msce[pos]+
                '. Dodano wpisów: '+ counter+'.');
        
        $(elt).removeClass("inactive").html(a);

        // last one should not be forgotten
        if ($(archie).size() == index+1){
            var li = $(document.createElement("li")).append("<span class='year'>"+cYear+"</span>:");
            li.append(cTree);
            newArch.append(li);
        }
    });
    //$("#debug").append(newArch);
    // Hide existing one
    var old = $("#archiwum").find(".old");
    $("#archiwum").append(newArch);
    old.hide();

    // And add style switcher
    $("#archiwum").find("h3").attr('title', 'Kliknij, aby zmienić styl archiwum.')
     .click(function(){
        $("#archiwum").find(".old").toggle();
        $("#archiwum").find(".js").toggle();
    });
}

// When DOM is ready:
jQuery(function($){
    generate_comment_badges();
    generate_badge_info();
    generate_easy_navigation();
    prepareSpoilers();
    prepare_post_info();
    prepare_top_menu();
    replace_archive();
});

