/*
 * jQuery Ellipsis plugin 1.0
 *
 * Copyright (c) 2010 PFZ
 */
;(function($) {
    $.fn.ellipsis = function( options ) {
        this.each(function() {
            if ( $( this ).css( 'overflow' ) != 'hidden' ) {
                // no overflow: hidden; thus nothing to do
                return;
            }
            if ( this.scrollWidth <= this.clientWidth ) {
                // nothing to do, text is nice within the limits
                return;
            }
            var referenceElement = this;
            var textNodeParent = this;

            var childCollection = $( this ).children( );
            // make sure that it is the only child element
            if ( childCollection.length == 1 ) {
                textNodeParent = childCollection[0];
            }
            var textNodes = $( textNodeParent ).contents().filter(
                function() {
                    return this.nodeType == 3;
                }
            );
            // there can be comment nodes (nodeType 8). They must be ignored.
            var allButCommentNodes = $( textNodeParent ).contents().filter( function() { return this.nodeType != 8; } );
            if ( allButCommentNodes.length == textNodes.length ) {
                textNodes.each(
                    function( ) {
                        this.nodeValue = $.trim( this.nodeValue ).substr( 0, 100 );
                        if ( this.nodeValue.length ) {
                            var maxIterations = 100;
                            while( referenceElement.scrollWidth > referenceElement.clientWidth ) {
                                this.nodeValue = this.nodeValue.substr( 0, this.nodeValue.length - 4 ) + '...';
                                maxIterations--;
                                if ( !maxIterations ) {
                                    break;
                                }
                            }
                        }
                        return;
                    }
                );
            }
        });

        return this;
    };
})(jQuery);
