var DosagePopup = {
  closeCurrent : function() {
    //TODO something very odd here. there's more than one. why are there so many??
    Control.Window.windows.each(function (w) {
      w.close();
    });
  },
  doSave: function(destination, url, params) {
    new Ajax.Request(url, {
      method: 'post',
      parameters: params,
      evalScripts: true,
      onFailure: function(response) {
        DosagePopup.failure(response, destination);
      },
      onSuccess: function(request) {
        DosagePopup.saveSuccess(request);
      }
    });
  },
  saveSuccess: function(response) {
    DosagePopup.closeCurrent();
    window.location.reload();
  },
  failure: function(response,destination) {
    if (response.status == 422) {
      // Validation failed
      PLM.Notify.bad(response.responseJSON.join('<br/>'), 'validation-errors');
      $$('.rx-save').invoke('enable');
    }
  }
}
PLM.init(function() {
  $$('body').first().observe('click', Event.delegate({
    '.rx-cancel': function(event){
      DosagePopup.closeCurrent();
      Event.stop(event);
      return false;
    },
    '.rx-reload': function(event){
      DosagePopup.closeCurrent();
      Event.stop(event);
      window.location.reload();
      return false;
    },
    '.rx-save': function(event){
      var form = event.element().form;
      event.element().disable();
      var destination = $$('.plm_window').first();
      DosagePopup.doSave(destination, form.action, Form.serialize(form));
      Event.stop(event);
      return false;
    },
    '#control_overlay': function(event){
      DosagePopup.closeCurrent();
    }
  }))
  });