var NewCommentForm=Class.create({
  initialize:function(form){
    this.views={
      form:form,
      media:{
        toggle:form.down('fieldset.media div.toggle a'),
        fieldWrapper:form.down('fieldset.media ol.add')
      },
      result:form.next('div.result')
    };
    this.model={};
    this.observers={
      toggleMedia:this.toggleMedia.bindAsEventListener(this),
      showForm:this.showForm.bindAsEventListener(this)
    };
    
    this.initializeForm();
    this.views.media.toggle.observe('click',this.observers.toggleMedia);
    this.views.result.down('p.post-again a').observe('click',this.observers.showForm);
  },
  initializeForm:function(){
    // If user has JS disabled, form submits via page reload; otherwise,
    // prepare it to submit with file via iframe, which returns a JS response.
    
    this.views.form.writeAttribute('target','new-comment-target')
      .writeAttribute('action',this.views.form.readAttribute('action')+'.js');
  },
  initializeValidatedForm:function(){
    var vf=this.model.validatedForm=new BB.ValidatedForm(this.views.form);
    vf.validates('presenceOf', 'textarea[name="comment[body]"]', {
      message:"Please enter your comment!"
    });
    vf.validates('presenceOf', 'input[name="comment[poster_name]"]', {
      message:"Please tell us your name."
    });
    vf.validates('presenceOf', 'input[name="comment[email]"]', {
      message:"Please tell us your email address. This will be private."
    });
    vf.validates('formatOf', 'input[name="comment[email]"]', {
      format:BB.ValidatedForm.formats.email,
      message:"This email address isn't valid."
    });
  },
  toggleMedia:function(ev){
    new Effect.toggle(this.views.media.fieldWrapper,'appear'); ev.stop();
  },
  showForm:function(ev){
    this.views.form.show().reset();
    this.views.form.down('div.submit input').removeAttribute('disabled');
    this.views.result.hide();
    ev.stop();
  }
});

document.observe('dom:loaded',function(){
  $$('form.new-comment').each(function(f){
    new NewCommentForm(f);
  });
});
