var wv8 = {};

jQuery(function($) {
	wv8.submitForm = function(event, form, partial) {
		var
			sbmt = $('#submit', form),
			data = form.serialize(),
			span = $('<span class="wv8ajax loading">...</span>'),
			url  = 'index.php?func=save&ajax=1&page=globalsettings' + (partial ? '_partial' : '_settings');

		// Formular zurücksetzen

		$('.wv8ajax', form).remove();
		$('#wv8errors').remove();
		$('#reset', form).after(span);

		// Request abschicken

		sbmt.prop('disabled', true);

		$.post(url, data, function(response) {
			span.removeClass('loading').addClass(response.status == 0 ? 'success' : 'error').text(response.message);
			sbmt.removeAttr('disabled');

			// Fehler ggf. anzeigen

			if (response.status == 1) {
				var ul = $('<ul id="wv8errors"></ul>');

				for (var id in response.errors) {
					ul.append($('<li>').text(response.errors[id]));
				}

				form.after(ul);
			}
		}, 'json');

		return false;
	};

	var hidden = $.cookie('wv8_hidden_legends');
	hidden = (hidden === '' || hidden === null) ? [] : hidden.split(',');

	// Ein- und Ausklappen von Fieldsets ermöglichen

	$('form#wv8 fieldset').wvToggleFieldset({
		isHidden: function(fieldset) {
			var id = fieldset.data('wv8id')+'';
			return $.inArray(id, hidden) >= 0;
		},

		onHide: function(fieldset) {
			var id = fieldset.data('wv8id')+'';
			hidden.push(id);
			$.cookie('wv8_hidden_legends', hidden.join(','), 30);
		},

		onShow: function(fieldset) {
			var id = fieldset.data('wv8id')+'';
			hidden.splice(hidden.indexOf(id), 1);
			$.cookie('wv8_hidden_legends', hidden.join(','), 30);
		}
	});
});
