/**
 * smartCut.js v1.0
 *
 * Julien Roubieu
 * julien@digilab.com.br
 *
 * This script allows you to cut the content of some html elements to a maximum number of lines,
 * just by specifying a specific class.
 *
 * The default class name to use is 'smartCut-x', where x is the maximum number of lines this element should contain.
 * For example, the content of the following div will cut not to occupy more than 3 lines :
 *      <div class="anyclasses smartCut-3" id="myclass">...long content...</div>
 *
 * Important : this class should only be applied to element that contain conly text. If the element contains some html tags,
 * they will be removed and only the text content will remain.
 */

// ============================================================================================
// You can change the value of these variables to configure the behaviour
// ============================================================================================

var MAX_LINES = 5;              /* Maximum number of lines that can be specified after the class name */
var CLASSNAME = "smartCut";     /* Class name to identify elements whose content must be cut. Default is 'smartCut'  */
var ELLIPSIS = "...";           /* Text that will be appended to the content if it is has been cut  */

// ============================================================================================

function smartCutAll() {
    for (var i=1; i<=MAX_LINES; i++) {
        $A(document.getElementsByClassName(CLASSNAME+"-"+i)).each(function (e) {
            smartCutText(e, i);
        });
    }
}

function smartCutText(element, maxLines) {
    var ie = document.all ? true : false;
    element = $(element);
    var text = ie ? element.innerText : element.textContent;
    var testDiv = document.createElement(element.tagName);
    testDiv.className = element.className;
    testDiv.style.visibility = 'hidden';
    element.parentNode.appendChild(testDiv);

    // find height of 1 line
    if (ie) testDiv.innerText = 'a';
    else testDiv.textContent = 'a';
    var lineHeight = testDiv.offsetHeight;
    var cutText = text;
    if (ie) testDiv.innerText = cutText;
    else testDiv.textContent = cutText;
    while(testDiv.offsetHeight > (maxLines * lineHeight)+3) { // +2 because firefox seems to find a slightly bigger offset sometimes
        // cut the end of the text
        cutText = cutText.substring(0, cutText.lastIndexOf(' ')) + ELLIPSIS;
        if (ie) testDiv.innerText = cutText;
        else testDiv.textContent = cutText;
    }
    testDiv.parentNode.removeChild(testDiv);
    if (ie) element.innerText = cutText;
    else element.textContent = cutText;
}


var previousOnload = window.onload;
window.onload = function () { if(previousOnload) previousOnload(); smartCutAll(); }