var FormEditor = {
	
	'init' : function() {
		$('.editor_form').live('submit', this.process);
		$('#request_presintation_submit').click(this.processByParent);
	},
	
	'process' : function() {
		FormEditor.processForm($(this));
		return false;
	},
	
	'processByParent' : function() {
		FormEditor.processForm($(this).parents('form:first'));
		return false;
	},
	
	'processForm' : function(frm) {
		frm.ajaxSubmit({
			//dataType: 'json',
			type: 'post',
			beforeSubmit : function(a, f, o) { $('.error_message').remove(); },
			success : function(data) {
				data = JSON.parse(data);
				
				if (data.success) {
					frm.clearForm();
					if (data.messages) {
						frm.prepend('<div class="error_message">'+data.messages.success+'</div>');
					}
					if (data.redirect) {
						document.location.href = data.redirect;
					}
				} else {
					$('#captcha_img').attr("src", "/captcha/?" + Math.random()/10);
					$('#captcha').attr("value", "");
					var fields = [];
					var kk = 0;
					for (var i in data.messages) {
						for (var j in data.messages[i]) {
							frm.find('#'+i).attr('value', data.messages[i][j]);
						}
						fields[kk] = i;
						kk++;
					}
					setTimeout(function(){
						for (field in fields) {
							ff = fields[field];
							if (ff == 'preffered_date') {
								$('#'+ff).val('дд.мм.гг');
							} else {
								$('#'+ff).val('');
							}
						}
					},3000);
				}
			}
		});
	}
};

$(document).ready(function() {
	FormEditor.init();
});
