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

<% -- Pregenerate the list of users
local useroptions = {{value="", label=""}}
if viewlibrary.check_permission("listusers") and (viewlibrary.check_permission("forwardmessage") or viewlibrary.check_permission("forwardmymessage")) then
	local users = viewlibrary.dispatch_component("listusers", nil, true)
	for i,v in ipairs(users.value) do
		v.firstname = v.firstname or ""
		v.lastname = v.lastname or ""
		v.username = v.username or ""
	end
	table.sort(users.value, function(a,b) if a.firstname ~= b.firstname then return a.firstname < b.firstname elseif a.lastname ~= b.lastname then return a.lastname < b.lastname else return a.username < b.username end end)
	for i,u in ipairs(users.value) do
		if u.username ~= session.userinfo.userid then
			useroptions[#useroptions+1] = {value=u.username, label=u.firstname..' '..u.lastname..' ('..u.username..')'}
		end
	end
end
%>
<% -- Pregenerate the list of folders
local reversefolders = {}
local folderoptions = {{value="", label=""}}
local dontmove=false
if viewlibrary.check_permission("listfolders") then
	local folders = viewlibrary.dispatch_component("listfolders", nil, true)
	for i,u in ipairs(folders.value) do
		reversefolders[u.in_folder] = u.label
	end
	if (viewlibrary.check_permission("movemessage") or viewlibrary.check_permission("movemymessage")) then
		if #folders.value <= 1 then
			dontmove = true
		end
		for i,u in ipairs(folders.value) do
			folderoptions[#folderoptions+1] = {value=u.in_folder, label=u.label}
		end
	end
end
%>
<% -- Figure out the callback number
local callmenumber = nil
if viewlibrary.check_permission("editmyusersettings") and viewlibrary.check_permission("callbackmymessage") then
	local settings = viewlibrary.dispatch_component("editmyusersettings", nil, true)
	if settings and settings.value and settings.value.callmenumber then
		callmenumber = settings.value.callmenumber.value
	end
end
%>

<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>');
	}
</script>

<script type="text/javascript">
	<% -- Browser detect script from http://www.quirksmode.org/js/detect.html %>
	var BrowserDetect = {
		init: function () {
			this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
			this.version = this.searchVersion(navigator.userAgent)
				|| this.searchVersion(navigator.appVersion)
				|| "an unknown version";
			this.OS = this.searchString(this.dataOS) || "an unknown OS";
		},
		searchString: function (data) {
			for (var i=0;i<data.length;i++)	{
				var dataString = data[i].string;
				var dataProp = data[i].prop;
				this.versionSearchString = data[i].versionSearch || data[i].identity;
				if (dataString) {
					if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
				}
				else if (dataProp)
					return data[i].identity;
			}
		},
		searchVersion: function (dataString) {
			var index = dataString.indexOf(this.versionSearchString);
			if (index == -1) return;
			return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
		},
		dataBrowser: [
			{
				string: navigator.userAgent,
				subString: "Chrome",
				identity: "Chrome"
			},
			{ 	string: navigator.userAgent,
				subString: "OmniWeb",
				versionSearch: "OmniWeb/",
				identity: "OmniWeb"
			},
			{
				string: navigator.vendor,
				subString: "Apple",
				identity: "Safari",
				versionSearch: "Version"
			},
			{
				prop: window.opera,
				identity: "Opera"
			},
			{
				string: navigator.vendor,
				subString: "iCab",
				identity: "iCab"
			},
			{
				string: navigator.vendor,
				subString: "KDE",
				identity: "Konqueror"
			},
			{
				string: navigator.userAgent,
				subString: "Firefox",
				identity: "Firefox"
			},
			{
				string: navigator.vendor,
				subString: "Camino",
				identity: "Camino"
			},
			{		// for newer Netscapes (6+)
				string: navigator.userAgent,
				subString: "Netscape",
				identity: "Netscape"
			},
			{
				string: navigator.userAgent,
				subString: "MSIE",
				identity: "Explorer",
				versionSearch: "MSIE"
			},
			{
				string: navigator.userAgent,
				subString: "Gecko",
				identity: "Mozilla",
				versionSearch: "rv"
			},
			{ 		// for older Netscapes (4-)
				string: navigator.userAgent,
				subString: "Mozilla",
				identity: "Netscape",
				versionSearch: "Mozilla"
			}
		],
		dataOS : [
			{
				string: navigator.platform,
				subString: "Win",
				identity: "Windows"
			},
			{
				string: navigator.platform,
				subString: "Mac",
				identity: "Mac"
			},
			{
				string: navigator.userAgent,
				subString: "iPhone",
				identity: "iPhone/iPod"
			},
			{
				string: navigator.platform,
				subString: "Linux",
				identity: "Linux"
			}
		]
	};
	BrowserDetect.init();

	function PlayMessage() {
		$(".temporaryplayer").remove();
		if ( BrowserDetect.browser == "Safari" ) {
			$(this).parent().parent().after("<tr class='temporaryplayer'><td colspan='9'><object type='audio/x-wav' data='" + $(this).attr("href") + "' width='100%' height='25'><param name='src' value='" + $(this).attr("href") + "'> <param name='autoplay' value='true'> <param name='autoStart' value='1'> </object></td></tr>");
		} else {
			$(this).parent().parent().after("<tr class='temporaryplayer'><td colspan='9'><embed width='100%' height='25px' autostart='1' playcount='1' src='" + $(this).attr("href") + "' type='application/x-mplayer2'></embed></td></tr>");
		};
		return false;
	}
	function HandleMulti() {
		var messages = [];
		$(".multicheck:checked").each(function(){
			messages[messages.length] = this.value;
		});
		$(this).parent().find("[name='message']").attr("value", messages.join(","));
	}
        $(document).ready(function() {
                $("#list").tablesorter({headers: {0:{sorter: false}, 1:{sorter: false}}, widgets: ['zebra']});
		$("#list").bind("sortStart",function() {
			$(".temporaryplayer").remove();
		});
		$(".playmessage").click(PlayMessage);
<% if viewlibrary.check_permission("deletemessage") or viewlibrary.check_permission("deletemymessage") then %>
		$(".multidelete").click(HandleMulti);
<% end %>
<% if viewlibrary.check_permission("forwardmessage") or viewlibrary.check_permission("forwardmymessage") then %>
		$(".multiforward").click(HandleMulti);
<% end %>
<% if viewlibrary.check_permission("emailmessage") or viewlibrary.check_permission("emailmymessage") then %>
		$(".multiemail").click(HandleMulti);
<% end %>
<% if viewlibrary.check_permission("movemessage") or viewlibrary.check_permission("movemymessage") then %>
		$(".multimove").click(HandleMulti);
<% end %>
        });
</script>

<% htmlviewfunctions.displaycommandresults({"deletemessage", "deletemymessage", "forwardmessage", "forwardmymessage", "emailmessage", "emailmymessage", "movemessage", "movemymessage", "callbackmessage", "callbackmymessage"}, session) %>

<% local header_level = htmlviewfunctions.displaysectionstart(view, page_info) %>
<table><tr><td>
<% local message = cfe({type="hidden"}) %>
<% if viewlibrary.check_permission("deletemessage") or viewlibrary.check_permission("deletemymessage") then
	local form = cfe({type="form", value={message=message}, label="", option="Delete", action="deletemymessage", class="multidelete" })
	if viewlibrary.check_permission("deletemessage") then form.action = "deletemessage" end
	htmlviewfunctions.displayitem(form, page_info, -1)
end
if viewlibrary.check_permission("forwardmessage") or viewlibrary.check_permission("forwardmymessage") then
	local form = cfe({type="form", value={message=message}, label="", option="Forward", action="forwardmymessage", class="multiforward" })
	if viewlibrary.check_permission("forwardmessage") then form.action = "forwardmessage" end
	form.value.newuser = cfe({type="select", option=useroptions})
	htmlviewfunctions.displayitem(form, page_info, -1)
end
if viewlibrary.check_permission("emailmessage") or viewlibrary.check_permission("emailmymessage") then
	local form = cfe({type="form", value={message=message}, label="", option="E-mail", action="emailmymessage", class="multiemail" })
	if viewlibrary.check_permission("emailmessage") then form.action = "emailmessage" end
	form.value.address = cfe({})
	htmlviewfunctions.displayitem(form, page_info, -1)
end
if viewlibrary.check_permission("movemessage") or viewlibrary.check_permission("movemymessage") then
	if not dontmove then
		local form = cfe({type="form", value={message=message}, label="", option="Move", action="movemymessage", class="multimove" })
		if viewlibrary.check_permission("movemessage") then form.action = "movemessage" end
		form.value.newfolder = cfe({type="select", option=folderoptions})
		htmlviewfunctions.displayitem(form, page_info, -1)
	end
end %>
</td></tr></table>
<table><tr><td>
<small>select: </small>
<small><a href='' OnClick='$(".multicheck").attr("checked", "true"); return false;'>all</a></small>
<small><a href='' OnClick='$(".multicheck").removeAttr("checked"); return false;'>none</a></small>
</td></tr></table>

<table id="list" class="tablesorter"><thead>
	<tr>
		<th></th>
		<th>Action</th>
		<th>Date</th>
		<th>Time</th>
		<th>Caller ID</th>
		<th>Priority</th>
		<th>Orig Mailbox</th>
		<th>Folder</th>
		<th>Duration</th>
	</tr>		
</thead><tbody>
<% local message = cfe({ type="hidden" }) %>
<% local viewtype = cfe({ type="hidden", value="stream" }) %>
<% local extension = cfe({ type="hidden", value=callmenumber }) %>
<% for k,v in ipairs( view.value ) do %>
	<tr>
		<td><input type=checkbox class="multicheck" value="<%= html.html_escape(v.uuid) %>"></td>
		<td>
		<% message.value = v.uuid %>
		<% if viewlibrary.check_permission("downloadmessage") then %>
			<% htmlviewfunctions.displayitem(cfe({type="link", value={message=message, viewtype=viewtype}, label="", option="Download", action="downloadmessage"}), page_info, -1) %>
			<% htmlviewfunctions.displayitem(cfe({type="link", value={message=message, viewtype=viewtype}, label="", option="Play", action="downloadmessage", class="playmessage"}), page_info, -1) %>
		<% elseif viewlibrary.check_permission("downloadmymessage") then %>
			<% htmlviewfunctions.displayitem(cfe({type="link", value={message=message, viewtype=viewtype}, label="", option="Download", action="downloadmymessage"}), page_info, -1) %>
			<% htmlviewfunctions.displayitem(cfe({type="link", value={message=message, viewtype=viewtype}, label="", option="Play", action="downloadmymessage", class="playmessage"}), page_info, -1) %>
		<% end %>
		<% if callmenumber then %>
			<% htmlviewfunctions.displayitem(cfe({type="form", value={message=message, extension=extension}, label="", option="CallMe", action="callbackmymessage"}), page_info, -1) %>
		<% end %>
		</td>
                <td><%= html.html_escape(os.date("%x", v.created_epoch)) %></td>
                <td><%= html.html_escape(os.date("%X", v.created_epoch)) %></td>
                <td><%= html.html_escape(v.cid_number) %></td>
                <td><%= html.html_escape(v.read_flags) %></td>
                <td><%= html.html_escape(v.username) %></td>
                <td><%= html.html_escape(reversefolders[v.in_folder] or v.in_folder) %></td>
                <td><%= html.html_escape(v.message_len) %></td>
	</tr>
<% end %>
</tbody>
</table>

<% if view.errtxt then %>
<p class="error"><%= html.html_escape(view.errtxt) %></p>
<% end %>
<% if #view.value == 0 then %>
<p>No messages found</p>
<% end %>
<% htmlviewfunctions.displaysectionend(header_level) %>
