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

<link rel="stylesheet" href="css/searchallqirs.css">
<link rel="stylesheet" href="css/error.css">

<script type="text/javascript">
	function printQIR() {
		var selected = $('#selectedQIR').val()
		if (selected != null) {
			window.open('viewQir.html?qirId=' + selected)
		}
	}

	function confirmCancel() {
		return confirm("All unsaved data will be lost. Are you sure you want to cancel?")
	}

	$(function() {
		$("#fromDateInput").datepicker()
		$("#toDateInput").datepicker()

		var table = $('#currentQIRS').DataTable({
			pageLength: 5,
			paging : true,
			autowidth : true,
			searching : false,
			select : 'single',
			order : [ [ 1, "desc" ] ]
		});

		$('#currentQIRS tbody').on('click', 'tr', function() {
			var isSelected = $(this).hasClass('selected')
			var data = table.row(this).data()
			$('#selectedQIR').val(isSelected ? data[1] : '')
			refreshButtons()
		})

		$("#excel")
				.click(
						function() {
							confirmDialog('<span tabindex="0">Would you like to export this list?</span>', function() {
								var url = 'qirExcelExport.html'
									if ($('#selectedQIR').val() != '')
										url += '?qirId=' + $('#selectedQIR').val()
								window.open(url);
							}, {
								okButtonLabel : 'Yes',
								cancelButtonLabel : 'No',
								cancelCallback : function() {
									displayAttentionDialog('<span tabindex="0">Export process terminated.</span>')
								}
							})
						})

		$("#Refresh").click(function() {
			$("#Search").trigger('click')
		})
		
		forceFocusOnInfoMessage()
	})

	function forceFocusOnInfoMessage() {

		if($('#informationMessageDiv').is(':visible')){	
			$('#informationMessageDiv p:first').focus()	
		}

	}
	
	function forceFocusOnTableHeader() {
		$(this).parent().focus()	
	}
	
	function refreshButtons() {
		var selectedVal = $('#selectedQIR').val()
		var buttonName = ''
		var existingVal = selectedVal != ''
		var qirStatusCode = qirMap[selectedVal].statusCode;
		var userSubmittedQir =  qirMap[selectedVal].submittedBy == "<c:out value="${fn:toLowerCase(userName)}" />";
		
		if(${userIsAdmin}) {
		
			
			if(	qirStatusCode == "Withdrawn" || qirStatusCode == "Closed" ) {
				console.log("user is national admin or qir status indicates not editable.");
				buttonName = "View"
			}
			else {
				console.log("user is admin or originator");
				buttonName = "Edit"
			}			
			
			setButtonVals(buttonName, existingVal);
			return;
		}
		
		
		if(${not isVendor} == true) { // user is not vendor
		
			console.log("user is not vendor");			
			if(	(qirStatusCode != "Withdrawn" && qirStatusCode != "Closed") && userSubmittedQir) {
				
				console.log("user is originator and qir status indicates editable.");
				buttonName = "Edit"
			}
			else {
				console.log("user is not originator");
				buttonName = "View" 
			}
		}
		else 
		{			
			// user is vendor
			console.log("user is vendor");
			if((qirStatusCode != "Closed") && 
			   ("${user.vendor.name}" == qirMap[selectedVal].qirVendor)) {
			   // qir has active state AND qir belongs to vendor logged in
			   console.log("qir has active state AND qir belongs to vendor logged in");
			   buttonName = "Edit"
		   }
		   else 
		   { 
		   		// qir not active or qir doesnt belong to vendor logged in
			   console.log("qir not active or qir doesnt belong to vendor logged in");
			   buttonName = "View"
		   }
		}
		
		setButtonVals(buttonName, existingVal);
	}
	
	function setButtonVals(btnName, existingVal) {
	
		$('#edit').css("display", existingVal ? "inline-block" : "none")
		$('#edit').attr('value', btnName)		
		$('#pdf').css("display", existingVal ? "inline-block" : "none")
	
	}

	function resetForm() {
		$("#tnInput").val('')
		$("#fromDateInput").val('')
		$("#toDateInput").val('')
		$("#facilitySelect").val('-1')
		$("#vendorSelect").val('-1')
		$("#typeOfComplaintSelect").val('-1')
		$("#statusSelect").val('-1')
	}

	var qirMap = new Object()
	<c:forEach items="${qirList}" var="qir">
		qirMap['${qir.id}'] = {
			statusCode : "<c:out value="${qir.qirStatusType}" />",
			submittedBy : "<c:out value="${fn:toLowerCase(qir.submittedBy)}" />",
			qirVendor: "<c:out value="${qir.vendor}" />"
		}
	</c:forEach>
</script>

<form:form method="post" action="searchAllQirs.html" id="searchForm">

	<form:errors path="*" cssClass="errorBlockRedText" id="errorBlock"
		element="div" tabIndex="0">
	</form:errors>

	<div id="leftCol">
		<table cellpadding="5">
			<tr>
				<td align="right"><h4 tabindex="0">Tracking Number:</h4></td>
				<td><form:input type="text" id="tnInput" path="id" /></td>
			</tr>
			<tr>
				<td align="right"><h4 tabindex="0">From Date:</h4></td>
				<td nowrap><form:input type="text" id="fromDateInput"
						path="fromDateAsString" 
						alt="From Date is in the form of two digit month forward slash two digit day forward slash four digit year" tabindex="0" /> <b>MM/DD/YYYY</b>
						<span style="width: 8px"></span><b>To Date:</b> 
						<form:input type="text" id="toDateInput" path="toDateAsString" 
						alt="To Date is in the form of two digit month forward slash two digit day forward slash four digit year" tabindex="0" /> <b>MM/DD/YYYY</b>
				</td>
			</tr>
			<tr>
				<td align="right"><h4 tabindex="0">Facility:</h4></td>
				<td><form:select id="facilitySelect" path="selectedFacilityId">
						<form:option value="-1">Select</form:option>
						<form:options items="${facilities}" />
					</form:select></td>
			</tr>
		</table>
	</div>
	<div id="rightCol">
		<table cellpadding="5">
			<tr>
				<td align="right"><h4 tabindex="0">Vendor:</h4></td>
				<td><sec:authorize access="!hasAuthority('Vendor')">
				<form:select id="vendorSelect" path="selectedVendorId"
					style="width:150px">
					<form:option value="-1">Select</form:option>
					<form:options items="${vendors}" />
				</form:select>
			</sec:authorize>
			<sec:authorize access="hasAuthority('Vendor')">
				<div
					style="display: inline-block; margin-left: 8px; margin-bottom: 10px;">
					<c:out value="${user.vendor.name}" default="(none)" />
				</div>
			</sec:authorize></td>
			</tr>
			<tr>
				<td align="right"><h4 tabindex="0">Type of Complaint:</h4></td>
				<td><form:select id="typeOfComplaintSelect"
				path="selectedComplaintTypeId" style="width:150px">
				<form:option value="-1">Select</form:option>
				<form:options items="${dmpQirTypes}" />
			</form:select></td>
			</tr>
			<tr>
				<td align="right"><h4 tabindex="0">Status:</h4></td>
				<td><form:select id="statusSelect" path="selectedStatusTypeId"
				style="width:150px">
				<form:option value="-1">Select</form:option>
				<form:options items="${qirStatusTypes}" />
			</form:select></td>
			</tr>
		</table>
	</div>
	<div id="searchButtonContainer">
		<input type="submit" class="submitAnchor button" id="Search"
			value="Search" name="Search" tabIndex="0" /> <input type="button"
			class="submitAnchor button" value="Reset"
			onclick="javascript:resetForm()" />
	</div>
</form:form>

<form:form method="get" action="manageQirs.html">
	<input type="hidden" name="fromPage" value="searchAllQirs.html" />
	<div id="searchResultsTableContainer">
		<table class="stripe dt-head-left dt-body-left hover cell-border"
			id="currentQIRS">
			<thead>
				<tr>
					<th><a href="javascript:forceFocusOnTableHeader()" aria-lable="Press Enter to Sort Status">Status</a></th>
					<th><a href="javascript:forceFocusOnTableHeader()" aria-lable="Press Enter to Sort TN">TN</a></th>
					<th><a href="javascript:forceFocusOnTableHeader()" aria-lable="Press Enter to Sort Has Attachement">Has Attachment</a></th>
					<th><a href="javascript:forceFocusOnTableHeader()" aria-lable="Press Enter to Sort Headline">Headline</a></th>
					<th><a href="javascript:forceFocusOnTableHeader()" aria-lable="Press Enter to Sort Submitted Date">Submitted Date</a></th>
					<th><a href="javascript:forceFocusOnTableHeader()" aria-lable="Press Enter to Sort Submitted By">Submitted By</a></th>
					<th><a href="javascript:forceFocusOnTableHeader()" aria-lable="Press Enter to Sort Facility">Facility</a></th>
					<th><a href="javascript:forceFocusOnTableHeader()" aria-lable="Press Enter to Sort Vendor">Vendor</a></th>
				</tr>
			</thead>
			<tbody>
				<c:forEach items="${qirList}" var="qir">
					<tr>
						<td tabindex="0"><c:out value="${qir.qirStatusType}" /></td>
						<td tabindex="0"><c:out value="${qir.id}" /></td>
						<c:choose>
							<c:when test="${qir.hasAttachments}">						
								<td tabindex="0" alt="HAS Attachment">
									<img src="images/PaperClip_Black.png" alt="Has Attachment" />
								</td>
							</c:when>
							<c:otherwise>
								<td tabindex="0">
									
								</td>
							</c:otherwise>
						</c:choose>
						<td tabindex="0"><c:out value="${qir.headline}" /></td>
						<td tabindex="0"><c:out value="${qir.submittedDateAsString}" />
						</td>
						<td tabindex="0"><c:out value="${qir.submittedByName}" /></td>
						<td tabindex="0"><c:out value="${qir.facilityNumAndName}" />
						</td>
						<td tabindex="0"><c:out value="${qir.vendor}" /></td>
					</tr>
				</c:forEach>
			</tbody>
		</table>
	</div>

	<div id="submitButtonContainer">
		<input type="submit" class="submitAnchor button" id="edit" value="Edit" name="editMode" /> 
		<input type="button" class="submitAnchor button" id="pdf" value="PDF" name="PDF" onclick="printQIR()" />
		<sec:authorize access="hasAuthority('National Administrator')">
			<input type="button" id="excel" class="submitAnchor button" value="Excel" />
		</sec:authorize>
		<input type="button" class="submitAnchor button" id="Refresh"
			value="Refresh" name="Refresh" onclick="document.location.href='searchAllQirs.html'" /> <input type="button"
			class="submitAnchor button" id="cancel" value="Cancel" name="Cancel"
			onclick="javascript:document.location.href='home.html'" /> <input
			id="selectedQIR" name="selectedQIR" type="hidden" value=" "
			path="selectedQIR" />
	</div>
</form:form>

