﻿var FieldGroupManager = {
	init: function () {
		var self = this;
		$("fieldset.fieldGroup").each(function () {
			var $fs = $(this);
			var $chk = $fs.find(">div.fieldGroup-header input:checkbox");
			if (!$chk.length) return;
			$chk.click(function (e) { self.sync($fs, $chk, true); });
			self.sync($fs, $chk, false);
		});
	},

	sync: function ($fs, $chk, animate) {
		var $body = $fs.children("div.fieldGroup-body");

		if ($chk.prop("checked")) {
			if (animate) {
				$body.slideDown(200);
			} else {
				$body.show();
			}
			$fs.addClass("open");
		} else {
			if (animate) {
				$body.slideUp(200);
			} else {
				$body.hide();
			}
			$fs.removeClass("open");
		}
	}
};

(function ($) {

	$.widget("ui.fieldgroup", {
		options: {
			label: "Options",
			selected: false,
			toggled: null
		},

		_fieldset: null,
		_body: null,
		_chk: null,

		_create: function () {
			var self = this;
			var id = "fieldgroup_" + new Date().getTime();

			var html = [];
			html.push("<fieldset class='fieldGroup'>");
			html.push("<div class='fieldGroup-header'>");
			html.push("<input id='" + id + "' type='checkbox'>");
			html.push("<label for='" + id + "'></label>");
			html.push("</div>");
			html.push("<div style='' class='fieldGroup-body'></div>");
			html.push("</fieldset>");

			var $fs = $(html.join(''));
			var $body = $fs.children("div.fieldGroup-body");
			var $header = $fs.children("div.fieldGroup-header");
			var $chk = $header.children("input:checkbox");
			var $lbl = $header.children("label");

			this._fieldset = $fs;
			this._body = $body;
			this._chk = $chk;

			$lbl.html(this.options.label);
			$chk.click(function (e) {
				if(self.options.toggled) self.options.toggled.call(self.element, self.selected());
				FieldGroupManager.sync($fs, $chk, true); 
			});
			$body.append(this.element.children());

			this.element.append($fs);

			$chk.prop("checked", this.options.selected);

			FieldGroupManager.sync($fs, $chk, false);
		},

		body: function() {
			return this._body;
		},

		toggle: function (show) {
			this._chk.prop("checked", show);
			FieldGroupManager.sync(this._fieldset, this._chk, true);
		},

		selected: function () {
			return this._chk.prop("checked");
		},

		destroy: function () {
			$.Widget.prototype.destroy.call(this);
		}
	});

})(jQuery);
