// mootools-1.2-beta2
/*
var MyAjax = new Class({
  
  Extends: Ajax,
  
  success: function(text, xml){
    if (this.options.update) {
      $(this.options.update).empty().set('html', text.stripScripts(false));
    }
    text = this.processScripts(text);
    this.onSuccess(text, xml);
  }
  
});
*/
// mootools-1.11
var MyAjax = Ajax;

var Prescription = {};

Prescription.Form = new Class({
  
  //Implements: Options,
  
  options: {
    update: null,
    uploadForm: null,
    ajaxSubmit: function(eventName) {
      return true;
    }
  },
  
  initialize: function(form, options) {
    this.form = $(form);
    this.setOptions(options);
    
    this.initDomElements();
    this.addEventHandlers();
  },
  
  initDomElements: function() {
    this.inputEvent = new Element('input', { type: 'hidden', name: '_eventName' });
    this.inputEvent.inject(this.form, 'top');
    
    this.submits = this.form.getElements('input[type=submit]');
  },
  
  addEventHandlers: function() {
    this.submits.each(function(input) {
      input.addEvent('click', this.handleSubmitClick.bind(this, input));
    }, this);
    
    this.form.addEvent('submit', this.handleFormSubmit.bind(this));
    
    if (this.options.uploadForm) {
      this.form.getElements('input[type=file]').each(function(input) {
        input.addEvent('change', this.handleFileChange.bind(this, input));
      }, this);
    }
  },
  
  handleSubmitClick: function(input) {
    this.inputEvent.value = input.name;
  },
  
  handleFormSubmit: function(e) {
    if (!this.options.ajaxSubmit(this.inputEvent.value)) return;
    if (e) new Event(e).stop();
    this.submits.each(function(submit) {
      submit.disabled = true;
    });
    new MyAjax(this.form.action, {
      method: 'post',
      data: this.form,
      update: this.options.update,
      evalScripts: true,
      onComplete: function() {
        this.submits.each(function(submit) {
          submit.disabled = false;
        });
      }.bind(this)
    }).request();
  },
  
  handleFileChange: function(input) {
    $(this.options.uploadForm).empty();
    
    var label = input.getPrevious('label');
    var inputName = input.name;
    
    var file = input;//.cloneNode(false);
    file.name = 'file';
    file.inject(this.options.uploadForm);
    
    var h = new Element('input', {
      type: 'hidden',
      name: 'inputName',
      value: inputName
    });
    h.inject(this.options.uploadForm);
    
    new iframe(this.options.uploadForm, {
      update: inputName + '-preview',
      onComplete: function() {
        var f = new Element('input', {
          type: 'file',
          name: inputName
        });
        f.inject(label, 'after');
        f.addEvent('change', this.handleFileChange.bind(this, f));
      }.bind(this)
    }).request();
  }
  
});
Prescription.Form.implement(new Options);