/*
Отправка формы
2008 - Magic Wand
*/

FormSender = function(form, button, status_block, code_image) {
    this.form = form;
    this.button = button;
    this.status_block = status_block;
    this.code_image = code_image ? code_image : '/code.php';
}

FormSender.prototype = {
    send: function() {
        this.displaySendProcess();
        var _this = this;
        $.post(this.getFormAction(), this.getFieldsData(), function(data) {
           _this.processResponse(data);
        });
    },
    
    processResponse: function(data) {
        data = $.trim(data);
        if(data == 'ok') {
            this.hideSendProcess('Спасибо! Ваше сообщение принято.');
            this.cleanFields();
        } else {
            //this.hideSendProcess('При отправке сообщения произошла ошибка. Пожалуйста, повторите попытку позднее.');
            this.hideSendProcess(data);
        }
        this.reloadProtectedCode();
    },
    
    cleanFields: function() {
        this.getFields().not(':hidden').val('');
    },
    
    reloadProtectedCode: function() {
        this.getCodeImage().attr('src', this.code_image + '?' + Math.random() * 10000);
    },
    
    getFormAction: function() {
        return this.getForm().attr('action');
    },
    
    displaySendProcess: function() {
        this.disableButton(true);
        this.showStatus('<img src="/i/ajax-loader.gif"/>');
    },
    
    hideSendProcess: function(result) {
        this.disableButton(false);
        this.showStatus(result);
    },
    
    disableButton: function(disable) {
        this.getButton().each(function() {
          this.disabled = disable;
        });
    },
    
    showStatus: function(msg) {
        this.getStatusBlock().html(msg);
    },
    
    getFieldsData: function()
    {
        var data = {};
        this.getFields().each(function() {
          data[this.name] = this.value;
        });
        return data;
    },
    
    getCodeImage: function() {
        return $('img.code_image', this.getForm());
    },
    
    getFields: function() {
        return $(":input[type!='submit']", this.getForm());
    },
    
    getForm: function() {
        return $(this.form);
    },
    
    getButton: function() {
        return $(this.button);
    },
    
    getStatusBlock: function() {
        return $(this.status_block);
    }
}

