

(function() {
  
  function hideOrShow(element, shouldShow) {
    Element[shouldShow ? 'show' : 'hide'](element);
  }
  
  var Previewer = {
    setup: function(element, form) {
      this.element  = $(element);
      this.form     = $(form);      
      this.gravatar = this.element.down('.gravatar img');
      
      // Initialize the Markdown converter.
      this.converter = new Showdown.converter();
      
      this.fields = {
        author:  $('author') || this.form.down('.post-comment-logged-in a'),
        url:     $('url'),
        email:   $('email'),
        comment: this.form.down('textarea')
      };

      this.slots = {
        author:  this.element.down('.comment-author .content'),
        comment: this.element.down('.comment-body .content')
      };
      
      this.placeholders = {
        author:  this.element.down('.comment-author .placeholder'),
        comment: this.element.down('.comment-body .placeholder')
      };
      
      this.formObserver = this.formObserver = new Form.Observer(this.form, 0.5,
       this.updatePreview.bind(this));
       
      this.updatePreview();      
    },
    
    updatePreview: function() {
      window.clearTimeout(this.timeout);
      var values = this.getValues(), s = this.slots, p = this.placeholders;
      
      var hasContent =  [values.author, values.email, values.url, 
       values.comment].detect( function(value) { return !value.blank(); });
      
      hideOrShow(this.element, hasContent);
      
      s.author.update(values.author);
      if (values.author.blank()) {
        s.author.hide();
        p.author.show();
      } else {
        p.author.hide();
        s.author.show();
      }
      
      s.comment.update(this.converter.makeHtml(values.comment));
      if (values.comment.blank()) {
        s.comment.hide();
        p.comment.show();
      } else {
        p.comment.hide();
        s.comment.show();
      }
      
      // Update the gravatar. But wait until the user has stopped typing for
      // at least one second.
      this.timeout = (function() {
        var md5 = MD5(values.email || "");
        var url = ["http://www.gravatar.com/avatar/", md5, ".jpg?size=40",
         "&d=http%3A%2F%2Fwww.gravatar.com%2Favatar%2F",
         "ad516503a11cd5ca435acc9bb6523536%3Fs%3D40&r=G"].join('');
        
        if (url !== this.gravatar.readAttribute('src')) {
          this.gravatar.writeAttribute('src', url);
        }
      }).bind(this).delay(1);

      this.element.fire("preview:updated");
    },

    getValues: function() {
      if (!this.fields) {
        throw "Fields not initialized!";
      }

      var f = this.fields, values = {};
      
      if ($('openid') && $('openid_checkbox').checked) {
        values.author = $('openid').getValue();        
      } else if (f.author) {
        values.author = (f.author.nodeName.toUpperCase() === "INPUT") ?
         f.author.getValue() : f.author.innerHTML;
      }

      if (f.url) {
        values.url = f.url.getValue();
      }

      if (f.comment) {
        values.comment = f.comment.getValue();
      }
      
      if (f.email) {
        values.email = f.email.getValue();
      }

      return values;    
    }
    
  };
  
  document.observe("dom:loaded", function() {
    $$('label.ghosted').each( function(label) {
      var text = label.innerHTML, input = $(label.readAttribute('for'));
      new Form.GhostedField(input, text, { cloak: true });
    });
  });


  document.observe("dom:loaded", function() {
    if (!$('openid_checkbox')) return;
  
    var containerOpenId = $('comment_form').down('ul.info-openid');
    var containerNormal = $('comment_form').down('ul.info-regular');
  
    function hideOrShow(element, shouldShow) {
      shouldShow ? element.show() : element.hide();
    }
  
    $('openid_checkbox').observe('click', function(event) {
      var isChecked = event.element().checked;
  
      hideOrShow(containerNormal, !isChecked);
      hideOrShow(containerOpenId,  isChecked);    
    });
  });



  function _init() {
    if ($('comment_preview'))
      Previewer.setup('comment_preview', 'comment_form');
  }
  document.observe("dom:loaded", _init);
})();