(function($) {
	/*
	 * needs jquery.validate
	 */
	
	$.fn.comForm = function(options) {
		var opts = $.extend({}, $.fn.comForm.defaults, options);
		var $this;
		
		// iterate and reformat each matched element
		return this.each(function() {
			$this = $(this);
						
			$this.validate({
				submitHandler: function(form) {
					var data = $this.serialize() + '&action=' + opts.action;
					success = function(data, textStatus, jqXHR) {
						if (data.status == 0) {
							jAlert(data.html, 'Fehler');
							return false;
						}
						else if (data.status == 1) {
							opts.success(data, opts, form);
						}
					}
					
					$.ajax({
						type: 'POST',
						url: opts.rpc,
						data: data,
						success: success,
						dataType: 'json'
					});
					
				}
			})
			return;
			
		});
	};	
	
	$.fn.comForm.success = function(data, options, form) {
		if (options.after == 'submit') {
			form.submit();
			return;
		}
		else if (options.after != '') {
			jAlert(data.html, 'Hinweis', function() {
				var url = (options.after == '_self') ? window.location.href : options.after; 
				window.location.replace(url);
			});
			
		}
		
	}
	
	/* plugin defaults */
	$.fn.comForm.defaults = {
		rpc:			'/icoaster/extension/com/rpc.php',
		action:			'',
		success:		$.fn.comForm.success,		// wenn request mit status=1 antwortet
		after:			'', 						// what to do after success {'submit': submit original form}
	};

})(jQuery);
