var FormAjax = Class.create({

    initialize: function(form_id, config) {
        this.form = $(form_id) || document[form_id];
        this.config = config;

        if (!this.form) throw('Form "' + frm + '" not found');

        $(this.form).observe('submit', this._submitForm.bind(this));
    },

    _submitForm: function (event) {

        event.stop();

        if (!this._validateForm()) return false;

        this.showSpinner();

        this.form.request({
            enctype: 'multipart/form-data',
            onComplete: this._parseResult.bind(this)
        });

        return 1;
    },

    _validateForm: function() {
        return 1;
    },

    _parseResult: function(transport) {

        this.hideSpinner();
        this.is_processing = 0;

        var response = transport.responseText.evalJSON();

        if (response.status == 'success') {
            this._success(response.data);
        } else if (response.status == 'error') {
            this._error(response.messages);
        } else {
            alert('Unknown server response');
        };

    },

    _success: function(data) {
        if (!this.config.callbackSuccess) return;
        this.config.callbackSuccess(data);
    },

    _error: function(messages) {

        for(i=0; i<messages.length; i++ ) {
            this._setElementError(messages[i].name, messages[i].value);
        }
    },

    _setElementError: function(name, value) {
        var selector = '#' + this.form.id + ' #error_' + name;
        if (!$$(selector)) throw('Element not found: ' + selector);

        $$(selector)[0].innerHTML = value;
    },

    clearErrors: function() {
        $$('#' + this.form.id + ' .error').each(function(container){
            container.innerHTML = '';
        });
    },

    showSpinner: function() {
        var spinner = $$('#' + this.form.id + ' .spinner')[0];

        if (!spinner || !spinner.style) return 0;

        $(spinner).show();
        return 1;
    },

    hideSpinner: function() {
        $$('#' + this.form.id + ' .spinner').each(function (img) {img.hide()});
    }
});

