
/* Setup
----------------------------------------------------------------------------*/

var Tabber = function (root) {
    if (window == this)
        return new Tabber(root);
    
    this.init(root);
};

Tabber.prototype = {
    init: function (root) {
        var self = this;
        
        this.root = $(root);
        this.triggers = $("<ul/>").addClass("triggers");
        this.activeTabIndex = -1;
        
        var triggers = this.triggers;
        var index = 0;
        
        this.root
        .find("h3")
            .each(function () {            
                $("<li><a></a></li>")
                .appendTo(triggers)
                .find("a")
                    .html($(this).html())
                    .attr({
                        href: "#",
                        targetTabIndex: index++
                    })
                    .click(function () {
                        self.switchTab($(this).attr("targetTabIndex"));
                        return false;
                    });
            })
            .end()
        .prepend(this.triggers)
        .find("li:first()").addClass("first").end()
        .find("li:last()").addClass("last").end()
        .children("div.tab").hide();
        
        var initialIndex = 0;
        if (location.hash) {
            var id = location.hash;
            this.root.children("div.tab").each(function (i) {
                if ($(this).is(id)) {
                    initialIndex = i;
                    return false;
                }
            });
        }
        
        this.switchTab(initialIndex);
    },
    
    switchTab: function (num) {
        var num = num || 0;
        var old = this.activeTabIndex;
        
        if (num == old) return;
        
        this.activeTabIndex = num;
        
        this.triggers
        .children("li.active")
            .removeClass("active")
            .end()
        .find("li:eq("+ num +")")
            .addClass("active");
        
        var newContainer = this.root.children("div.tab:eq("+ num +")");
        var oldContainer = this.root.children("div.tab:eq("+ old +")");
        var newHeight = 64 + newContainer.height();
        var oldHeight = 64 + oldContainer.height();
        
        var id = newContainer.attr("id");
        newContainer.attr("id", "");
        location.hash = id;
        
        var root = this.root;
        if (oldHeight > newHeight) {
            oldContainer.fadeOut("slow", function () {
                root.animate({height: newHeight});
            });
        } else {
            oldContainer.fadeOut("slow");
            this.root.animate({height: newHeight});
        }
        newContainer.fadeIn("slow").attr("id", id);
    }
};

$(function () {
    $(".tabber").each(function () {
        new Tabber(this);
    });
    
    $(".tabber a").css("outline", "none");
});
