﻿(function($) {
    $.fn.tabs = function(options) {
        function switchTab(obj, i) {
            obj.find('> ul .tab').removeClass('active');
            obj.find('> ul .tab:eq(' + i + ')').addClass('active');
            obj.find('> .tabContainer').removeClass('active').hide();
            obj.find('> ul .tab:eq(' + i + '), > .tabContainer:eq(' + i + ')').addClass('active').show();
          }
        var defaults = { extraClasses: '', fillHeight: false }
        var options = $.extend(defaults, options);
        return this.each(function(i) {
            var obj = $(this), initialized = obj.data('bonnier.tabs');
            if (!initialized) {
                obj.addClass(options.extraClasses);
                // hook up click event on tabs to switch div on click
                obj.find('> ul .tab').each(function(i) {
                    $(this).bind('click.tabs', { index: i }, function(e) {
                        e.preventDefault();
                        switchTab(obj, e.data.index);
                    });
                });

                // set active state on first one just in case, unless another explicitly has it
                if (obj.find('> ul li.active').length == 0) {
                    obj.children('ul:eq(0) .tab:eq(0), div:eq(0)').addClass('active');
                    switchTab(obj, 0);
                } else {
                obj.find('> ul li.tab').each(function(i) { // switch to the explicitly active tab
                        if ($(this).hasClass('active')) switchTab(obj, i);
                    });
                }

                if (options.fillHeight) {
                    var h = 0;
                    obj.find('> div.tabContainer').each(function() {
                        if ($(this).outerHeight() > h) { h = $(this).outerHeight(); }
                    });
                    obj.find('> div.tabContainer').css({ height: h });
                }
                // initialization done on this one, flag it.
                obj.data('bonnier.tabs', true);
            }
        });
    }
})(jQuery);
