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

<% local domain = string.gsub(form.value.filename.value, "^.*/", "") %>
<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">
	var editEntry = '<td> \
		<a href="javascript:;"><img src="<%= html.html_escape(page_info.wwwprefix..page_info.staticdir) %>/tango/16x16/actions/list-add.png" width="16" height="16" title="Insert record"></a> \
		<a href="javascript:;"><img src="<%= html.html_escape(page_info.wwwprefix..page_info.staticdir) %>/tango/16x16/actions/list-remove.png" width="16" height="16" title="Remove record"></a> \
		<a href="javascript:;"><img src="<%= html.html_escape(page_info.wwwprefix..page_info.staticdir) %>/tango/16x16/actions/document-properties.png" width="16" height="16" title="Edit record"></a> \
		</td>';
	var addEntry = '<tr><td> \
		<a href="javascript:;"><img src="<%= html.html_escape(page_info.wwwprefix..page_info.staticdir) %>/tango/16x16/actions/list-add.png" width="16" height="16" title="Insert record"></a> \
		</td></tr>';
	<% local replaceableItem = cfe({label="ReplaceLabel", value="ReplaceValue", name="ReplaceName", descr="ReplaceExtra"}) %>
	var replaceableEntry = '<% htmlviewfunctions.displayformitem(replaceableItem) %>';

	function Entry(entryType,descr,num,descr0,descr1,descr2,descr3,descr4,descr5,descr6,descr7,descr8,descr9,descr10){
		this.entryType=entryType;
		this.descr=descr;
		this.num=num;this.descriptions=new Array(11);
		this.descriptions[0]=descr0;this.descriptions[1]=descr1;this.descriptions[2]=descr2;this.descriptions[3]=descr3;this.descriptions[4]=descr4;this.descriptions[5]=descr5;this.descriptions[6]=descr6;this.descriptions[7]=descr7;this.descriptions[8]=descr8;this.descriptions[9]=descr9;this.descriptions[10]=descr10;
	}

	var entryTypes = new Array(14);
	entryTypes[0]=new Entry("#","Comment line",1,"Comment");
	entryTypes[1]=new Entry(".","Name server",6,"Domain","IP address","Name server","Time to live","Timestamp","Location");
	entryTypes[2]=new Entry("&","Delegate subdomain",6,"Domain","IP address","Name server","Time to live","Timestamp","Location");
	entryTypes[3]=new Entry("=","Host",5,"Host","IP address","Time to live","Timestamp","Location");
	entryTypes[4]=new Entry("+","Host",5,"Host","IP address","Time to live","Timestamp","Location");
	entryTypes[5]=new Entry("@","Mail exchanger",7,"Domain","IP address","Mail exchanger","Distance","Time to live","Timestamp","Location"); 
	entryTypes[6]=new Entry("'","Text record",5,"Domain","Text Record","Time to live","Timestamp","Location");
	entryTypes[7]=new Entry("^","Reverse record",5,"PTR","Domain name","Time to live","Timestamp","Location");
	entryTypes[8]=new Entry("C","Canonical name",5,"Domain","Canonical name","Time to live","Timestamp","Location");
	entryTypes[9]=new Entry("Z","SOA record",11,"Domain","Primary name server","Contact address","Serial number","Refresh time","Retry time","Expire time","Minimum time","Time to live","Timestamp","Location");
	entryTypes[10]=new Entry(":","Generic record",6,"Domain","Record type","Record data","Time to live","Timestamp","Location");
	entryTypes[11]=new Entry("%","Client location",2,"Location","IP prefix");
	entryTypes[12]=new Entry("S","Service location",8,"Domain Service", "IP address", "Server", "Port", "Weight", "Priority", "Time to live", "Timestamp");
	entryTypes[13]=new Entry("N","Naming authority pointer",9,"Domain", "Order", "Preference", "Flags", "Service", "Regular expression", "Replacement", "Time to live", "Timestamp");

	function octal_to_char(val){
		return String.fromCharCode(parseInt(val.substring(1), 8))
	}
	function char_to_octal(val){
		var code = "000" + val.charCodeAt(0).toString(8)
		return "\\" + code.slice(-3)
	}
	function finishForm(entry, force){
		var addresspresent = false;
		var notindomain = false;
		var entrytext = entry.find("select").val() + entry.find("input:not(.submit)").map(function(){
			var val = $(this).val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
			if (this.name != "dontconvertme") {
				val = val.replace(/[\\:\r\n ]/g, char_to_octal);
			}
			if (this.name == "fixme") {
				if (val != "")
					val = val + ".<%= html.html_escape(domain) %>";
				else
					val = "<%= html.html_escape(domain) %>";
			}
			if (this.name == "address" && val != "")
				addresspresent = true;
			if (this.name == "testme" && val != "" && null == val.match(/\.?<%= string.gsub(html.html_escape(domain), "[\\%[%]%.%*%?%+%{%^%$]", "\\%1") %>$/i))
				notindomain = true;
			return val
		}).get().join(":");
		// Clean up blank comments
		if ("#" == entrytext) {
			entrytext = "";
		}
		if (addresspresent && notindomain) {
			if (force)
				entry.empty().append(entrytext);
			return false;
		}
		else
			entry.empty().append(entrytext);
		return true;
	}
	function createForm(entry){
		var entrytext = entry.text();
		var entryType = null;
		var form = '<select>';
		var typechar = entrytext.charAt(0);
		if (typechar === null) { typechar = ""; }
		for (i=0; i<14; i++) {
			form = form + '<option ';
			if (typechar == entryTypes[i].entryType){
				entryType=entryTypes[i];
				form = form + 'selected ';
			}
			form = form + 'value="' + entryTypes[i].entryType + '">' + entryTypes[i].descr + '</option>';
		}
		form = form + "</select><br><dl>";
		var entries;
		if (null == entryType){
			// Invalid type, use Comment type
			entryType = entryTypes[0];
			entries = new Array(1);
			entries[0] = entrytext;
		} else {
			entrytext = entrytext.substring(1,entrytext.length) + "::::::::::";
			entries = entrytext.split(":");
		}
		for (i=0; i<entryType.num; i++){
			if (entries[i] === null) { entries[i] = ""; }
			var name = "";
			var value = entries[i];
			var extra = "";
			if (entryType.descriptions[i] == "Comment")
				name = "dontconvertme"
			else {
				value = value.replace(/\\\d{3}/g, octal_to_char);
				if (entryType.descriptions[i] == "Domain" || entryType.descriptions[i] == "Host" || entryType.descriptions[i] == "Domain Service" ) {
					name = "fixme";
					value = value.replace(/\.?<%= string.gsub(html.html_escape(domain), "[\\%[%]%.%*%?%+%{%^%$]", "\\%1") %>$/i, "")
					extra = " . <%= html.html_escape(domain) %>"
				}
				else if (entryType.descriptions[i] == "IP address")
					name = "address";
				else if (entryType.descriptions[i] == "Name server" || entryType.descriptions[i] == "Mail exchanger" || entryType.descriptions[i] == "Server")
					name = "testme";

			}
			form = form + replaceableEntry.replace(/ReplaceLabel/g, entryType.descriptions[i]).replace(/ReplaceValue/g, value).replace(/ReplaceName/g, name).replace(/ReplaceExtra/g, extra);
		}
		form = form + "\n</dl>";
		entry.empty().append(form);
		entry.find("select").change(function(){
			var entry = $(this).parent();
			finishForm(entry, true);
			createForm(entry);
		});
		entry.find("input.submit").click(function() {
			$("input[name='<%= html.html_escape(form.option) %>']").click();
		});
	}
	function editLine(){
		var parent = $(this).parent();
		if (parent.is("td")) {
			parent = parent.parent();
		}
		var entry = parent.find("td:eq(1)");
		if (entry.find("select").is("select")){
			if ( ! finishForm(entry) )
				alert("Error: Cannot set IP address for host outside of <%= html.html_escape(domain) %> domain");
		} else {
			createForm(entry);
		}
	}
	function deleteLine(){
		$(this).parent().parent().replaceWith();
	}
	function addLine(){
		addLinks($(this).parent().parent().before('<tr><td></td></tr>').prev());
	}
	function addLinks(rows){
		rows.each(function(){
			$(this).prepend(editEntry);
			$(this).find("td > a:eq(0)").click(addLine);
			$(this).find("td > a:eq(1)").click(deleteLine);
			$(this).find("td > a:eq(2)").click(editLine);
			$(this).find("td:eq(1)").dblclick(editLine);
		});
	}
	function submitFile(){
		var success = true;
		var file = "";
		var lines = $("#entries").find("tr").find("td:eq(1)");
		lines.each(function(){
			var elem = jQuery(this);
			if (elem.find("select").is("select")){
				success = finishForm(elem) && success;
			}
			file = file + elem.text() + "\n";
		});
		$("input[name='filecontent']").val(file);
		if ( ! success ) {
			alert("Error: Cannot set IP address for host outside of <%= html.html_escape(domain) %> domain");
			return false;
		}
	}

	$(function(){
		addLinks($("#entries").find("tr"));
		$("#entries").append(addEntry).find("a:last").click(addLine);
		$("form").submit(submitFile);
		<% if form.value.filecontent.linenumber then %>
			$("#entries tr:eq(<%= form.value.filecontent.linenumber - 1 %>)").find("a:eq(2)").click();
			var top = $("#entries tr:eq(<%= form.value.filecontent.linenumber - 1 %>)").offset().top;
			$("html,body").scrollTop(top);
		<% end %>
	});
</script>

<%
local header_level0, header_level, header_level2
if form.type == "form" then
	header_level0 = htmlviewfunctions.displaysectionstart(cfe({label="Configuration"}), page_info)
	header_level = htmlviewfunctions.displaysectionstart(cfe({label="Expert Configuration"}), page_info, htmlviewfunctions.incrementheader(header_level0))
else
	header_level = htmlviewfunctions.displaysectionstart(cfe({label="View File"}), page_info)
end
header_level2 = htmlviewfunctions.displaysectionstart(cfe({label="File Details"}), page_info, htmlviewfunctions.incrementheader(header_level))

htmlviewfunctions.displayitem(form.value.filename)
htmlviewfunctions.displayitem(form.value.size)
htmlviewfunctions.displayitem(form.value.mtime)
if form.value.grep and form.value.grep.value and form.value.grep.value ~= "" then
	htmlviewfunctions.displayitem(form.value.grep)
end

htmlviewfunctions.displaysectionend(header_level2)

htmlviewfunctions.displaysectionstart(cfe({label="File Entries"}), page_info, header_level2)
if form.type == "form" then
	htmlviewfunctions.displayformstart(form, page_info)
	form.value.filename.type = "hidden"
	htmlviewfunctions.displayformitem(form.value.filename, "filename")
	form.value.filecontent.type = "hidden"
	htmlviewfunctions.displayformitem(form.value.filecontent, "filecontent")
end
%>
<table id="entries">
<% for line in string.gmatch(html.html_escape(form.value.filecontent.value), "([^\n]*)\n?") do %>
	<tr>
	<td><%= line %></td>
	</tr>
<% end %>
</table>
<%
htmlviewfunctions.displayinfo(form.value.filecontent)

if form.type == "form" then
	htmlviewfunctions.displayformend(form)
end
htmlviewfunctions.displaysectionend(header_level2)

htmlviewfunctions.displaysectionend(header_level)
if form.type == "form" then
	htmlviewfunctions.displaysectionend(header_level0)
end
%>
