function McxElementListView(parentElement)
{
	this.ParentElement = parentElement;
	this.CaptionElement = this.ParentElement.children[0];
	this.HeaderElement = this.ParentElement.children[1];
	this.HeaderRowElement = this.HeaderElement.children[0];

	this.CountInput = this.ParentElement.parentElement.parentElement.children[0];

	this.HeaderAddRowButton = this.HeaderRowElement.children[0].children[0];
	this.HeaderAddRowButton.NativeObject = this;
	this.HeaderAddRowButton.addEventListener("click", function(e)
	{
		var lv = this.NativeObject;
		lv.addRowBefore(0);

		e.preventDefault();
		e.stopPropagation();
		return false;
	});

	this.BodyElement = this.ParentElement.children[2];
	this.setEmpty = function(value)
	{
		if (value)
		{
			System.ClassList.Add(this.ParentElement.parentElement, "mcx-empty");
		}
		else
		{
			System.ClassList.Remove(this.ParentElement.parentElement, "mcx-empty");
		}
	};

	this.buildRow = function(callback, callback_parms)
	{
		var lvInstId = this.ParentElement.getAttribute("data-fqecid");
		
		var xhr = new XMLHttpRequest();
		var url = System.ExpandRelativePath("~/" + System.TenantName + "/flowController.htmld");
		xhr.open("POST", url);

		var h = {
			"_flowExecutionKey": "e0s1",
			"ecid": lvInstId,
			"sessionSecureToken": "7733ad40-edf6-4dc9-aa90-85bcf93cc8f0",
			"clientRequestID" : "9af7ce5bc51348a6981539a98b267072"
		};
		xhr.__callback = callback;
		xhr.__this = this;
		xhr.onreadystatechange = function(e)
		{
			if (this.readyState === 4)
			{
				responseJSON = JSON.parse(this.responseText);
				if (responseJSON.result == "success")
				{
					if (responseJSON.item.widget == "row")
					{
						// !!! `this` is now XHR, not McxElementListView !!!
						var tr = document.createElement("tr");
						tr.appendChild(this.__this.createAddRemoveColumn());

						var newRowIndex = this.__this.BodyElement.children.length;
						this.__this.CountInput.value = this.__this.BodyElement.children.length + 1;
						
						for (var i = 1; i < this.__this.HeaderRowElement.children.length; i++)
						{
							// ! BEGIN HACK !
							var columnOffset = 0;
							if (this.__this.HeaderRowElement.children.length != responseJSON.item.contents.length)
							{
								columnOffset = 1;
							}

							var td = document.createElement("td");
							var rowDefinition = responseJSON.item.contents[i - columnOffset];
							if (typeof(rowDefinition) !== "undefined")
							{
								// var colInstId = this.__this.HeaderRowElement.children[i].getAttribute("data-ecid");
								var colInstId = rowDefinition.ecid;
								var colWidget = rowDefinition.widget;

								var fqecid = lvInstId + ":" + newRowIndex + ":" + colInstId;
								
								if (colWidget === "text")
								{
									var input = document.createElement("input");
									input.id = "ec_" + fqecid;
									input.name = "ec_" + fqecid;
									input.setAttribute("data-ecid", "ec_" + fqecid);
									input.type = "text";
									td.appendChild(input);
								}
								else if (colWidget === "checkbox")
								{
									var input = document.createElement("input");
									input.id = "ec_" + fqecid;
									input.name = "ec_" + fqecid;
									input.setAttribute("data-ecid", "ec_" + fqecid);
									input.type = "checkbox";
									td.appendChild(input);

									//! must be called after appendChild since it needs to finagle the DOM
									new CheckBox(input);
								}
								else if (colWidget === "monikerListInput")
								{
									var multiselect = false;
									if (rowDefinition.multiselect === true)
									{
										multiselect = true;
									}
									var moniker = McxInstanceBrowser.create({ "multiselect": multiselect, "fullyQualifiedECID": fqecid, "ecid": rowDefinition.ecid, "validClassIds": [ rowDefinition.ecdt ], "autocompleteUrl": "~/prompt/c0/" + rowDefinition.ecdt });
									if (moniker)
									{
										td.appendChild(moniker);
									}
								}
							}
							else
							{
								td.innerHTML = "undefined row def at index " + i;
							}
							tr.appendChild(td);
						}
						this.__callback(tr, callback_parms);
					}
				}
			}
		};
		xhr.send(JSON.stringify(h));
	};
	this.addRowBefore = function(beforeIndex)
	{
		this.buildRow(function(tr, parms)
		{
			parms[0].BodyElement.insertBefore(tr, parms[0].BodyElement.children[parms[1]]);
		}, [ this, beforeIndex ]);
		this.setEmpty(false);
	};
	this.addRowAfter = function(afterElement)
	{
		this.buildRow(function(tr, parms)
		{
			parms[0].BodyElement.insertAfter(tr, parms[1]);
		}, [ this, afterElement ]);
		this.setEmpty(false);
	};
	this.removeRow = function(row)
	{
		row.remove();
		this.setEmpty(this.BodyElement.children.length == 0);
	};
	this.removeRowAt = function(index)
	{
		this.BodyElement.children[index].remove();
		this.setEmpty(this.BodyElement.children.length == 0);
	};

	this.createAddRemoveColumn = function()
	{
		var td = document.createElement("td");
		td.className = "uwt-listview-row-buttons";
		
		var aAdd = document.createElement("a");
		aAdd.className = "uwt-listview-row-add";
		aAdd.href = "#";
		aAdd.NativeObject = this;
		aAdd.addEventListener("click", function(e)
		{
			this.NativeObject.addRowAfter(this.parentElement);

			e.preventDefault();
			e.stopPropagation();
			return false;
		});
		td.appendChild(aAdd);

		var aRemove = document.createElement("a");
		aRemove.className = "uwt-listview-row-remove";
		aRemove.href = "#";
		aRemove.NativeObject = this;
		aRemove.addEventListener("click", function(e)
		{
			this.NativeObject.removeRow(this.parentElement.parentElement);

			e.preventDefault();
			e.stopPropagation();
			return false;
		});
		td.appendChild(aRemove);

		return td;
	};
}

window.addEventListener("load", function()
{
	var items = document.getElementsByClassName("mcx-element");
	for (var i = 0; i < items.length; i++)
	{
		if (items[i].tagName === "TABLE" && System.ClassList.Contains(items[i], "uwt-listview"))
		{
			items[i].McxElementListView = new McxElementListView(items[i]);
		}
	}
});