<%#
 Copyright (C) 2017 Jian Chang <aa65535@live.com>
 Licensed to the public under the GNU General Public License v3.
-%>

<%+cbi/valueheader%>

<%-
	local values = self:formvalue(section)
	if not values then
		values = self:cfgvalue(section) or {self.default}
	end

	local function serialize_json(x, cb)
		local rv, push = nil, cb
		if not push then
			rv = { }
			push = function(tok) rv[#rv+1] = tok end
		end

		if x == nil then
			push("null")
		elseif type(x) == "table" then
			push("[")
			for k = 1, #x do
				if k > 1 then
					push(",")
				end
				serialize_json(x[k], push)
			end
			push("]")
		else
			push('"%s"' % tostring(x):gsub('["%z\1-\31\\]',
				function(c) return '\\u%04x' % c:byte(1) end))
		end

		if not cb then
			return table.concat(rv, "")
		end
	end
-%>

<div<%=attr("id", cbid .. ".value.field")%>></div>
<script type="text/javascript">//<![CDATA[
	(function() {
		var values = <%=serialize_json(values)%>;
		var keylist = <%=serialize_json(self.keylist)%>;
		var vallist = <%=serialize_json(self.vallist)%>;
		var parent = document.getElementById("<%=cbid%>.value.field");

		var dynamiclist_cbi_init = function() {
			while (parent.firstChild) {
				parent.removeChild(parent.firstChild);
			}

			for (var i = 0; i < values.length; i++) {
				var sel = document.createElement("select");
				sel.id = "<%=cbid%>." + (i + 1);
				sel.name = "<%=cbid%>";
				sel.index = i;
				sel.className = "cbi-input-select";
				sel.onchange = function() {
					values[this.index] = this.value;
				};
				parent.appendChild(sel);

				for (var j = 0; j < keylist.length; j++) {
					var opt = document.createElement("option");
					opt.value = keylist[j];
					if (opt.value == values[i]) {
						opt.selected = "selected";
					}
					opt.appendChild(document.createTextNode(vallist[j]));
					sel.appendChild(opt);
				}

				var btn = document.createElement('img');
				btn.src = "<%=resource%>" + ((i + 1) < values.length ? "/cbi/remove.gif" : "/cbi/add.gif");
				btn.index = i;
				btn.className = 'cbi-image-button';
				btn.onclick = function() {
					if (this.src.indexOf('remove') > -1) {
						values.splice(this.index, 1);
					} else {
						values.push("<%=self.default%>");
					}
					dynamiclist_cbi_init();
					return false;
				};
				parent.appendChild(btn);
				parent.appendChild(document.createElement('br'));
			}
		};
		dynamiclist_cbi_init();
	}());
//]]></script>

<%+cbi/valuefooter%>
