var SendMessageToUserDialog = Behavior.create(Dialog.Base, {
  initialize : function($super) {
    $super();
    this._bindRemoteFormSubmission();
  },
  
  open: function($super, recipientName, recipientID) {
    this.element.down('h6 span').innerHTML = recipientName;
    this.element.down('input[name=\'message\[recipient_id\]\']').value = recipientID;
    $super();
  },
  
  clearFields : function() {
    this.element.down('input[name=\'message\[subject\]\']').value = '';
    this.element.down('textarea[name=\'message\[content\]\']').value = '';
  },
  
  _bindRemoteFormSubmission : function() {
    var submitButton = this.element.down('input[type=submit]') || this.element.down('button[type=submit]');
    var remoteForm = new Forms.Remote({
      onComplete : function(response) {
        this.reset();
      }.bind(this)
    });
    submitButton.observe('click', remoteForm.onclick.bindAsEventListener(remoteForm));
  },
  
  reset: function() {
      this.clearFields();
      this.close();
  }
});

Dialog.initInstance('send_message', '.dialog.send_message_to_user', SendMessageToUserDialog);

Event.addBehavior({
    '#canvas.logged_in a.send_message_to_user:click': function(event) {
        var hcard, recipientName, recipientID;
        
        hcard = event.element().up('.vcard');
        if (hcard) {
            recipientName = hcard.down('.fn').innerHTML;
            recipientID = hcard.dbID();
            Dialog.getInstance('send_message').open(recipientName, recipientID);
            event.stop();
        }
  }
});