function McxPrimarySearch(parentElement)
{
	this.ParentElement = parentElement;
	this.FormElement = this.ParentElement.children[0];
	this.TextBoxElement = this.FormElement.children[0];
	this.PopupElement = this.ParentElement.children[1];
	this.MenuElement = this.PopupElement.children[0];

	this.clearSearchResults = function()
	{
		while (this.MenuElement.children.length > 0)
		{
			this.MenuElement.children[0].remove();
		}
	};

	this.search = function(query)
	{
		var xhr = new XMLHttpRequest();
		var searchUrl = System.ExpandRelativePath("~/" + System.TenantName + "/search.htmld?q=" + encodeURIComponent(query));
		/*
		if (this.ParentElement.hasAttribute("data-valid-class-ids"))
		{
			searchUrl += "&validClassIds=" + this.ParentElement.getAttribute("data-valid-class-ids");
		}
		*/
		xhr.open("GET", searchUrl, true);
		xhr.NativeObject = this;
		xhr.onreadystatechange = function()
		{
			if (this.readyState === 4)
			{
				var resultsText = this.responseText;
				var json = JSON.parse(resultsText);
				if (json.result === "success")
				{
					this.NativeObject.clearSearchResults();

					for (var i = 0; i < json.items.length; i++)
					{
						var li = document.createElement("li");
						li.className = "uwt-menu-item uwt-menu-item-command uwt-visible";
						li.searchResult = json.items[i];
						li.NativeObject = this.NativeObject;
						li.addEventListener("click", function()
						{
							if (this.NativeObject.activateSearchResult(this.searchResult))
							{
								this.NativeObject.setEditing(false);
							}
						});

						var span = document.createElement("span");
						span.className = "uwt-title uwt-description-empty";
						span.innerText = json.items[i].title;
						li.appendChild(span);

						this.NativeObject.MenuElement.appendChild(li);
					}

					System.ClassList.Remove(this.NativeObject.PopupElement, "uwt-loading");
				}
				else
				{
					if (json.responseCode === 403)
					{
						Alert.show("Please log in to continue", "Not Authorized", "uwt-color-danger");
					}
					System.ClassList.Remove(this.NativeObject.PopupElement, "uwt-loading");
				}
			}
		};
		xhr.send(null);
	};

	this.TextBoxElement.NativeObject = this;
	this.TextBoxElement.addEventListener("keydown", function(e)
	{
		this.NativeObject.search(this.value);
	});
}

window.addEventListener("load", function()
{
	var primarySearch = document.getElementsByClassName("uwt-searchbar");
	primarySearch[0].NativeObject = new McxPrimarySearch(primarySearch[0]);
});
