<%@ include file="inc_header.jsp"%>

<script type="text/javascript">
	var nextAttachmentRowId = 0
	var qirId = <c:out value="${param.qirId}" default="null" />

	$(function() {
		var theTable = $('#attachmentTable').DataTable({
			"dom" : '<"top">rt<"bottom"><"clear">',
			autowidth : true,
			searching : false,
			select : 'single',
			"language" : {
				"emptyTable" : "No attachments have been added yet."
			},
		})
		
		$("#addAttachmentButton").click(addAttachment)
		$("#viewAttachmentButton").click(viewAttachment)
		$("#deleteAttachmentButton").click(deleteAttachment)
		
		$('#attachmentTable tbody').on('click', 'tr', function() {
			var theRow = $(this)
			var theTable = $('#attachmentTable')
			theTable.removeData('selectedRowId').data('selectedRowId', theRow.data('rowId'))
			theTable.removeData('selectedAttachmentId').data('selectedAttachmentId', theRow.data('attachmentId'))
			
			refreshButtons(theRow)
		})
		// create attachtment table
		<c:forEach items="${attachmentTableInitialValues}" var="attachment"> 
		// ${fn:toLowerCase(attachment.modifiedBy)}
		// ${fn:toLowerCase(userName)}
			addAttachmentRow(${attachment.id}, new Date(<c:out value="${attachment.date.time}" />), "<c:out value="${attachment.name}" />",
				<c:out value="${attachment.length}" />,
				${fn:toLowerCase(attachment.modifiedBy) == fn:toLowerCase(userName)})
		</c:forEach>
	})

	function disableAttachmentTable() {
		$('#addAttachmentButton').hide();
		$('#deleteAttachmentButton').hide();
	}
	
	function refreshButtons(rowSelected) {
		$('#viewAttachmentButton').css("display", !rowSelected || rowSelected.data('attachmentId') == null ? "none" : "inline-block")
		if(!rowSelected){
			$('#deleteAttachmentButton').css("display", "none")
		}
		else { // row selected
			if(rowSelected.data('isCreator')){ 
				// show delete if vendor added attachment
				$('#deleteAttachmentButton').css("display", "inline-block")
			}
			else {
				$('#deleteAttachmentButton').css("display", "none")
			}
		}
	}
	
	function addAttachment() {
		var currentCombinedSize = 0
		$(".attachmentRow").each(function() {
			currentCombinedSize += $(this).data('length')
		})
		
		var fileInput = $('<input type="file" name="attachmentFiles" style="display:none" />')
		fileInput.change(function(e) {
			var files = e.currentTarget.files
			
			for (var i = 0; i < files.length; i++) {
				var file = files[i]
				
				if(file.name.indexOf(":") != -1  || file.name.indexOf("=") != -1) {
					displayAttentionDialog('<span tabindex="0">The file name you are trying to attach cannot contain : or = due to security concerns. Please attach a different file name).</span>')
		        	return
				}
		        
				var fileExtention = file.name.split('.')
				fileExtention = fileExtention[fileExtention.length - 1]
				if(fileExtention == 'txt' || fileExtention == 'html' || fileExtention == 'htm') {
					displayAttentionDialog('<span tabindex="0">The file type you are trying to attach (.txt, htm, or .html) cannot be uploaded due to security concerns. Please attach a different file type (for example; .doc, .xls or .msg, etc).</span>')
		        	return
				}
				
		        if (file.size + currentCombinedSize > 5 * 1024 * 1024) {
		        	displayAttentionDialog('<span tabindex="0">Sorry, the file you selected (combined with any other existing attachments) exceeds the 5MB limitation.</span>')
		        	return
		        }
		        
				addAttachmentRow(null, new Date(), file.name, file.size, true, fileInput)
		    }
		})
		fileInput.trigger('click')
	}
	
	function forceFocusOnTableHeader() {
		$(this).parent().focus()	
	}
	
	function viewAttachment() {
		var theTable = $('#attachmentTable')
		var attachmentId = theTable.data('selectedAttachmentId')
		if (attachmentId == null) return
		
		window.open("viewQir.html?attachmentId=" + attachmentId)
	}

	function deleteAttachment() {
		confirmDialog('Do you want to delete the attachment?', function() {
			var tableEl = $('#attachmentTable')
			var theTable = tableEl.DataTable()
			
			var selectedRowId = tableEl.data('selectedRowId')
			if (selectedRowId == null) return
			
			theTable.row($("#attachmentRow" + selectedRowId)).remove().draw()
			
			var selectedAttachmentId = tableEl.data('selectedAttachmentId')
			if (selectedAttachmentId) {
				$("#deletedAttachments").append($('<input type="hidden" name="deletedAttachments" value="' + selectedAttachmentId + '" />'))
			}
			refreshButtons()
		},
		{
			okButtonLabel : 'Yes',
			cancelButtonLabel : 'No',
			title : 'Manage QIR Attachments'
		})
	}

	function addAttachmentRow(id, date, filename, length, isCreator, optionalFileInput) {
		var tr = $('<tr class="attachmentRow" id="attachmentRow' + nextAttachmentRowId + '">')
		tr.data('rowId', nextAttachmentRowId)
		tr.data('attachmentId', id)
		tr.data('length', length)
		tr.data('isCreator', isCreator)
		
		
		$('<td nowrap>' + $.datepicker.formatDate("M d, yy", date) + '</td>')
				.appendTo(tr)
		var justFile = filename.replace(/^.*[\\\/]/, '')
		
		var td = $('<td></td>').append(justFile).appendTo(tr)
		
		if (optionalFileInput)
			optionalFileInput.appendTo(td)
		
		nextAttachmentRowId++
		$('#attachmentTable').DataTable().row.add(tr).draw()
	}
</script>

<style>
#attachmentTable {
	min-width: 500px;
	max-width: 500px;
}
</style>
<form:hidden path=""/>
<table id="attachmentTable" border="1" summary="List of Attachments">
	<thead>
		<tr>
			<th width="20%"><a href="javascript:forceFocusOnTableHeader()" aria-lable="Press Enter to Sort Date">Date</a></th>
			<th width="65%"><a href="javascript:forceFocusOnTableHeader()" aria-lable="Press Enter to Sort Name">Name</a></th>
		</tr>
	</thead>
	<tbody>
	</tbody>
</table>
<div style="margin-top: 10px">
	 <input type="button" class="button" title="View" id="viewAttachmentButton"
	 	value="View" style="display: none" />
	<input type="button" class="button" title="Add" id="addAttachmentButton"
		value="Add" />
	<input type="button" class="button" title="Remove" id="deleteAttachmentButton"
		value="Remove" style="display: none" />
</div>
<div id="deletedAttachments" style="display: none"></div>
<iframe style="visibility: hidden; display: none"
	id="attachmentDownloadFrame"></iframe>