(function(window) {
  'use strict';

  function limitTextLines(container, limit, btnClass) {
    this.button = false;
    this.container = container;
    this.viewed = false;

    this.container.style.lineHeight = '1.3em';

    this.limitLines(limit, btnClass);

    window.onresize = function() {
      this.limitLines(limit, btnClass);
    }.bind(this);
  }

  limitTextLines.prototype.limitLines = function(limit, btnClass) {
    if (this.viewed) return;

    var style = window.getComputedStyle(this.container),
      lineHeight = parseInt(style.getPropertyValue('line-height').replace('px', '')),
      paddingTop = parseInt(style.getPropertyValue('padding-top').replace('px', '')),
      paddingBottom = parseInt(style.getPropertyValue('padding-bottom').replace('px', '')),
      children = this.container.children;

    if (children.length > 1) {
      console.error('o container deve ter apenas 1 tag filha');
      return;
    } else if (children.length == 0) {
      console.error('o container deve ter pelo menos 1 tag filha');
      return;
    }

    var lines = Math.ceil((children[0].offsetHeight - paddingTop - paddingBottom) / lineHeight);

    if (lines > limit) {
      this.container.style.height = limit * lineHeight + paddingTop + paddingBottom + 'px';
      this.container.style.overflow = 'hidden';

      if (!this.button) {
        var button = document.createElement('a');
        button.textContent = 'Ver mais';
        button.classList.add.apply(
          button.classList,
          btnClass
            .trim()
            .replace(/[\s]+/g, ' ')
            .split(' ')
        );
        button.onclick = function(e) {
          e.preventDefault();
          button.parentNode.removeChild(button);
          this.container.removeAttribute('style');
          this.viewed = true;
        }.bind(this);

        this.container.parentNode.insertBefore(button, this.container.nextElementSibling);
        this.button = button;
      }
    } else {
      this.container.removeAttribute('style');
      if (this.button) {
        this.button.parentNode.removeChild(this.button);
        this.button = false;
      }
    }
  };
  window.limitTextLines = limitTextLines;
})(window);
