var truncDimention = function ( element, maxWidth, maxHeight, fontSize ) {
	this.element = element;
	this.maxWidth = maxWidth;
	this.maxHeight = maxHeight;
	this.fontSize = fontSize;
	this.element.style.width = this.maxWidth + 'px';
	if ( this.fontSize ) this.element.style.fontSize = this.fontSize + 'px';
	return this;
};
truncDimention.prototype.setValue = function ( str ) {
	this.element.innerHTML = '';
	this.element.title = str;
	this.createRuler();
	var s = this.truncate( str ), c;
	while ( c = this.element.lastChild ) this.element.removeChild(c);
	this.element.innerHTML = s;
	this.ruler.parentNode.removeChild( this.ruler );
};
truncDimention.prototype.createRuler = function () {
	this.ruler = this.element.parentNode.insertBefore( document.createElement('SPAN'), this.element );
	this.ruler.style.visibility = 'hidden';
	this.ruler.style.position = 'absolute';
	this.ruler.style.width = this.maxWidth + 'px';
	if ( this.fontSize ) this.ruler.style.fontSize = this.fontSize + 'px';
};
truncDimention.prototype.getExtent = function ( str ) {
	var c;
	while ( c = this.ruler.lastChild ) this.ruler.removeChild(c);
	this.ruler.innerHTML = str.replace( this.AT, '<br />' );
	var dim = [ this.ruler.offsetWidth, this.ruler.offsetHeight ];
	while ( c = this.ruler.lastChild ) this.ruler.removeChild(c);
	return dim;
};
truncDimention.prototype.truncate = function ( str ) {
	if ( str.length == 0 ) return '';
	var dim = this.getExtent( str.replace( this.BR, '@' ) );
	if ( dim[0] <= this.maxWidth && dim[1] <= this.maxHeight ) return str;
	var str2 = str.replace( this.BR, '@' );
	for ( var i = str2.length - 1; i >= 1; --i ) {
		var s = str2.slice(0,i) + '...';
		var dim = this.getExtent(s);
		if ( dim[0] <= this.maxWidth && dim[1] <= this.maxHeight ) return s.replace( this.AT, '<br />' );
	}
	return '';
};
truncDimention.prototype.BR = /<br[^>]*>/ig;
truncDimention.prototype.AT = /@/g;

