var AddUserAsContactDialog = Behavior.create(Dialog.Base, {
  initialize : function($super) {
    $super();
    this._bindCancelEventHandler();
    this._bindRemoteFormSubmission();
  },
  
  _bindCancelEventHandler : function() {
    var cancelAnchor = this.element.down('a.cancel');
    cancelAnchor.observe('click', (function(e) { e.stop(); this.close(); }).bindAsEventListener(this));    
  },
  
  open: function($super, contactName, contactID) {
    this.element.down('h6 span').innerHTML = contactName;
    this.element.down('input[name=\'contactship\[contact_id\]\']').value = contactID;
    $super();
  },
  
  clearFields : function() {
    var textarea = this.element.down('textarea[name=\'contactship\[initial_message\]\']');
    textarea.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('add_user_as_contact', '.dialog.add_user_as_contact', AddUserAsContactDialog);
Event.addBehavior({
  '#canvas.logged_in a.add_contact:click':function(event){     
     event.stop();
     hcard = event.element().up('.vcard');
       if (hcard) {
         contactName = hcard.down('.fn').innerHTML;
         contactID = hcard.dbID();
       }
      Dialog.getInstance('add_user_as_contact').open(contactName,contactID);
  }
})