var CopyNotification = (function() {

'use strict';

function CopyNotification(message) {
  this.message = message;
  this.copyInput = $('.copyInput');
}

CopyNotification.prototype.render = function() {
  var copyNotification = '<div class="copyInput__notification">' + this.message + '</div>';
  return copyNotification;
};

CopyNotification.prototype.animate = function() {
  var animationEnd = 'webkitAnimationEnd oanimationend oAnimationEnd msAnimationEnd animationend';
  var notification = this.copyInput.find('.copyInput__notification');
  var fired = false;
  notification.addClass('copyInput__notification--animating');

  notification.one(animationEnd, function(e) {
    if (!fired) {
      fired = true;
      notification.remove();
    }
  });
};

return CopyNotification;

})();

var CopyInput = (function() {

function CopyInput(element) {
  this.element = element;
  this.copyButton = this.element.find('.copyInput__button');
  this.copyInputText = this.element.find('.copyInput__input');
  this.copyInputClass = '.' + this.element.attr('class');
  this.copyInputTextClass = this.copyInputText.attr('class');
  this.bindEvents();
}

CopyInput.prototype.bindEvents = function() {
  var self = this;
  this.copyButton.on('click', function(e) {
    e.preventDefault();
    e.stopPropagation();
    var copyTextParent = self.getClosest(this, self.copyInputClass);
    var copyText = self.getChild(copyTextParent, self.copyInputTextClass);
    self.copyToClipboard(copyText);
  });

  this.copyInputText.focus(function() {
    $(this).select();
  });
};

CopyInput.prototype.getClosest = function(elem, selector) {
  var firstChar = selector.charAt(0);

  // Get closest match
  for (; elem && elem !== document; elem = elem.parentNode) {
    if (firstChar === '.' ) {
      if (elem.classList.contains(selector.substr(1))) {
        return elem;
      }
    }
  }
  return false;
};

CopyInput.prototype.getChild = function(elem, selector) {
  for (var i = 0; i < elem.childNodes.length; i++) {
    if (elem.childNodes[i].className == selector) {
      return elem.childNodes[i];
    }
  }
};

CopyInput.prototype.copyToClipboard = function(copyText) {
  window.getSelection().removeAllRanges();
  var range = document.createRange();
  range.selectNode(copyText);
  window.getSelection().addRange(range);

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'copied' : 'not copied';
    var copyNotification = new CopyNotification(msg);
    $('.copyInput__notification').remove();

    this.copyButton.append(copyNotification.render());
    copyNotification.animate();

  } catch(err) {
    alert('Oops, unable to copy');
  }

  window.getSelection().removeAllRanges();
};

return CopyInput;

})();

$(function() {

if ($('.copyInput').length) {
  new CopyInput($('.copyInput'));
}

});