<%@ include file="/includes.jsp"%>
<%@ taglib prefix="smvc" uri="http://www.springframework.org/tags/form"%>
<link rel="stylesheet" href="../css/tables.css" type="text/css" />
<br />
<br />
<script type="text/javascript">

	function sendAjaxReq(hospitalCode){	
		var data=document.getElementById("csrfparameterName").value;
		data=data+"="+document.getElementById("csrfparametervalue").value;
		$.ajax({
		   type: "POST",
		   url: "../admin/validateHospitals.form",
		   data: "hospitalCode="+hospitalCode+"&hospitalId="+document.getElementById('hospitalId').value+ "&" + data,
		   success: function(msg){
		     var isHospExists = msg.isHospitalCodeExists;
		     if("Yes" == isHospExists){
		     	document.getElementById('validateCodeMsg').style.display = "block";
		     	document.getElementById('codeAlreadyExists').value = "Yes";
		     }else{
		     	document.getElementById('validateCodeMsg').style.display = "none";
		     	document.getElementById('codeAlreadyExists').value = "No";
		     }
		   }
	  });
    }
   	
	function sentReq(arg) {
		document.getElementById("taskId").value = arg;
		var fsForm = document.getElementById("formHospital");
		fsForm.method="POST";
		fsForm.action = "../admin/listhospitals.form";
		fsForm.submit();
	}
	
	function processHospitalForm(arg) {
		var result = validateField();
		if(result==true){	
			setMeetingLocations();
			sentReq(arg);
		}
	}
	
	function validateField(){
		var hospitalNameField = document.getElementById("hospitalName").value;
		var hospitalCodeField = document.getElementById("hospitalCode").value;
		
		var table = document.getElementById("meetingLocationsTable");
		var rowCount = table.rows.length;
		
		if(hospitalNameField==""){
			alert("Please enter Hospital Name");
			document.getElementById("hospitalName").focus();
			return false;
		}else if(hospitalCodeField==""){
			alert("Please enter Hospital Code");
			document.getElementById("hospitalCode").focus();
			return false;
		}else if(document.getElementById('codeAlreadyExists').value == "Yes"){
			alert("Hospital with code '"+hospitalCodeField+"' already exists.");
			document.getElementById("hospitalCode").focus();
			return false;
		}//else if(rowCount <= 0){
		//	alert("At least one Meeting Location has to be added");
		//	document.getElementById("newMeetingLocation").focus();
		//	return false;
		//}
		else{
			return validatePreferedImageTransfer();
		}
		return true;
	}
	
	function myTrim(newValue) {
   	 return newValue.replace(/^\s*/, "").replace(/\s*$/, "");
	}

	function validatePreferedImageTransfer(){
		var selectedVal = document.getElementById("preferedImageTransferMethod").value;
		var check = false;
		var count = 0;
		$("input[type=checkbox]:checked").each(function() { 
	    	var val = $(this).val();
	    	if(selectedVal == val){
	    		check = true;
	    	}
	    		count++;
	    }); 
	   
	     if(count == 1 && (selectedVal == 'select')){
	    	return true;
	    }else if(count == 0 && (selectedVal != 'select')){
	    	alert("Please select an image transfer method before selecting preferred image transfer method.");
	    	return false;
	    }else if(count > 0 && (check == false)){
	    	alert("Please select a matching Prefered Image Transfer Method");
			document.getElementById("preferedImageTransferMethod").focus();
			return false;
	    }else{
	    	return true;
	    }
	    
	}
		
	function addNewMeetingLocation(){
		var newMeetingLocation=document.getElementById("newMeetingLocation").value;
		if(newMeetingLocation==""){
			alert("Please enter Meeting Location");
			document.getElementById("newMeetingLocation").focus();
			return false;
		}else{
			var table = document.getElementById("meetingLocationsTable");
			var rowCount = table.rows.length;
			if (rowCount > 0) {
				for ( var i = 0; i < rowCount; i++)
					if (table.rows[i].cells[0].innerHTML == newMeetingLocation) {
						alert("Meeting Location '" + newMeetingLocation + "' is already present");
						document.getElementById("newMeetingLocation").focus();
						return false;
					}
			}
			
			var row = table.insertRow(rowCount);
			row.setAttribute("id", "meetingLocationsTable" + newMeetingLocation);

			var column = row.insertCell(0);
			column.setAttribute("width", "70%");
			var element = document.createTextNode(newMeetingLocation);
			column.appendChild(element);

			column = row.insertCell(1);
			column.setAttribute('align','center');	// TODO better put into css
			element = document.createElement("img");								
			element.setAttribute("src", "../images/delete.png");
			var newlink = document.createElement('a');
			newlink.appendChild(element);
			newlink.setAttribute("onclick", " deleteMeetingLocation('meetingLocationsTable" +newMeetingLocation
					+ "','meetingLocationsTable');");
			newlink.setAttribute("onmouseover", "this.style.cursor = cursorPointer");
			column.appendChild(newlink);
			
			document.getElementById("newMeetingLocation").value="";
			return false;
		}
	}
	function deleteMeetingLocation(row, tableId) {
		var isProceed=true;
		if (!confirm("Are you sure you want to remove this location?")) {
			isProceed = false;
		}
		if(isProceed){
			var table = document.getElementById(tableId);
			var tableRow = document.getElementById(row);
			tableRow.parentNode.removeChild(tableRow);
		}
	}
	function setMeetingLocations(){
		var table = document.getElementById("meetingLocationsTable");
		var rowCount = table.rows.length;
		var str = "";
		if (rowCount > 0) {
			for ( var i = 0; i < rowCount; i++) {
				str = str + "," + table.rows[i].cells[0].innerHTML;
			}
			document.getElementById('meetingLocations').value = str;
		}
	}
	</script>

<c:set var="msg" value='<%=request.getParameter("errorMsg")%>' />
<c:choose>
	<c:when
		test="${requestScope.successMsg ne null || requestScope.errorMsg ne null}">
		<c:if test="${requestScope.successMsg ne null}">
			<span class="info"><c:out value="${requestScope.successMsg}"/></span>
			<br />
		</c:if>
		<c:if test="${requestScope.errorMsg ne null}">
			<span class="error"><c:out value="${requestScope.errorMsg}"/></span>
			<br />
		</c:if>

		<c:if test="${msg ne null}">
			<span class="info"><c:out value="${msg}"/></span>
			<br />
		</c:if>
	</c:when>
	<c:otherwise>
		<c:if test="${msg ne null}">
			<span class="info"><c:out value="${msg}"/></span>
			<br />
		</c:if>
	</c:otherwise>
</c:choose>
<sec:authorize access="hasRole('ADMIN')">
<smvc:form id="formHospital" >
	<input type="hidden" id="csrfparameterName" value="<c:out value="${_csrf.parameterName}"/>" />
	<input type="hidden" id="csrfparametervalue" value="<c:out value="${_csrf.token}"/>" />
	<input type="hidden" name="redirectParams" value="<c:out value="${requestScope['javax.servlet.forward.query_string']}" />"/>
	<br></br>
	<smvc:errors />

	<fieldset style="width: 50%" class="nobg"><c:choose>
		<c:when test="${hospitalsDTO eq null}">
			<legend>Add Hospital</legend>
		</c:when>
		<c:otherwise>
			<legend>Edit Hospital</legend>
		</c:otherwise>
	</c:choose>
	<fieldset><input type="hidden" name="task" id="taskId" /> 
	<input type="hidden" name="hospitalId" id="hospitalId" value="<c:out value="${hospitalsDTO.hospitalId}"/>" />
		<input type="hidden" name="codeAlreadyExists" id="codeAlreadyExists" value="No"/>
	<table>
		<tr>
			<c:choose>
				<c:when test="${hospitalsDTO eq null}">
					<td colspan="9"><B>Add Hospital </B></td>
				</c:when>
				<c:otherwise>
					<td colspan="9"><B>Edit Hospital</B></td>
				</c:otherwise>
			</c:choose>
		</tr>
		<tr>
			<td colspan="9">&#160;</td>
		</tr>
	</table>
	<c:if test="${hospitalsDTO ne null}">
		<input type="hidden" name="hospitalCreationDate" id="hospitalCreationDate"  value='<fmt:formatDate value="${hospitalsDTO.creationDate}" pattern="dd/MM/yyyy HH:mm:ss" />' />
	</c:if>
	<table width="100%" border="1" bordercolor="#F8F8FF">
		<tr>
			<td width="40%" align="left" valign="top">Hospital Name <span
				style="color: red;">*</span></td>
			<td width="60%" align="left" valign="top"><c:choose>
				<c:when test="${hospitalsDTO eq null}">
					<input type="text" name="hospitalName" id="hospitalName" />
				</c:when>
				<c:otherwise>
					<input type="text" name="hospitalName" id="hospitalName"
						value="<c:out value="${hospitalsDTO.hospitalName}"/>" />
				</c:otherwise>
			</c:choose></td>
		</tr>
		<tr>
			<td width="40%" align="left" valign="top">Hospital Code<span
				style="color: red;">*</span></td>
			<td width="60%" align="left" valign="top"><c:choose>
				<c:when test="${hospitalsDTO eq null}">
					<input type="text" name="hospitalCode" id="hospitalCode" onchange="sendAjaxReq(this.value);"/>
				</c:when>
				<c:otherwise>
					<input type="text" name="hospitalCode" id="hospitalCode" onchange="sendAjaxReq(this.value);"
						value="<c:out value="${hospitalsDTO.hospitalCode}"/>" />
				</c:otherwise>
			</c:choose>
			<span id="validateCodeMsg" class="error" style="display:none">This hospital code already exists</span></td>
		</tr>
		<tr>
			<td width="40%" align="left" valign="top">Hospital Description</td>
			<td width="60%" align="left" valign="top"><c:choose>
				<c:when test="${hospitalsDTO eq null}">
					<input type="text" name="hospitalDescription"
						id="hospitalDescription" />
				</c:when>
				<c:otherwise>
					<input type="text" name="hospitalDescription"
						id="hospitalDescription" value="<c:out value="${hospitalsDTO.hospitalDesc}" />" />
				</c:otherwise>
			</c:choose></td>
		</tr>
		<tr>
			<td width="40%" align="left" valign="top" colspan="2">Image
			Transfer Method</td>
		</tr>
		<c:if test="${imageTranfserMethods ne null}">

			<c:forEach var="imageTranfserMethod" items="${imageTranfserMethods}">
				<c:set var="check1" value="0" />
				<tr>
					<td width="40%" align="right" valign="top"><c:choose>
						<c:when test="${hospitalsDTO ne null}">
							<c:forEach var="selectedMapping"
								items="${hospitalsDTO.imageTransferMapping}">
								<c:choose>
									<c:when
										test="${selectedMapping.imgTansMethod.imgTransCode eq imageTranfserMethod.imgTransCode}">
										<input type="checkbox" name="imageTransferMethod"
											id="imageTransferMethod"
											value="<c:out value="${imageTranfserMethod.imgTransCode}"/>" checked="checked" />
										<c:set var="check1" value="1" />
									</c:when>
									<c:otherwise>
									</c:otherwise>
								</c:choose>
							</c:forEach>
							<c:if test="${check1 eq '0'}">
								<input type="checkbox" name="imageTransferMethod"
									id="imageTransferMethod"
									value="<c:out value="${imageTranfserMethod.imgTransCode}" />"/>
							</c:if>
						</c:when>
						<c:otherwise>
							<input type="checkbox" name="imageTransferMethod"
								id="imageTransferMethod"
								value="<c:out value="${imageTranfserMethod.imgTransCode}"/>"/>
						</c:otherwise>
					</c:choose></td>
					<td width="60%" align="left" valign="top"><c:out value="${imageTranfserMethod.description}"/></td>
				</tr>
			</c:forEach>
		</c:if>
		<tr>
			<td width="40%" align="left" valign="top">Preferred Image
			Transfer Method</td>
			<td width="60%" align="left" valign="top"><select
				id="preferedImageTransferMethod" name="preferedImageTransferMethod">
				<option value="select">Select</option>
				<c:forEach var="imageTranfserMethod" items="${imageTranfserMethods}">
					<c:choose>
						<c:when test="${hospitalsDTO ne null}">
							<c:set var="check" value="0" />
							<c:forEach var="selectedMapping"
								items="${hospitalsDTO.imageTransferMapping}">
 
								<c:if
									test="${(imageTranfserMethod.imgTransCode eq selectedMapping.imgTansMethod.imgTransCode)and (selectedMapping.isPreferred)}">
									<option value="<c:out value="${imageTranfserMethod.imgTransCode}"/>"
										selected="selected"><c:out value="${imageTranfserMethod.description}"/></option>
									<c:set var="check" value="1" />
								</c:if>

							</c:forEach>
							<c:if test="${check eq '0'}">
								<option value="<c:out value="${imageTranfserMethod.imgTransCode}"/>"><c:out value="${imageTranfserMethod.description}"/></option>
							</c:if>
						</c:when>
						<c:otherwise>
							<option value="<c:out value="${imageTranfserMethod.imgTransCode}"/>"><c:out value="${imageTranfserMethod.description}"/></option>
						</c:otherwise>
					</c:choose>
				</c:forEach>
			</select></td>
		</tr>
	</table>
	</fieldset>
	<fieldset><legend>Meeting Locations</legend>
	<table width="100%">
		<tr>
			<td><input type="hidden" id="meetingLocations" name="meetingLocations"/>
				<table id="meetingLocationsTable" width="100%" border="1" bordercolor="#F8F8FF">
					<c:forEach var="locations" items="${hospitalsDTO.meetingLocations}">
						<tr id="meetingLocationsTable<c:out value="${locations}"/>"><td><c:out value="${locations}"/></td>
							<td><a onclick="deleteMeetingLocation('meetingLocationsTable<c:out value="${locations}"/>','meetingLocationsTable')">
							<img src="../images/delete.png" border="0" alt="Delete"
								onmouseover="this.style.cursor = cursorPointer; " /></a></td>
						</tr>
					</c:forEach>
				</table>
			</td>
		</tr>
		<tr >
			<td align="left"><input type="text" id="newMeetingLocation"/><input type="button" value="add" onclick="addNewMeetingLocation();"></td>
		</tr>
	</table>
	</fieldset>
	<fieldset class="buttonFieldset"><input type="button"
		value="Back" onclick="sentReq(6);" /> <c:choose>
		<c:when test="${hospitalsDTO eq null}">
			<input type="button" value="Save" onclick="processHospitalForm(2);" />
		</c:when>
		<c:otherwise>
			<input type="button" value="Update" onclick="processHospitalForm(5);" />
		</c:otherwise>
	</c:choose></fieldset>
	</fieldset>
	<input type="hidden" name="bbRadImagingInterfaceChk"
		id="bbRadImagingInterfaceChk" />
	<input type="hidden" name="iEPImageTransferChk"
		id="iEPImageTransferChk" />
	<input type="hidden" name="manualPostingofDVDChk"
		id="manualPostingofDVDChk" />
	<input type="hidden" name="pACSSendofImagesChk"
		id="pACSSendofImagesChk" />
	<input type="hidden" name="preferedImageTransferMethodSlct"
		id="preferedImageTransferMethodSlct" />

</smvc:form></sec:authorize>