/*
Plugin Equal Horizontal Distribution
*/
(function( $ ){
	$.fn.equalDistribution = function (options) {
		var settings  = {  
			childElement: "li",  
			marginSide: "margin-right",
            elementsPerRow: null
		};
		
		var options = $.extend(settings, options);
	
		return this.each (function () {
			var dElement = $(this);
			var dElementChild = $(this).children(options.childElement);
			var dWidth = dElement.width();
			var dChildWidth = dElementChild.width();
			var dChildNumber;
			if (!settings.elementsPerRow) {
                dChildNumber = dElementChild.length;
            } else {
                dChildNumber = settings.elementsPerRow;
            }
			var defineFirstOrLast;
			if (options.marginSide == "margin-right"){
				defineFirstOrLast = ":last-child";
			} else {
				defineFirstOrLast = ":first-child";
			}
			if (settings.elementsPerRow) {
                var rowElements = ":nth-child(" + settings.elementsPerRow + "n)";
            }
			var dSpaceLeft = dWidth - (dChildNumber * dChildWidth);
			var dMargin = Math.floor(dSpaceLeft / (dChildNumber - 1));
			
			if (!rowElements) {
                dElement.find(options.childElement + ":not(" + defineFirstOrLast + ")").css(options.marginSide, dMargin);

            } else {
                dElement.find(options.childElement + ":not(" + defineFirstOrLast + ", " + rowElements + ")").css(options.marginSide, dMargin);
            }
			
			var dElementPadding = dWidth - ((dChildNumber*dChildWidth)+(dChildNumber*dMargin));
			var dChildRealWidth = 0;
			if (!rowElements) {
                dElementChild.each(function () {
                    dChildRealWidth += parseInt($(this).outerWidth(true));

                });

            } else {
                var count = 1;
                dElementChild.each(function () {
                    if (count <= settings.elementsPerRow) {
                        dChildRealWidth += parseInt($(this).outerWidth(true));
                        count++;
                    }
                });
            }
			if (dChildRealWidth < dElement.width()){
				var widthDiff = dElement.width() - dChildRealWidth;
				var widthCompensation = Math.floor(widthDiff / 2);			
				dElement.css({
					"width": dElement.width()-widthCompensation,
					"padding-left":widthCompensation
				})
			}
			
			
			// IE6 double margin bug
			/*
			if (dElementChild.css("float") === "left" || dElementChild.css("float") === "right") {
			  dElementChild.css("display", "inline");
			}
			*/
		});
	};
})( jQuery );
