

// Initialize tabs

$(document).ready(function(e){

    // Find all tabbed content
    $(".tabbed-content").each(function(content_i){

        var tc = this;
        tc.contentIndex = -1;
        tc.tabs = [];
        tc.contents = [];

        // Find all tabs for this content
        $(".content-tabs li", this).each(function(tab_i) {
            var tab = this;
        
            // Check for presence of tab and content
            var tab_id = this.id;
            if (tab_id.substr(tab_id.length - 4) != '-tab') return;
            var content_id = tab_id.substring(0, tab_id.length - 4);
            var content = document.getElementById(content_id);
            if (!content) return;

            // Give the tab and content references to each other
            this.content = content;
            content.tab = this;

            // Store references in the tabbed content element
            tc.tabs.push(this);
            tc.contents.push(content);

            // Attach events
            $(tab).bind('click', function(evt){

                // Show or hide content
                for (var i=0, len=tc.tabs.length; i < len; i++) {
                    var this_tab = tc.tabs[i];
                    var is_active = this_tab == tab;
                    $(this_tab)[is_active ? 'addClass' : 'removeClass']('active');
                    $(this_tab.content)[is_active ? 'show' : 'hide']();
                    if (is_active) tc.contentIndex = i;
                }

                // Stop the event
                evt.preventDefault();
                evt.stopPropagation();
            });

        });

        // Next
        tc.next = function() {
            if (tc.contentIndex < tc.tabs.length-1) {
                $(tc.tabs[tc.contentIndex + 1]).trigger('click');
            }
        }
        $('.next-content-tab', tc).each(function(i){
            $(this).bind('click', function(evt) {
                tc.next();
                evt.preventDefault();
                evt.stopPropagation();
            });
        });

        // Previous
        tc.previous = function() {
            if (tc.contentIndex > 0) {
                $(tc.tabs[tc.contentIndex - 1]).trigger('click');
            }
        }
        $('.previous-content-tab', tc).each(function(i){
            $(this).bind('click', function(evt) {
                tc.previous();
                evt.preventDefault();
                evt.stopPropagation();
            });
        });

        // Show the first element
        $(tc.tabs[0]).trigger('click');

    });

});

