// JavaScript Document
function CheckboxGroup () {}

CheckboxGroup.create = function (tableContainer, data, form, numColumns) {
	numColumns = numColumns || 3;
	if (tableContainer) {
		var lastRowContaner;
		for (var i=0; i<data.length; i++) {
			var d = data[i];
			if (i%numColumns == 0) {
				var rowContainer = tableContainer.insertRow(-1);
				lastRowContaner = rowContainer;
			}
			else {
				var rowContaner = lastRowContaner;
			}

			var checkbox = new CheckboxWidget(
				rowContainer, d["name"], d["value"], d["title"], d["checked"], form);
		}
	}
}

function CheckboxWidget (rowContainer, name, value, title, checked, form) {
	this.rowContainer = rowContainer;
	this.name = name;
	this.value = value;
	this.title = title;
	this.checked = Boolean(Number(checked));
	this.form = form;
	
	this.createControl();
	this.createView();
	this.setChecked(this.checked);
}

CheckboxWidget.prototype.createControl = function () {
	var ch = document.createElement("input");
	ch.type 	= "checkbox";
	ch.value 	= this.value;
	ch.checked 	= this.checked;
	ch.name 	= this.name;
	ch.style.display = "none";
	ch.style.visibility = "hidden";
	this.checkboxControl = ch;
	this.form.appendChild(ch);
}

CheckboxWidget.prototype.createView = function () {
	this.checkedIcon = createImage("images/checkbox/1.gif");
	this.uncheckedIcon = createImage("images/checkbox/0.gif");
	this.icon = createImage();
	
	var cell = this.rowContainer.insertCell(-1);
	cell.style.paddingRight = px(4);
	cell.style.verticalAlign = "top";
	cursor(cell, "pointer");
	cell.appendChild(this.icon);
	
	var cell = this.rowContainer.insertCell(-1);
	noUserSelect(cell);
	cell.style.verticalAlign = "top";	
	cursor(cell, "pointer");
	cell.innerHTML = this.title.length > 0 ? this.title : "&nbsp;";
	this.titleCell = cell;
	
	Event.bindDom(this.icon, "click", this, this.onClick);
	Event.bindDom(this.titleCell, "click", this, this.onClick);
}

CheckboxWidget.prototype.setChecked = function (b) {
	this.checked = Boolean(b);
	this.icon.src = this.checked ? this.checkedIcon.src : this.uncheckedIcon.src;
	this.checkboxControl.checked = this.checked;
	this.titleCell.style.backgroundColor = this.checked ? "#1C7AD5" : "";
}

CheckboxWidget.prototype.onClick = function (ev) {
	var b = ! this.checked;
	this.setChecked(b);
}