/** 
 *
 *  JS line break substringer
 *
 *  Line-breaks string to desired amount of lines based on maxLineWidth
 *  
 *  @author Erling Limm (eibon.dott at gmail.com)
 */

function lineBreak(string, maxLineWidth, numLines, addDots, addBreak, fontFamily, fontSize) {
  var lineStack = [], lines = [];
  var tokens = string.split(" ");
  var helper = getHelperNode(fontFamily, fontSize);
  addDots = addDots || false;
  addBreak = addBreak || false;
  maxLineWidth = maxLineWidth - 10;
  numLines = numLines || 3; // absurd default value

  for (var i = 0; i < tokens.length; i++) {
    helper.innerHTML = lineStack.toString();
    var stringWidth = helper.offsetWidth;

    if (stringWidth < maxLineWidth) {
      lineStack.push(tokens[i]);
    } else {
      i--;
      popStack(lineStack, lines);
    }
  }

  if (lineStack.length > 0)
    popStack(lineStack, lines);

  var result = "";
  for (var i = 0; i < lines.length && i < numLines; i++)
    if (i == lines.length - 1 || i == numLines - 1)
      result += lines[i] + (addDots ? "..." : "");
    else
      result += lines[i] + (addBreak ? "<br />" : " ");

  return result;
}

function popStack(lineStack, lines) {
  var is = lineStack.length;
  var line = "";
  while (is--)
    line += lineStack.shift() + " ";
  lines[lines.length] = line.replace(/^\s+|\s+$/g, '');
}

function getHelperNode(fontFamily, fontSize) {
  var helper = $('line-subst-helper');
  if (!helper) {
    helper = document.createElement('span');
    helper.setAttribute('id', 'line-subst-helper');
    helper.style.position = 'fixed';
    helper.style.top = '-' + (parseInt(fontSize) * 10) + 'px';
    helper.style.left = '0';
    helper.style.fontFamily = fontFamily;
    helper.style.fontSize = parseInt(fontSize) + 3 + 'px'; // A little hack!
    document.body.appendChild(helper);
  }
  return helper;
}
