/**
 * Simulate HTML5 placeholder attribute
 *
 * Needed since
 *    - div[contentEditable] elements don't support it
 *    - older browsers (such as IE8 and Firefox 3.6) don't support it at all
 *
 * @param {Object} parent Instance of main wysihtml.Editor class
 * @param {Element} view Instance of wysihtml.views.* class
 * @param {String} placeholderText
 *
 * @example
 *    wysihtml.dom.simulatePlaceholder(this, composer, "Foobar");
 */
(function(dom) {
  dom.simulatePlaceholder = function(editor, view, placeholderText, placeholderClassName) {
    var CLASS_NAME = placeholderClassName || "wysihtml-placeholder",
        unset = function() {
          var composerIsVisible   = view.element.offsetWidth > 0 && view.element.offsetHeight > 0;
          if (view.hasPlaceholderSet()) {
            view.clear();
            view.element.focus();
            if (composerIsVisible ) {
              setTimeout(function() {
                var sel = view.selection.getSelection();
                if (!sel.focusNode || !sel.anchorNode) {
                  view.selection.selectNode(view.element.firstChild || view.element);
                }
              }, 0);
            }
          }
          view.placeholderSet = false;
          dom.removeClass(view.element, CLASS_NAME);
        },
        set = function() {
          if (view.isEmpty() && !view.placeholderSet) {
            view.placeholderSet = true;
            view.setValue(placeholderText, false);
            dom.addClass(view.element, CLASS_NAME);
          }
        };

    editor
      .on("set_placeholder", set)
      .on("unset_placeholder", unset)
      .on("focus:composer", unset)
      .on("paste:composer", unset)
      .on("blur:composer", set);

    set();
  };
})(wysihtml.dom);
