
function findContent(root, li) {
	var content = null;
	root.find('fieldset').each(function(index) {
		if ('w_' + $(this).attr('id') == li.attr('id')) {
			content = $(this);
		}
	});
	return content;
}

function w_deactivate(e) {
	var content = findContent(e.parent().parent(), e);
	e.removeClass('active');
}

function w_activate(e) {
	var root = e.parent().parent();
	var content = findContent(root, e).show().siblings('fieldset').hide();

	root.is('form') ? w_validate(root, content) : true

	e.addClass('active');

	(e.next().length > 0) ? root.find('a.next').show() : root.find('a.next').hide();
	(e.prev().length > 0) ? root.find('a.prev').show() : root.find('a.prev').hide();
	(e.next().length > 0 || !root.is('form')) ? root.find('.submit').hide() : root.find('.submit').show();
}

function w_step(from, to) {
	w_deactivate(from);
	w_activate(to);
}

function w_next(from) {
	var n = from.nextAll().not('.hidden').first();
	if (n.length > 0) {
		w_step(from, n);
	}
}

function w_prev(from) {
	var n = from.prevAll().not('.hidden').first();
	if (n.length > 0) {
		w_step(from, n);
	}
}

function w_validate(form, content) {
	var ok = true;

	// Ta bort alla errors, sätts av valideringen
	$('.wizard fieldset em').each(function() {
		$(this).remove();
	});

	content.find('input').add(content.find('select')).each(function(index) {
		if (!form.validate(validation[form.attr('id')]).element($(this))) {
			ok = false;
		}
	});
	return ok;
}

$(function(e) {

	// Skapa ordnad lista med alla steg.
	var ol = '<ul class="wiznav">';
	$('.wizard > fieldset > legend').each(function() {
		var cls = '';
		if ($(this).parent().hasClass('hidden')) {
			cls = ' class="hidden"';
			$(this).parent().removeClass('hidden');
		}
		ol += '<li id="w_' + $(this).parent().attr('id') + '"' + cls + '>' + $(this).text() + '</li>';
		$(this).hide();
	});
	ol += '</ul>';
	$('.wizard').prepend(ol);

	// Föregående/Nästa
	$('.wizard div.buttons').prepend('<a class="button next" href="#" onclick="this.blur();"><span>' + loc['next'] + '</span></a>');
	$('.wizard div.buttons').prepend('<a class="button prev" href="#" onclick="this.blur();"><span>' + loc['prev'] + '</span></a>');

	// Aktivera första
	$('.wizard ul.wiznav li:first').each(function() {
		w_activate($(this));
	});

	// onclick
	$('.wizard .button').click(function(e) {

		var root = $(this).parent().parent();
		var active = root.find('li.active');
		var content = findContent(root, active);

		if ($(this).hasClass('prev')) {
			e.preventDefault();
			w_prev(active);
		}
		else if (root.is('form') ? w_validate(root, content) : true) {
			if ($(this).hasClass('next')) {
				e.preventDefault();
				w_next(active);
			}
		}
		else {
			e.preventDefault();
		}

	});
});

