<% local form, viewlibrary, page_info, session = ... %>
<% htmlviewfunctions = require("htmlviewfunctions") %>
<% html = require("acf.html") %>

<script type="text/javascript">
	if (typeof jQuery == 'undefined') {
		document.write('<script type="text/javascript" src="<%= html.html_escape(page_info.wwwprefix) %>/js/jquery-latest.js"><\/script>');
	}
</script>

<script type="text/javascript">
	function checkboxChanged(){
		if ($(this).is(':checked')) {
			$(this).siblings(":input").prop('disabled', true);
		} else {
			$(this).siblings(":input").prop('disabled', false);
		}
	}
	$(document).ready(function() {
		$(".nulls:checked").each(checkboxChanged);
		$(".defaults:checked").each(checkboxChanged);
		$(".nulls").change(checkboxChanged);
		$(".defaults").change(checkboxChanged);
	});
</script>

<%
local header_level = htmlviewfunctions.displaysectionstart(form, page_info)
local header_level2 = htmlviewfunctions.incrementheader(header_level)
htmlviewfunctions.displayformstart(form, page_info)
htmlviewfunctions.displayformitem(form.value.connection, "connection", header_level2)
htmlviewfunctions.displayformitem(form.value.table, "table", header_level2)
htmlviewfunctions.displaysectionstart(form.value.fields, nil, header_level2)
htmlviewfunctions.displayinfo(form.value.fields)

local order = {}
local tmporder = {}
for name,item in pairs(form.value.fields.value) do
	if tonumber(item.seq) then
		tmporder[#tmporder+1] = {seq=tonumber(item.seq), name=name}
	end
end
if #tmporder>0 then
	table.sort(tmporder, function(a,b) if a.seq ~= b.seq then return a.seq < b.seq else return a.name < b.name end end)
	for i,val in ipairs(tmporder) do
		order[#order+1] = val.name
	end
end
for x,name in ipairs(order) do
	--htmlviewfunctions.displayformitem(form.value.fields.value[name], name, header_level2, "fields")
	local myitem = form.value.fields.value[name]
	-- Set the id so the label 'for' can point to it
	myitem.id = "fields."..name
	header_level = htmlviewfunctions.displayitemstart(myitem, nil, header_level2)
	if 0 <= header_level then
		io.write(html.html_escape(myitem.label))
	end
	htmlviewfunctions.displayitemmiddle(myitem, nil, header_level2)
	htmlviewfunctions.displayformitem(myitem, name, -1, "fields")
	if not myitem.readonly and form.value.defaults and form.value.defaults.value[name] then
		form.value.defaults.value[name].class = "defaults"
		htmlviewfunctions.displayformitem(form.value.defaults.value[name], name, -1, "defaults")
	end
	if not myitem.readonly and form.value.nulls and form.value.nulls.value[name] then
		form.value.nulls.value[name].descr = "Null"
		form.value.nulls.value[name].class = "nulls"
		htmlviewfunctions.displayformitem(form.value.nulls.value[name], name, -1, "nulls")
	end
	htmlviewfunctions.displayitemend(myitem, nil, header_level2)
end

htmlviewfunctions.displaysectionend(header_level2)
htmlviewfunctions.displayformend(form, header_level2)
htmlviewfunctions.displaysectionend(header_level)
%>
