function OrderForm()
{
    this.init();
}

OrderForm.prototype = {
    o: {
        $form: '#form',
        $overlay: '#overlay',
        form_prefix: 'form_',
        delay: 300,
        
        msg: {
        	form_submited: 'Форма отправлена'
        },
        
        errors: {
        	person: {
        		required: 'Поле обязательное для заполнения'
    		},
        	email: {
        		required: 'Поле обязательное для заполнения', 
        		invalid: 'Неверный формат'
    		}
        }
    },


    init: function ()
    {
        var _this = this;
        $(this.o.$form).submit(function()
        {
            _this.request();
            return false;
        });

        $(this.o.$form).find('.close').click(function()
        {
            _this.hideForm();
            return false;
        });
    },


    msg: function (code) {
    	var text = this.o.msg[code];
    	$(this.o.$form).find('.form').hide();
    	$(this.o.$form).find('.msg').show().html(text);
    	this._normalizeLayout();
    },


    hideForm: function () {
    	$(this.o.$form).fadeOut(this.o.delay);
    	//$(this.o.$form).hide();
    	$(this.o.$overlay).hide();
    },


    showForm: function () {
		$(this.o.$form).fadeIn(this.o.delay);
		//$(this.o.$form).show();
		$(this.o.$overlay).show();

        this._normalizeLayout();
    },


	_normalizeLayout: function () {
        var w = $(window).width();
        var w2 = $(this.o.$form).width();
        var h = $(window).height();
        var h2 = $(this.o.$form).height();
        var left = Math.round((w / 2) - (w2 / 2));
        var top  = Math.round((h / 2) - (h2 / 2));

        $(this.o.$form).css({
            top: top + 'px',
            left: left + 'px'
        });
	},


    request: function ()
    {
    	var _this = this;
        var sendData = $(this.o.$form).serialize();
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: 'form_send.php',
            data: sendData,
            success: function (data) 
            {
                if (data.status == 'neok')
                {
                    _this.showErrors(data.errors)
                }
                else if (data.status == 'ok')
                {
                	_this.msg('form_submited');
                }
            }
        });
    },


    showErrors: function (fields)
    {
    	var _this = this;
    	$(this.o.$form).find('div.error').hide();
    	$(this.o.$form).find('input.error').removeClass('error');
        $.each(fields, function(field, error_code)
        {
            var id = _this.o.form_prefix + field;
            var $error_block = $('#'+ id).parent().next();
            var error_text = _this.o.errors[field][error_code];
            
            $('#'+id).addClass('error');
            $error_block.html(error_text).show();
        });
    }

}
