/**
 * Create an elipses of html content
 *
 * @copyright 2010 Squiz Pty Ltd (ABN 77 084 670 600)
 * @license   GNU General Public License v.2
 * @version   SVN: $Id: jquery-ellipses.js 492 2010-07-02 01:47:36Z abarnes $
 * @link
 */
 
 
// Start jQuery closure
(function($) { 


    // Start jQuery ellipses plugin
    jQuery.fn.ellipses = function(options)
    {
        
        var defaults = {
            maxChars: 255,
            appendString: "...",
            chopString: false
        };
        
        var opt = $.extend({},defaults,options);
    
        return $(this).each(function() {
            var $this = $(this);
            var origHTML = $this.text();
            if (origHTML.length > opt.maxChars) {
                var newHTML = $.fn.ellipses.trim(origHTML,opt.maxChars,opt.appendString,opt.chopString);
                $this.html(newHTML);
            }
        }); 
        
    }; // End ellipses
    
    /**
     * Trim a string
     *
     * @param {String}      html            String to trim
     * @param {String}      maxChars        The maximum number of character to allow
     *                                      in the output. This result is maxChars - appendString.length
     * @param {String}      appendString    The string to append to the content
     * @param {Boolean}     chopString      Chops the string at hard character limit if true
     *                                      If false, chops the string and the last word before the limit
     */
    jQuery.fn.ellipses.trim = function(html,maxChars,appendString,chopString)
    {
        
        var words = html.split(" ");
        var numWords = words.length;
        var appendLength = appendString.length;
        var newHTML = '';
        
        if (chopString) {
            newHTML = html.substring(0,maxChars-appendLength);
        } else {
            newHTML = "";
            var totalLength = 0;
            for (var i = 0; i < numWords; i++) {
                var thisWordLength = words[i].length;
                totalLength += thisWordLength + 1;
                if ((totalLength + appendLength) <= maxChars) {
                    newHTML += words[i];
                }
                if (typeof(words[i + 1]) === "string") {
                    var nextLength = totalLength + words[i + 1].length + 1;
                    if ((nextLength + appendLength) <= maxChars) {
                        newHTML += " ";
                    }
                }
            }
        }
    
        newHTML += appendString;    
        return newHTML;
        
    }; // End ellipses trim

})(jQuery); // End jQuery closure

