<% local view, 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">
	if (typeof $.tablesorter == 'undefined') {
		document.write('<script type="text/javascript" src="<%= html.html_escape(page_info.wwwprefix) %>/js/jquery.tablesorter.js"><\/script>');
		document.write('<script type="text/javascript" src="<%= html.html_escape(page_info.wwwprefix) %>/js/jquery.tablesorter.widgets.js"><\/script>');
		document.write('<link href="<%= html.html_escape(page_info.wwwprefix..page_info.staticdir) %>/tablesorter/jquery.tablesorter.pager.css" rel="stylesheet">');
		document.write('<script type="text/javascript" src="<%= html.html_escape(page_info.wwwprefix) %>/js/widgets/widget-pager.js"><\/script>');
	}
</script>

<script type="text/javascript">
<% -- Since we're including a submission of searchdevices, we need to overcome the automatic redirect
	if session.searchdevicesresult then
		-- Use JavaScript to redirect to the searchdevices page
%>
		window.location.assign("<%= html.html_escape(page_info.script..page_info.prefix..page_info.controller) %>/searchdevices");
<%
	end
	
	-- Since we're including a submission of createdevicefromrequest, we need to overcome the automatic redirect
	if session.createdevicefromrequestresult and not session.createdevicefromrequestresult.errtxt then
		local tmp = session.createdevicefromrequestresult
		session.createdevicefromrequestresult = nil
		-- Use JavaScript to redirect to the edit page
%>
		window.location.assign("<%= html.html_escape(page_info.script..page_info.prefix..page_info.controller) %>/<% if viewlibrary.check_permission("editdevice") then io.write("editdevice") elseif viewlibrary.check_permission("overridedeviceparams") then io.write("overridedeviceparams") else io.write("editdeviceparams") end %>?device_id=<%= tmp.value.device_id.value %>&redir=<%= html.html_escape(page_info.orig_action) %>");
<%
	elseif session.createdevicefromrequestresult then
		-- Use JavaScript to redirect to the createdevicefromrequest page
%>
		window.location.assign("<%= html.html_escape(page_info.script..page_info.prefix..page_info.controller) %>/createdevicefromrequest");
<%
	end
%>

        $(document).ready(function() {
		// The following is a hack to include a multiline string
		var MultiString = function(f) {
			return f.toString().split('\n').slice(1, -1).join('\n');
		}
		<% local mac = cfe({ type="hidden", value="REPLACEME" }) %>
		var actions = MultiString(function() {/**
		<%
			if viewlibrary.check_permission("deleterequest") then
				htmlviewfunctions.displayitem(cfe({type="form", value={mac=mac}, label="", option="Delete", action="deleterequest", class="deleterequest" }), page_info, -1)
			end
		%>
		**/});
		var foundactions = MultiString(function() {/**
		<%
			if viewlibrary.check_permission("searchdevices") then
				htmlviewfunctions.displayitem(cfe({type="form", value={id=cfe({type="hidden", value="device_id"}), value=cfe({type="hidden", value="REPLACEME"})}, label="", option="Search", action="searchdevices" }), page_info, -1)
			end
		%>
		**/});
		var missingactions = MultiString(function() {/**
		<%
			if viewlibrary.check_permission("createdevicefromrequest") then
				htmlviewfunctions.displayitem(cfe({type="form", value={mac=mac}, label="", option="Create", action="createdevicefromrequest" }), page_info, -1)
			end
		%>
		**/});

                $("#list").tablesorter({headers: {1:{sorter:'digit'}, 3:{sorter:'ipAddress'}}, widgets: ['zebra', 'filter', 'pager'], widgetOptions: {
			// Filtering is handled by the server
			filter_serversideFiltering: true,
		
			// We can put the page number and size here, filtering and sorting handled by pager_customAjaxUrl
			pager_ajaxUrl : '<%= html.html_escape(page_info.script .. page_info.orig_action) %>?viewtype=json&page={page+1}&pagesize={size}',
			
			// Modify the url after all processing has been applied to handle filtering and sorting
			pager_customAjaxUrl: function(table, url) {
				var columns = ["action", "date", "mac", "ip", "agent", "device_id"];
				var directions = ["asc", "desc"];
				for (var s=0; s<table.config.sortList.length; s++) {
					// 0=column number, 1=direction(0 is asc)
					if ((table.config.sortList[s][0] < columns.length) && (table.config.sortList[s][1] < directions.length)) {
						url += "&orderby."+(s+1)+".column="+columns[table.config.sortList[s][0]]+"&orderby."+(s+1)+".direction="+directions[table.config.sortList[s][1]]
					}
				}
				for (var f=0; f<table.config.pager.currentFilters.length; f++) {
					var filter = table.config.pager.currentFilters[f];
					if (filter.trim()) {
						url += "&filter."+columns[f]+"="+encodeURIComponent(filter.trim());
					}
				}
				return url;
			},
			
			// process ajax so that the following information is returned:
			// [ total_rows (number), rows (array of arrays), headers (array; optional) ]
			pager_ajaxProcessing: function(data){
				if (data && data.value && data.value.result) {
					rows = [];
					for ( r=0; r<data.value.result.value.length; r++) {
						row=[];
						if (data.value.result.value[r].device_id != null) {
							row[0] = actions.replace(/REPLACEME/g, data.value.result.value[r].mac) + foundactions.replace(/REPLACEME/g, data.value.result.value[r].device_id);
						} else {
							row[0] = actions.replace(/REPLACEME/g, data.value.result.value[r].mac) + missingactions.replace(/REPLACEME/g, data.value.result.value[r].mac);
						}
						row[1] = '<span class="hide">'+Date.UTC(data.value.result.value[r].date)+'</span>'+data.value.result.value[r].date;
						row[2] = data.value.result.value[r].mac;
						row[3] = data.value.result.value[r].ip;
						row[4] = data.value.result.value[r].agent;
						row[5] = data.value.result.value[r].device_id;
						rows.push(row);
					}
					return [ parseInt(data.value.rowcount.value), rows];
				}
			}
		}})
		.bind('pagerComplete', function(e, c){
			$(".deleterequest").click(function(){ return confirm("Are you sure you want to delete this request?")});
		});
        });
</script>

<% htmlviewfunctions.displaycommandresults({"deleterequest", "editdevice"}, session) %>

<% local header_level = htmlviewfunctions.displaysectionstart(cfe({label="Requests"}), page_info) %>
<table id="list" class="tablesorter"><thead>
	<tr>
		<th class="filter-false remove sorter-false">Action</th>
		<th class="filter-false">Timestamp</th>
		<th>MAC Address</th>
		<th>IP Address</th>
		<th>User Agent</th>
		<th>Device ID</th>
	</tr>		
</thead><tbody>
</tbody>
</table>

<div id="pager" class="pager">
	<form>
		Page: <select class="gotoPage"></select>
		<img src="<%= html.html_escape(page_info.wwwprefix..page_info.staticdir) %>/tablesorter/first.png" class="first"/>
		<img src="<%= html.html_escape(page_info.wwwprefix..page_info.staticdir) %>/tablesorter/prev.png" class="prev"/>
		<span class="pagedisplay"></span> <!-- this can be any element, including an input -->
		<img src="<%= html.html_escape(page_info.wwwprefix..page_info.staticdir) %>/tablesorter/next.png" class="next"/>
		<img src="<%= html.html_escape(page_info.wwwprefix..page_info.staticdir) %>/tablesorter/last.png" class="last"/>
		<select class="pagesize">
			<option selected="selected" value="10">10</option>
			<option value="20">20</option>
			<option value="30">30</option>
			<option value="40">40</option>
		</select>
	</form>
</div>

<% htmlviewfunctions.displaysectionend(header_level) %>
