(function($){

	$.fn.autoWidth = function(){

		var totalWidth = 0;
		var totalFixedWidth = 0;
		var newTotalWidth = 0;
		var reste = 0;
		
		//fixe les enfants en taille fixe
		//calcul la largeur des enfants
		this.children().each(
			function(){

				var mFloat = $(this).css('float');
				$(this).css({float:"none"});

				if($(this).outerWidth(true) != $(this).parent().width() ){
					$(this).addClass('fixed');
					totalFixedWidth += $(this).outerWidth(true);
				}

				$(this).css({float: mFloat });
				totalWidth += $(this).outerWidth(true);
			}
		);

		//si total taille enfant superieur conteneur
		if( totalWidth > this.width() )
		{	
					this.children().each(
						function(){

							if( $(this).hasClass("fixed") ){
								$(this).removeClass('fixed');
							}else{

								var childrenWidth = $(this).children().width(); 
								var newWidth = Math.floor( ($(this).outerWidth(true) * ($(this).parent().width() - totalFixedWidth) / (totalWidth - totalFixedWidth) )  - ( $(this).outerWidth(true) - $(this).width() ));
								if(newWidth < childrenWidth) $(this).children().css({paddingTop:"5px", paddingBottom:"6px"}); 
								$(this).css({width: newWidth + "px"});

							}

							$(this).children().css({
								width:"100%",
								height:"100%",
								textAlign:"center",
								display:"block"
							});

							newTotalWidth += $(this).outerWidth(true);

						}
					);

		}else{
					var numChildrenFixed = this.children(".fixed").size();
					var numChildren = this.children().size();

					this.children().each(
						function(){
							if( $(this).hasClass("fixed") ){
								$(this).removeClass('fixed');
							}else{
								var newWidth = Math.floor( ($(this).parent().width() - totalWidth) / (numChildren - numChildrenFixed) ) - ( $(this).outerWidth(true) - $(this).width() ) + $(this).width();
								$(this).css({width: newWidth + "px"});
							}

							$(this).children().css({
								width:"100%",
								height:"100%",
								textAlign:"center",
								display:"block"
							});

							newTotalWidth += $(this).outerWidth(true);
						}
					);

					
		}

		if( newTotalWidth < this.width() ){
			var newWidth = this.children(":last").width() + this.width() - newTotalWidth;
			this.children(":last").css({width: newWidth + "px"});
		}

		

	}

})(jQuery);
