/*
 * jQuery clip string plugin 0.3
 * 
 * history
 * : 2009-01-19 ver0.3 -Fixed a bug that it doesn't work when width is not given.
 * :                   -New parameter set_title sets the original text into
                        title attribute when it get true.
 * : 2009-01-18 ver0.2 Fixed some inconvinient UIs
 * : 2009-01-17 ver0.1 Initial release
 *
 * http://jamadam.com/blog/
 *
 * Copyright (c) 2008 Sugama Keita
 * 
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
;(function($) {
    
	$.fn.extend({
        
		clipstr: function(args) {
            
            args = 
                $.extend({
                    instead_str : '...',
                    width       : null,
                    set_title   : false
                }, args);
            
            $(this).each(function () {
                
                var attr_name = 
                    (this.innerText) 
                        ? 'innerText'
                        : 
                    (this.textContent)
                        ? 'textContent'
                        : null;
                
                if (! attr_name) {
                    
                    return;
                }
                
                var dummyspan = $(this).wrapInner('<span></span>').find('span');
                var width     = (args.width) ? args.width : $(this).width();
                var org       = dummyspan.attr(attr_name);
                var subnum    = 1;
                var cliped    = false;
                
                while (dummyspan.width() > width) {
                    
                    dummyspan.attr(
                        attr_name,
                        dummyspan.attr(attr_name).slice(0, -1 * subnum)
                            + args.instead_str
                    );
                    
                    subnum = args.instead_str.length + 1;
                    cliped = true;
                }
                
                if (cliped) {
                    
                    // remove dummy span
                    $(this).attr(attr_name, dummyspan.attr(attr_name));
                    
                    if (args.set_title) {
                        
                        this.title = 
                            org.replace(/^[\n\s]+/g, '')
                               .replace(/[\n\s]+$/g, '');
                    }
                }
            });
            
			return this;
		}
    });
})(jQuery);
