﻿$(document).ready(function () {
    $.fn.fitContent = function () {

        var totalWidth = $(this).width();
        var $tabs = $(this).children();
        var w_ideal = Math.floor(totalWidth / $tabs.length);
        var usedWidth = 0;
        var toSmallCount = 0;

        $tabs.each(function () {
            var ow = $(this).outerWidth();
            if (ow > w_ideal) {
                usedWidth += ow
            } else toSmallCount += 1;
        });

        var w = Math.floor((totalWidth - usedWidth) / toSmallCount);

        if (w > 0) {
            $tabs.each(function () {
                var ow = $(this).outerWidth();
                if (ow <= w_ideal) {
                    $(this).width(w);
                    usedWidth += w
                };

            });
        };

        var spare = (totalWidth - usedWidth);
        if (spare > 0) {
            $tabs.each(function () {
                if (spare > 0) {
                    $(this).width($(this).width() + 1);
                    spare -= 1;
                };
            });
        };

        $tabs.each(function () {
            var w = $(this).width();
            $(this).children('div').width(w);
        });

    };
});
