/**
 * Wrk_Form(elem, options)
 * 
 * Initializes the form as our standard ajax admin form.
 * 
 * Options:
 *  submitOnEnter: false
 *  dataType: text etc...
 *  success: callback(response)
 * 
 * Exposes a number of events for extensibility:
 *  form-success
 *  form-after-success
 *  form-reset
 *  form-error
 *  
 */
var Wrk_Form = new Class({
    Implements: [Options, Events],
    options: {/*
        onClick: $empty,
        onNext: $empty,
        onPrev: $empty,*/
        submitOnEnter: false,
        dataType: 'text'
    },
    
    initialize: function(element, options) {
        this.setOptions(options);
        this.target = $(element);

        if(this.options.submitOnEnter === false) {
            this.target.bind("keypress", function(e) {
                if (e.keyCode == 13) return false;
            });
        }
        
        var form = this;
        this.target.ajaxForm({
            beforeSubmit: function(data, formElem, options) {
              form.fireEvent('form-before-submit', [data, formElem, options]);
              //run validator here. Conversly, we could bind a function to  the "form-submit-validate" event
              formElem.validate({
                  messagePrepend: '<span class="ui-icon ui-icon-alert"></span>'
              });
              if(formElem.valid()) {
                  return true;
              } else {
                  Wrk.notify('There are one or more validation errors! Please check the form.', 'error');
                  return false;
              }
            },
            dataType: this.options.dataType,
            success: this._success.bind(this),
            error: this._error.bind(this)
        });
        
        this.target.bind('form-pre-serialize', function(event, $form, options) {
            form.fireEvent('form-pre-serialize');
        /** @todo Will this trigger the save of multiple instances? */
            if(typeof tinyMCE != "undefined")
                tinyMCE.triggerSave();
        }); 

    },
    
    _success: function(response) {
        this.fireEvent('form-success', [response]);
        
        Wrk.notify(response, 'success');
        
        if(this.target.find('input[name=editing]').val() != 'true') {
            this.reset();
        }
        
        this.fireEvent('form-after-success');
    },
    
    
    _error: function(XMLHttpRequest, textStatus, errorThrown) {
        this.fireEvent('form-error');
        Wrk.notify(XMLHttpRequest.responseText, 'error');
    },

    reset: function() {
        this.fireEvent('form-reset');
    },
    
    /**
     * $.toObject()
     * 
     * Converts a form into a javascript object using control names
     * for keys, and field values for, well values.
     * 
     * @return object
     */
    toObject: function() {
        var d = this.target.serializeArray();
        var data = {};
        $.each(d, function(i, val) {
            data[val.name] = val.value;
        });
        
        return data;
    },
    
    /**
     * populate(data)
     * 
     * Populates a form's text fields from an object. Uses the 
     * object's keys for control names.
     * 
     * Currently only supports type = text || hidden
     * 
     * @return void
     */
    populate: function(data) {
       var $form = this.target;
       $.each(data, function(i, val) {
           $form.find(':text[name="'+i+'"], :hidden[name="'+i+'"]').val(val);
       });
    }

});
