(function($) {
	function collectionEllipsis(collection){//bypeb: optimization
		var $el,
			oldClasses='',
			newClasses,
			originalText,
			text,
			i=collection.length,
			t;

		while(i--){
			
			$el = collection[i].$;
			originalText = collection[i].originalText;
			
			if ((newClasses = $el.attr('class')) !== oldClasses){
				t && t.remove();
				oldClasses = newClasses;
				t = $($el.get([0]).cloneNode(true)).hide().css({
					'position': 'absolute',
					'width': 'auto',
					'overflow': 'visible',
					'max-width': 'inherit'
				});
				$el.after(t);
			}

			text = originalText;
			t.html(text);
			
			while(text.length > 0 && t.width() > $el.width()){
				text = text.substr(0, text.length - 1);
				t.html(text + "...");
			}
			$el.html(t.html());
		}
		t && t.remove();
	}

	$.fn.ellipsis = function(enableUpdating){
		var s = document.documentElement.style,
			$el,
			_collection,
			_L = this.length
			i = _L;
		if (!('textOverflow' in s || 'OTextOverflow' in s)) {
			_collection = [];
			while(i--) {
				$el = $(this[i]);

				_collection[i] = {
					$: $el,
					originalText: this[i].innerHTML,
					oldW: $el.width()
				}
			}
			collectionEllipsis(_collection);

			if(enableUpdating === true){
				setInterval(function(){
					var i = _L,
						collection = _collection,
						element,
						auxCollection = [],
						elW;
					while(i--){
						element = collection[i];
						elW = element.$.width();
						if(elW !== element.oldW){
							element.oldW = elW;
							element.$.html(element.originalText);
							auxCollection.push(element);
						}
					}
					if (auxCollection.length){collectionEllipsis(auxCollection);}

				}, 200);
			}
		}
		return this;
	};
})(jQuery);
