﻿
(function($) {
    $.fn.extend({
        tabify: function() {

            return this.each(function() {

                //Creating a reference to the object
                var obj = $(this);

                //Create a reference for all headings and it's content using .next()
                //Remember to pass the object reference "obj" into the identifier.
                var headings = $('h4', obj);
                var tabContent = $('h4', obj).next();

                //We wan't to hide the headings and the content
                headings.hide();
                tabContent.hide();
                
                //But we want to show content of the first tab since it's selected by default. 
                tabContent.eq(0).show();

                //Prepend the object with the tab container (ul).
                obj.prepend('<ul class="tabs"><\/ul>');

                //For every heading create an item (<li>)
                for (var i = 0; i < headings.length; i++) {

                    var sel;
                    //The first object is selected by default so add class="sel" to it
                    if (i == 0) {
                        sel = ' class="sel"';
                    }
                    //Else set it to empty
                    else {
                        sel = "";
                    }
                    //the label for the tab should equal the text of the heading
                    var label = headings.eq(i).text();
                    $("ul.tabs", obj).append('<li' + sel + '>' + label + '<\/li>');
                }

                //Create a reference to the tabs for each obj
                var tabs = $("ul.tabs li", obj);

                tabs.click(function() {

                    //When a tab is clicked "de-activate" the old one
                    $("ul.tabs li.sel", obj).removeClass("sel");
                    tabContent.hide();
                    $(this).addClass("sel");

                    //And display the clicked tab
                    var current = tabs.index($(this));
                    tabContent.eq(current).show();
                });
            });
        }
    });
})(jQuery);

