function updateJSON(request, json) {
  hideErrors();
  if (json) {
    json.each(function(item) {
      var form_element = $(item[0] + '_error');
      form_element.show()
      form_element.update(item[1]);
    });
  } else {
    $('comment_added').update('<p>Your comment has been submitted and is being reviewed.  Thank You!</p>');
    new Effect.BlindDown('comment_added');
  }
  Recaptcha.reload();
  $('spinner').hide();
  $('submit_button').show();
}

function hideErrors() {
  var fields = $w('name email comment recaptcha_response_field');
  fields.each(function(field){
    $(field + '_error').hide();
  });
}

Event.addBehavior({
  '#profiles_by_ep li a:click' : function() {
    $$('#profiles_by_ep li a').each(function(el) {
      el.removeClassName('active');
    });

    this.toggleClassName('active');

    if (this.id == 'show_all_episodes') {
      $$('#profile_thumbs li').invoke('show');
      return;
    }
    var targetClass = this.id.replace('show_', 'in_');
    var targetElements = [];

    $$('#profile_thumbs li').invoke('hide');

    $$('#profile_thumbs li').each(function(el) {
      if (el.hasClassName(targetClass)) {
        targetElements.push(el)
      }
    });

    targetElements.invoke('show');
  },

  '#profile_thumbs li a:click' : function() {
    var href_for_xhr = this.href.replace(/\/(dr_profiles|patient_updates\/patient)\//, '/$1/xhr/');

    
    $$('#profile_thumbs li a').each(function(el) {
      el.removeClassName('active');
    });

    this.toggleClassName('active');

    new Ajax.Updater('sel_profile', href_for_xhr, {method: 'get', evalScripts: true});
    return false;
  },

  '#patient_comment_form:submit' : function() {
    $('spinner').show();
    $('submit_button').hide();
    new Ajax.Request(this.action, 
                    { onComplete: updateJSON, 
                      parameters: Form.serialize(this)});
    return false;
  }
});