jQuery.fn.getFormData = function(data) {
	$('*[name]', $(this)).each(function() {
		var t = $(this);
		var val = (t.attr('type') == 'checkbox') ? (t.attr('checked') == true) ? 1 : 0
                        : (t.attr('type') == 'radio') ? (t.attr('checked') == true) ? t.val() : false
                        : t.val();
                if(val !== false) {
        		data[t.attr('name')] = val;
                }
	});
	
	return $(this);
}

jQuery.fn.formSubmitAjax = function(callback, config) {
	var method = config.method || $(this).attr('method');
	var action = config.action || $(this).attr('action');

	data = new Object();
	$(this).getFormData(data);

	$.ajax({
		type: method,
		url: action,
		dataType: config.type,
		data: data,
		success: callback
	});

	return false;
}

/**
 * Submits a form using XHR. Grabs all form-controls
 * with name-attributes and submits to form's action
 * using form's method or custom action/method set in conf
 *
 * @class ajaxSubmit
 * @param {String|Function} foo, CSS-selector to element to be updated with XHR-response or callback function for XHR-call (data is passed to function)
 * @param {Object} conf, custom config-object
 */
jQuery.fn.ajaxSubmit = function(foo, conf) {
	var config = {
		method: false,	// request method (get/post) defaults to form's
		action: false,	// action (url) defaults to form's
		loading: 'Carregando...',
		type: false		
	};
	config = $.extend(config, conf);

	var callback = (typeof(foo) === 'string') ? function(data) {$(foo).html(data);} : (typeof(foo) === 'function') ? foo : false;

	return this.each(function() {
		var form = $(this);

		if(form.is('form')) {
			var submit = $('input[type="submit"]', form);
			var data = {};

			form.submit(function() {
				submit.val(config.loading);
				submit.attr('disabled', 'disabled');

				return form.formSubmitAjax(callback, config);
			});
		}
	});
};
