

$.fn.equalWidths = function(options) {
	
	var defaults = {
		px: true,
		includeElement: '',
		listWidth: 1000,
		justify: false,
		fillerClass: ''
	};
		
	var o = $.extend(defaults, options);
	
	$(this).each(function(){
		
		bumperWidth = 0;
		kerning = 0;
		totalWidth = 0;
		currentWidest = 0;
		
		$(this).children().each(function(i){
			//var thisW = parseInt($(this).width()) - ( parseInt($(this).outerWidth()) - parseInt($(this).width()) );
			var thisW = parseInt($(this).outerWidth());
			
			if (thisW > currentWidest) {
				currentWidest = thisW;
				// set kerning (if border or margins exist, need to remove their widths later
				kerning = ( parseInt($(this).outerWidth()) - parseInt($(this).width()) );
			}
			
		});
	
		
		if (o.justify) {
			
			fitToWidth = parseInt($(this).width());
			itemCount = ($(this).children().length);
			fitCount = (Math.floor(fitToWidth/currentWidest));
			rowCount = (Math.ceil(itemCount/fitCount));
			
			if (rowCount > 1) {
				currentWidest = (Math.floor(fitToWidth/fitCount));
				fillerCount = ((fitCount * rowCount) % itemCount);
				fillerWidth = (fillerCount * currentWidest);
				bumperWidth = (fitToWidth - (fitCount * currentWidest));
			
				
				if(o.fillerClass.length) {
					var filler = $('<li />')
						//.attr("id", $('> .nav',el).attr('id') + '_list')
						.addClass(o.fillerClass)
						//.html('<span class="subNavTitle">&nbsp;</span>')
						//.html(o.fillerContent)
						.css({ width: fillerWidth + bumperWidth });
				}
					
			} else {
				
				if(o.fillerClass.length) {
					fillerCount = (fitCount - itemCount);
					fillerWidth = (fitToWidth-(itemCount * currentWidest));
					
					var filler = $('<li />')
						.addClass(o.fillerClass)
						.css({ width: fillerWidth });
				} else {
					currentWidest = (Math.floor(fitToWidth/itemCount));
					fitWidth = currentWidest * itemCount;
				}
			}
		}
		
		if (!o.px || !Number.prototype.pxToEm) currentWidest = currentWidest.pxToEm({scope:$(this).children()}); //use ems unless px is specified
		
		//remove kerning (set above)
		currentWidest = currentWidest - kerning;
		
		// for ie6, set Width since min-Width isn't supported
		if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({'width': currentWidest}); }
		$(this).children().css({'min-width': currentWidest});
		
		if (bumperWidth > 0 ) {
			for (i=1; i<rowCount; i++) {
				$('> li:nth-child(' + i * fitCount + ')',this).css({'min-width': currentWidest + bumperWidth});
				//$('> li:nth-child(' + i * (fitCount + 1) + ')',this).css({'margin-top': '5px'});
			}
		}
		
		if (o.includeElement.length) $(o.includeElement, this).css({'min-width': currentWidest});
		
		if (typeof filler != 'undefiend') $(this).append(filler);
		
		
	});
	return this;
};

