var Ellipsis = Class.create({
  
	initialize: function(element) {
		this.element = element;
		this.text = element.innerHTML;

	}, ltrim: function(str, chars) {
		return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
	}, rtrim: function(str, chars) {
		return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
	}, trim: function(str) {
		return this.ltrim(this.rtrim(str, "\\s|\t|\n|\r|\0|\x0B"), "\\s|\t|\n|\r|\0|\x0B");
	}, addAsManyCharsAsWeCan: function(text /*content*/, lastWord, spanEl/*outer element*/, h /*height*/, w /*weight*/, 
			end /*end word*/) {
		var i = text.length;
	    var j = 0;
		while (spanEl.getHeight() <= h && spanEl.getWidth() <= w && j < lastWord.length) {
			text = text + lastWord.charAt(j++);
			this.textContainerElement.innerHTML = text + end;
		}
		text = text.substr(0, text.length - 1);
		this.textContainerElement.innerHTML = this.trim(text) + end;
	},
	truncate: function(suffix) {
		var h = this.element.getHeight();
		var w = this.element.getWidth();
		
		var text = this.element.innerHTML;
		// This is an IE8 hack. It has no sense! But it works. Hate me - Adriano
	    this.element.innerHTML = '<span style="border:0px transparent solid">' + text + '</span>';
	    
		this.textContainerElement = this.element.down(); 

	    this.chopp(this.textContainerElement, h, w, text, suffix, suffix);
	},
	truncateNoEndChars: function(suffix) {
		this.textContainerElement = this.element;
		var spanEl = this.textContainerElement.up();

		var enclosingDiv = spanEl.up();
		while (enclosingDiv.tagName != "DIV") {
			enclosingDiv = enclosingDiv.up();
		}
		var h = enclosingDiv.getHeight();
		var w = enclosingDiv.getWidth();
		
		var text = this.trim(this.textContainerElement.innerHTML);
        this.textContainerElement.innerHTML = text;
		this.chopp(spanEl, h, w, text, suffix, suffix);
	},
	chopp: function(spanEl, h, w, text, end, suffix)
	{
		var lastWord = '';
		while (spanEl.getHeight() > h || spanEl.getWidth() > w) {
			var i = text.lastIndexOf(' ');
			if (i > 0) {
				lastWord = text.substr(i);
				text = text.substr(0, i);
				this.textContainerElement.innerHTML = text +  suffix;
			} else {
				lastWord = text;
				text = '';
				this.textContainerElement.innerHTML = '';
				break;
			}
		}
		if (lastWord.length > 2) {
			this.addAsManyCharsAsWeCan(text, lastWord, spanEl, h, w, end);
		}
	}
});

