/*
 * trueWidth Plugin for jQuery JavaScript Library
 * http://hackthetruth.org/
 *
 * Copyright (c) 2009 - 2011 Dakota Schneider
 * Dual licensed under the MIT and GPL licenses.
 *  - http://www.opensource.org/licenses/mit-license.php
 *  - http://www.gnu.org/copyleft/gpl.html
 *
 * Inspired by this question and the answers it spawned:
 * http://stackoverflow.com/questions/4755593/
 *
 * Author: Dakota A. Schneider
 * Version: 1.0.0
 * Date: 21st July 2011
 *
 * .trueWidthWithStyle() requires jquery.getStyleObject plugin
 */

(function($){
    $.fn.trueWidth = function() {
        var tempobj = this // starting with truncated text div container
            .clone().contents() // duplicate the text
            .wrap('<div id="trueWidthTempObj"/>') // wrap it in a container
            .parent().appendTo('body') // add this to the dom
            .css('margin-left','-1000px'); // but put it far off-screen
        var result = tempobj.width(); // measure it
        tempobj.remove(); // clean up
        return result;
    };
    
    
    $.fn.trueWidthWithStyle = function() {
        // all CSS values which have an effect on the length of a line of text
        var widthStyles = [
            'font-family','font-size','font-weight','font-style',
            'text-transform','letter-spacing','word-spacing'
        ];
        var widthStyleValues = {};
        var orig = this;
        
        // get the relevant CSS rules from the original, to apply to the ruler
        $.each(widthStyles, function(index, value) {
            widthStyleValues[value] = orig.css(value);
        });
        
        var tempobj = this // starting with truncated text div container
            .clone().contents() // duplicate the text
            .wrapAll('<p id="trueWidthTempObj"></p>') // wrap it in a container
            .parent().appendTo('body') // add this to the dom
            .css(widthStyleValues) // and style it to match the text of the source
            .css('margin-left','-1000px') // but put it far off-screen
            .css('display','inline') // and make sure it is only as wide as the content
            .children().css('display','inline'); // and do the same for all the child elements

        var result = $('#trueWidthTempObj').width(); // get the value

        $('#trueWidthTempObj').remove(); // clean up
        
        return parseInt(result); // send it back
    };
})(jQuery);
