$(document).ready(function() {
	var targets = new Array;
	targets['connect-form'] = 'step2';
	targets['check-form'] = 'step3';
	targets['go-services'] = 'step4';


	var connectForm = $('#connect-form');
	connectForm.find('input').change(function() {
		if ($(this).is(':checked')) {
			connectForm.submit();
		}
	});

	
	var handleServices = function(obj) {
		if ($.browser.msie)
			return;
		var svc = obj.find('#go-services input[@name="services"]');
		if (!svc.length)
			return;

		svc.change(function() {
			var grpName = $(this).attr('id') + '-group';
			if ($(this).is(':checked'))
				$('#' + grpName).show();
			else
				$('#' + grpName).hide();
		});
		svc.trigger('change');
	};



	var handleForm = function() {
		var $this = $(this);
		var target = getTarget($this);

		$.ajax({
			url: $this.attr('action'),
			type: $this.attr('method'),
			data: $this.serialize() + '&ajax=1',
			dataType: 'json',
			beforeSend: function() {
				var w = target.find('.wrapper');
				$this.addClass('ajaxi');
				var p = $this.parents('.wrapper');
				p.find('.b-messagebox').remove();
				p.find('.error').each(function() {
					$(this).parent('tr').remove();
				});
			},
			error: function() {
				$this.removeClass('ajaxi');
			},
			success: function(data) {
				if (typeof data.redirect != "undefined") {
					document.location = data.redirect;
					return;
				}

				$this.removeClass('ajaxi');
				var w = data.error ? $this.parents('.wrapper') : target.find('.wrapper');
				w.html(data.html)
				handleServices(w);
				w.jNice();
				w.find('form').submit(handleForm);
			}
		});
		return false;
	}

	connectForm.submit(handleForm);


	function getTarget(obj) {
		var _id = targets[ obj.attr('id') ];
		var div = $('#' + _id);

		if (!div.length) {
			div = $('<div id="' + _id + '"><div class="wrapper" /></div>');
			var p = obj.after(div);
		}
		return div;
	}
	
	connectForm.find('input').trigger('change');
});
