(function($) {
    var debug = false;

    // Private Methods
    function log(msg) {
        if (window.console && debug) {
            window.console.log(msg);
        }
    }

    // Verschieden Fehlerbehebungen für IE
    function initIEFix() {
        $.each($.browser, function(i, val) {
            if (i == "msie") {
                // Workaround für abgerundete Buttons
                $(".button-red, .button-grey").append("<span></span>");
                // Workaround für first-child Pseudoselektor im IE6
                $("p:first-child, h2:first-child, h1:first-child").addClass("first-child");
            }
        });
    }

    // Macht Boxen auf- und zuklappbar
    function initCollapsableBoxes(className) {
        // Macht jede Box auf/-zuklappbar
        $(className).each(function() {
            var box = $(this);

            var title = box.children("h2, h3");

            var text = title.text();

            var plus = $("<span></span>").addClass("plus").prependTo(title);
            plus.html(box.children(".content:visible").length > 0 ? "&ndash;" : "+");

            title.click(function() {
                // Klappt den Content der Box ein bzw. aus
                box.children(".content").slideToggle("slow");
                plus.html(plus.html() == "+" ? "&ndash;" : "+");
            });
        });
    }

    // Erzeugt CardView
    function initCardView(className) {
        $(className).each(function() {
            var tabs = $(this).addClass('tabs');
            var tabbar = $("<ul></ul>").addClass("bar clearfix");
            var buttons = [];

            tabs.prepend(tabbar);
            tabs.children(".tab").each(function() {

                var tab = $(this).hide();
                var label = tab.children("h2").attr("title");
                if (!label) {
                    label = tab.children("h2").remove().text();
                }
                var button = $("<a></a>").text(label);

                tab.children("h2").removeAttr("title");

                buttons.push(button);
                tabbar.append($("<li></li>").append(button));

                button.click(function() {
                    $(buttons).each(function() { this.removeClass("selected"); this.parent().removeClass("selected"); });
                    button.parent().addClass("selected");
                    button.addClass("selected");
                    tabs.children('.tab').css('display', 'none');
                    tab.css('display', 'block');
                });

            });
            if (buttons.length < 4) {
                tabbar.addClass("medium");
            }
            buttons[0].click();
        });
    }
    
    // Wird ausgeführt beim start der Seite
    $(function() {
        initCardView(".cardview");
        initCollapsableBoxes(".collapsable");
        initIEFix();
    });

})(jQuery);
