(function($) {

	var minimalIsHidden = function(fieldset) {
		return fieldset.is('.wv-hidden');
	};

	var toggleFieldset = function() {
		var
			fieldset  = $(this).closest('fieldset'),
			isHidden  = $(this).data('wv-ishidden'),
			onShow    = $(this).data('wv-onshow'),
			onHide    = $(this).data('wv-onhide'),
			legend    = $('legend', fieldset),
			is06      = $('body').is('.sly-0_6'),
			base      = is06 ? '../data/dyn/public/developer_utils/' : '../data/dyn/public/webvariants/developer-utils/',
			link      = this;

		if (isHidden(fieldset)) {
			fieldset.removeClass('wv-hidden');
			link.src = base + 'images/up.png';
			legend.removeClass('wv-collapsed');

			onShow(fieldset);
		}
		else {
			fieldset.addClass('wv-hidden');
			link.src = base + 'images/down.png';
			legend.addClass('wv-collapsed');

			onHide(fieldset);
		}
	};

	$.fn.extend({
		wvToggleFieldset: function(settings) {
			settings = $.extend({}, {
				isHidden: minimalIsHidden,
				onClick:  toggleFieldset,
				onHide:   function(fieldset) { },
				onShow:   function(fieldset) { }
			}, settings);

			return this.each(function() {
				if (!$(this).is('fieldset')) return;

				var
					legend   = $('legend', this),
					is06     = $('body').is('.sly-0_6'),
					base     = is06 ? '../data/dyn/public/developer_utils/' : '../data/dyn/public/webvariants/developer-utils/',
					fieldset = $(this);

				if (settings.isHidden(fieldset)) {
					legend.append('<img class="wv-fieldsettoggle" src="' + base + 'images/down.png" alt="" />');
					legend.addClass('wv-collapsed');
					fieldset.addClass('wv-hidden');
				}
				else {
					legend.append('<img class="wv-fieldsettoggle" src="' + base + 'images/up.png" alt="" />');
				}

				$('.wv-fieldsettoggle', legend)
					.data('wv-ishidden', settings.isHidden)
					.data('wv-onhide',   settings.onHide)
					.data('wv-onshow',   settings.onShow)
					.bind('click', settings.onClick);
			});
		}
	});

})(jQuery);
