<%@ include file="/includes.jsp"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ taglib prefix="smvc" uri="http://www.springframework.org/tags/form"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>

<script src="../js/webapp.js" type="text/javascript"></script>
<script src="../js/pswdStrength.js" type="text/javascript"></script>
<script src="../js/AJAXSupport.js" type="text/javascript"></script>

<smvc:form modelAttribute="userForm" id="form" action="../admin/userform.form">
	<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']}" />" />
	<input type="hidden" id="containsStrongPw" name="containsStrongPw" value="<c:out value="${enforceStrngPwdVal}" />" />
	<input type="hidden" id="containsPwdExpire" name="containsPwdExpire" value="<c:out value="${passwordCanExpireVal}" />" />
	<input type="hidden" id="enforcePasswordHidden" name="enforcePasswordHidden" value="<c:out value="${enforceStrngPwdVal}" />" />
	<input type="hidden" id="pwdExpireHddn" name="pwdExpireHddn" value="false" />
	<input type="hidden" id="isPaswordChanged" name="isPaswordChanged" value="false"/>
	<input type="hidden" id="fromAdmin" name="fromAdmin" value="true" />
	<input type="hidden" name="cancelField" id="cancelField" value="true" />
	<input type="hidden" name="delete" id="delete" value="false" />
	<input type="hidden" name="userId" id="userId" value="<c:out value="${userForm.user.id}" />" />
	<smvc:hidden path="user.id"/>
	<input type="hidden" name="nopatientId" id="nopatientId" value="true" />
	<input type="hidden" name="editsupportingStaff" id="editsupportingStaff" value="false" />
	<input type="hidden" id="passwordMinimumLength" name="passwordMinimumLength" value="<c:out value="${passwordMinimumLength}" />" />
	<input type="hidden" id="passwordIncludeNumeric" name="passwordIncludeNumeric" value="<c:out value="${passwordIncludeNumeric}" />" />
	<input type="hidden" id="passwordIncludeUpperCase" name="passwordIncludeUpperCase" value="<c:out value="${passwordIncludeUpperCase}" />" />
	<input type="hidden" id="passwordIncludeSpecialChar" name="passwordIncludeSpecialChar" value="<c:out value="${passwordIncludeSpecialChar}" />" />
	<c:set var="ldapUser" value="${userForm.user.ldapUser}"/>
	<smvc:errors />
	<br />&nbsp;
	<c:if test="${msg ne null}">
		<span class="info"><c:out value="${msg}"/></span>
	</c:if>
	<c:if test="${errors ne null}">
		<span class="error"><c:out value="${errors}"/></span>
	</c:if>
	<c:if test="${userForm.errors ne null}">
		<span class="error"><c:out value="${userForm.errors}"/></span>
	</c:if>
	<c:if test="${ldapUser eq true}">
		 <span class="warning"> This user account is controlled from Windows Active Directory<br/> 
			and cannot be changed here: please ask your AD system administrator to make any changes.</span>
	</c:if>
	<smvc:hidden path="user.strCreationDate"/>
	<table align="center" width="750px">
		<tr>
			<td>
			<fieldset class="nobg"><legend>Edit User</legend>
			<table cellspacing="10" width="100%">
				<tr>
					<td valign="top">
					<fieldset>
					<table width="375px">
						<tr>
							<td class="label">Username <span class="mandatory">*</span></td>
							<td class="input"><sec:authorize access="hasRole('ADMIN')">
								<smvc:input path="user.username" id="usernameId" />
							</sec:authorize> <sec:authorize access="!hasRole('ADMIN')">
								<smvc:input path="user.username" disabled="true" id="usernameId"/>
							</sec:authorize></td>
						</tr>
						<sec:authorize access="hasRole('ADMIN')">
							<tr>
								<td class="label">Honorific Prefix</td>
								<td class="input"><webapp:selectAndEditList
									path="user.prefix" domain="webapp" list="userPrefix"
									includeEmpty="true" currentValue="${userForm.user.prefix}"/></td>
							</tr>
						</sec:authorize>
						<tr>
							<td class="label">Forename</td>
							<td class="input"><smvc:input path="user.forename" disabled="${ldapUser}" /></td>
						</tr>
						<tr>
							<td class="label">Middle name(s)</td>
							<td class="input"><smvc:input path="user.middlename" disabled="${ldapUser}" /></td>
						</tr>
						<tr>
							<td class="label">Surname</td>
							<td class="input"><smvc:input path="user.surname"  disabled="${ldapUser}" /></td>
						</tr>
						<sec:authorize access="hasRole('ADMIN')">
							<tr>
								<td class="label">Honorific Suffix</td>
								<td class="input"><webapp:selectAndEditList
									path="user.suffix" domain="webapp" list="userSuffix"
									includeEmpty="true"  currentValue="${userForm.user.suffix}" /></td>
							</tr>
						</sec:authorize>
						<!--<tr>
                                            <td class="label">Organization Code</td>
                                            <td class="input">
                                                <webapp:selectAndEditList path="user.orgCode" domain="webapp" list="Organization Code" includeEmpty="true"/>
                                            </td>
                                        </tr>-->
						<sec:authorize access="hasRole('ADMIN')">
							<tr>
								<td class="label">Hospital</td>
								<td class="input">
									<smvc:select path="selectedHospital" disabled="${ldapUser}"  >
										<smvc:option value="">select a hospital</smvc:option>
										<smvc:options items="${webapp.hospMap}" />
									</smvc:select>
								</td>
							</tr>
						</sec:authorize>
						<sec:authorize access="hasRole('ADMIN')">
							<tr>
								<td class="label">Account Locked </td>
								<td class="input">
									<smvc:checkbox path="accountLocked" id="accountLocked" disabled="${ldapUser}" />
								</td>
							</tr>
						</sec:authorize>
						<tr>
							<td class="label">Enabled </td>
							<td class="input"><sec:authorize access="hasRole('ADMIN')">
								<c:if test="${userForm.loginUserIsEditingUser eq 'yes' }">
									<smvc:checkbox path="user.enabled" id="enabled"
										disabled="true" />
								</c:if>
								<c:if test="${userForm.loginUserIsEditingUser ne 'yes' }">
									<smvc:checkbox path="user.enabled" id="enabled"
										 disabled="${ldapUser}" />
								</c:if>
							</sec:authorize>
							</td>
						</tr>
						<c:if test="${passwordCanExpireVal eq 'true'}">
							<tr>
								<td class="label">Password can expire</td>
								<td class="input"><sec:authorize access="hasRole('ADMIN')">
									<c:if test="${userForm.loginUserIsEditingUser eq 'yes' }">
										<smvc:checkbox path="user.passwordCanExpire"
											id="passwordCanExpire" disabled="true" />
									</c:if>
									<c:if test="${userForm.loginUserIsEditingUser ne 'yes' }">
										<smvc:checkbox path="user.passwordCanExpire"
											id="passwordCanExpire" disabled="false"
											onchange="processPasswordCanExpire(); " />
									</c:if>
								</sec:authorize> 
								<sec:authorize access="!hasRole('ADMIN')">
									<smvc:checkbox path="user.passwordCanExpire"
										id="passwordCanExpire" disabled="true" />
								</sec:authorize></td>
							</tr>
						</c:if>
						<c:choose>
							<c:when test="${enforceStrngPwdVal eq 'true'}">
								<tr>
								   <sec:authorize access="hasRole('ADMIN')">
									<td class="label">Enforce Strong Password</td>
									<td class="input">
										<smvc:checkbox path="user.enforceStrongPassword"
											id="enforceStrongPassword" disabled="false"
											onclick="processEnforcePassword();" /></td>
									</sec:authorize>
									<sec:authorize access="!hasRole('ADMIN')">
										<td><smvc:checkbox path="user.enforceStrongPassword"
											id="enforceStrongPassword" cssStyle="display:none;" disabled="true"/></td>
									</sec:authorize>
								</tr>
							</c:when>
							<c:otherwise><tr><td>
								<smvc:checkbox path="user.enforceStrongPassword"
								 id="enforceStrongPassword" disabled="true" cssStyle="display:none;" /></td></tr>
							</c:otherwise>
						</c:choose>
						<sec:authorize access="hasRole('ADMIN')">
							<tr>
								<td class="label">Account expires on</td>
								<td class="input">
									<c:if test="${userForm.loginUserIsEditingUser eq 'yes' }">
									<smvc:input path="user.strdateAccountExpires"
										id="strdateAccountExpires" disabled="true" />
									<img title='Click to choose date' style='cursor: pointer'
										src='../images/16x16/date.png' />
								</c:if> 									
								<c:if test="${userForm.loginUserIsEditingUser ne 'yes' }">
									<spring:bind path="user.strdateAccountExpires">
                           			<c:choose>
                           				<c:when test="${user.ldapUser}">
                           				    <input type="text" name="user.strdateAccountExpires" class="mediumTxtBox" id="strdateAccountExpires" disabled="disabled"  value="<c:out value="${userForm.user.strdateAccountExpires}"/>" placeholder="dd/mm/yyyy"/>
                           				</c:when>
                           				<c:otherwise>
                           				     <input type="text" name="user.strdateAccountExpires" class="mediumTxtBox" id="strdateAccountExpires" placeholder="dd/mm/yyyy" value="<c:out value="${userForm.user.strdateAccountExpires}"/>" />
                           				</c:otherwise>
                           			</c:choose>
                                	</spring:bind>
									<img title='Click to choose date' style='cursor: pointer'
										src='../images/16x16/date.png'
										id='strdateAccountExpires_DateTrigger' />
									
								</c:if></td>
							</tr>
						</sec:authorize>
						<tr id="pwdStrength">
							<td class="label"><smvc:hidden path="pass1" id="password1"/></td>
							<td class="input"> <div id="passwordDescription" class="label"></div>
							</td>
						</tr>
						<tr>
							<td colspan="2">
							<hr />
							</td>
						</tr>
						<tr>
							<td class="label">Email <span class="mandatory">*</span></td>
							<td class="input"><smvc:input path="user.email"   disabled="${ldapUser}"  size="30"/>
							<smvc:hidden path="user.password"/>	</td>
						</tr>
					</table>
					</fieldset>
					</td>
					<td valign="top"><sec:authorize access="hasRole('ADMIN')">
						<fieldset><input type="hidden" name="updateRoles"
							value="true" /> <b>Roles</b><br />
						<c:choose>
							<c:when test="${userForm.roles  ne null }">
								<c:forEach var="role" items="${userForm.roles}">
								    <c:choose>
										<c:when test="${role.enabled}">
											<smvc:checkbox path="selectedRoles" value="${role.value}" disabled="${ldapUser}" />&nbsp;<c:out value="${role.value }"/><br />
										</c:when>
										<c:otherwise>
											<input type="checkbox" <c:if test="${ldapUser}"> disabled="disabled"</c:if>/><s>&nbsp;<c:out value="${role.value }"/></s><br />
										</c:otherwise>
									</c:choose>
								</c:forEach>
							</c:when>
							<c:otherwise>No roles defined</c:otherwise>
						</c:choose>
						<hr />
					</fieldset>
					</sec:authorize></td>
				</tr>
			</table>

			<fieldset class="buttonFieldset">
			<sec:authorize
				access="hasRole('ADMIN')">
				<c:if test="${!empty userForm.user.id}">
					<input type="button" value="Add/Edit Support Staff"
						onclick="return supportingStaff();" />
				</c:if>
			</sec:authorize>

				<%--
			<input type="reset" <c:if test="${ldapUser}"> disabled="disabled"</c:if> />
			--%>

			
			<sec:authorize access="hasRole('ADMIN')">
				<c:if test="${userForm.loginUserIsEditingUser eq 'yes' }">
					<input type="button" id="deleted" value="Delete"
						disabled="disabled" onclick="deleteUser();" />
				</c:if>
				<c:if test="${userForm.loginUserIsEditingUser ne 'yes' }">
					<c:if test="${userForm.newUser ne 'true' }">
						<input type="button" id="deleted" value="Delete"
							onclick="deleteUser();" />
					</c:if>
					<c:if test="${userForm.newUser eq 'true' }">
						<input type="button" id="deleted" value="Delete"
							disabled="disabled" onclick="deleteUser();" />
					</c:if>
				</c:if>
			</sec:authorize>
			<c:if test="${!empty userForm.user.id and !ldapUser}">
				<sec:authorize access="hasRole('ADMIN')">
					<input type="button" value="Reset password" onclick="document.location.href ='userPassword.form'" />
				</sec:authorize>
				<sec:authorize access="!hasRole('ADMIN')">
					<c:if test="${userForm.user.id eq webapp.currentUser.id}">
						<input type="button" value="Change password" onclick="document.location.href ='userPassword.form'" />
					</c:if>
				</sec:authorize>
			</c:if>

				&nbsp;<input type="button" value="Save" onclick="enableUserBox();" <c:if test="${ldapUser}"> disabled="disabled"</c:if>/>

			</fieldset>

			</fieldset>
			</td>
		</tr>
	</table>
	<div id="formatedDateId" style="display: none;"><fmt:formatDate
		value="${userForm.user.dateAccountExpires}" type="date" pattern="dd/MM/yyyy" /></div>
<%@ include file="userPatientpopUp.jsp"%>
</smvc:form>
<div id="backgroundPopup" class="backgroundPopup"></div>
<script type="text/javascript">
	function update() {
		fullScreenPleaseWait();
		document.getElementById("cancelField").name = 'org.apache.struts.taglib.html.CANCEL';
		document.getElementById("form").submit();
	}
	
	function deleteUser() {
	   var confirmed;
	   confirmed = confirm("Are you sure you want to delete the user?");
	   if(confirmed){
		   var data=document.getElementById("csrfparameterName").value;
		   data=data+"="+document.getElementById("csrfparametervalue").value;
       	   $.ajax({
				type : "GET",
				url : "../admin/getpatientswithuser.form",
				data : "username="+document.getElementById('usernameId').value+ "&" + data,
				success : function(msg) {
					if(msg.patientListSize<=0){
						fullScreenPleaseWait();
						document.getElementById("delete").value = "true";
						document.getElementById("form").submit(); 
					}else{
						var table = document.getElementById("patientsOfUserPopUpTable");
						var rowCount = table.rows.length;
						var row = table.insertRow(rowCount);
						var column = row.insertCell(0);
						var element = document.createTextNode(msg.message);
						column.style.fontWeight = 'bold';
						column.style.fontSize = '16';
						column.style.paddingLeft ='10px';
						column.style.paddingBottom ='15px';
						column.appendChild(element);
						rowCount++;
						
						var row = table.insertRow(rowCount);
						var column = row.insertCell(0);
						var element = document.createTextNode("The patients are:");
						column.style.paddingLeft ='30px';
						column.style.fontSize = '14';
						column.style.paddingBottom ='10px';
						column.appendChild(element);
						rowCount++;
						
						for(var i=0;i<msg.patientListSize;i++){
							var count=i+1;
							var row = table.insertRow(rowCount);
							var column = row.insertCell(0);
							var element = document.createTextNode(count+". "+msg.patientNameList[i]);
							column.style.paddingLeft ='50px';
							column.style.paddingBottom ='5px';
							column.appendChild(element);
							rowCount++;
						}
					 document.getElementById('patientsOfUserPopUpId').style.display = '';
					 centerPopup('patientsOfUserPopUpId'); 
					 loadPopup('patientsOfUserPopUpId');
					}
				}
			});
       }
       else{
          return false;
       }
    }
    function supportingStaff(){
    	
    	var editsupportingStaff = document.getElementById("editsupportingStaff");
    		editsupportingStaff.value ="true";
    	
    	var theUserForm = document.getElementById("form");
    	enableUserBox();
		fullScreenPleaseWait();
		theUserForm.submit();
    	
    }
    function enableUserBox(){
       	var result=processDateAccountExpires();
       	if(result){
	 	   	var enabledCheckBox = document.getElementById("enabled");
	       	if(enabledCheckBox){    		
	    		enabledCheckBox.disabled =false;
	    	}
	       	fullScreenPleaseWait();
	    	saveValues('roleAdmin');
	    	return true;
    	}else if(!result){
	    	document.getElementById("strdateAccountExpires").focus();
	    	return false
    	}
    }
    function processEnforcePassword(){ 
    	 var chkValue =  document.getElementById("enforceStrongPassword").checked;
         document.getElementById("enforcePasswordHidden").value = chkValue;	   	
		 var txtValue = document.getElementById("password1").value;  
		   if(chkValue == true && txtValue.length >0){
	  		 	passwordStrength(txtValue);
	  		}
	  		
		//if(chkValue == true){	   
		//	document.getElementById("pwdStrength").style.display='';
		//	document.getElementById("password1").onkeyup = function() {passwordStrength(this.value) };
		//}else{
		//	document.getElementById("pwdStrength").style.display='none';
		//	document.getElementById("containsStrongPw").value=document.getElementById("enforceStrongPassword").checked;
		//	document.getElementById("password1").onkeyup =function() { };
		//}	
		      
    }

    function enableDisableStrongPw(){
		alert( document.getElementById("enforceStrongPassword").checked);

    }
    
    function processPasswordCanExpire(){
        if(document.getElementById("containsPwdExpire").value == 'true'){   
          document.getElementById("pwdExpireHddn").value = document.getElementById("passwordCanExpire").checked; 
          document.getElementById("containsPwdExpire").value= document.getElementById("passwordCanExpire").checked
       	}
    }
    
    function loadDate(){
	    document.getElementById("strdateAccountExpires").value = document.getElementById("formatedDateId").innerHTML;    
    }
    
    function loadAll(){
	    loadDate();
	    processPasswordCanExpire();
	    processEnforcePassword();
    }
	function processDateAccountExpires(){
	    if(document.getElementById('strdateAccountExpires').disabled){
	    	return true;
	    }
		var sDate=document.getElementById("strdateAccountExpires").value;
		if(sDate==""){
	        return true;
		}
		var checkOK = "0123456789/";
        var allValid_f = true;                                                    

        for (i = 0; i < sDate.length; i++) { 
       		ch = sDate.charAt(i); 
               for (j = 0; j < checkOK.length; j++)
                if (ch == checkOK.charAt(j))
                break;
                if (j == checkOK.length){ 
	               	allValid_f = false; 
	               	break; 
               } 
        }
        if (!allValid_f){ 
           alert("Invalid From Date.\nFormat accepted is dd/mm/yyyy.");
           return (false); 
        }
        var k;
        var l=0;
        var checkStr=sDate;
        for(k = 0; k < checkStr.length; k++) { 
        		ch = checkStr.charAt(k); if(ch=='/') l++;}
            	if (l!=2){ 
                    alert("Invalid From Date.\nFormat accepted is dd/mm/yyyy.");
                    return (false); 
                 } 
		        a=checkStr.indexOf('/')
		        b=checkStr.indexOf('/',a+1)
		        fs_date=checkStr.substring(0,a)
		        fs_month=checkStr.substring(a+1,b)
		        fs_year=checkStr.substring(b+1,10)
		       
				if(fs_year<=1752){
					alert("can not have a date earlier than the year 1753.");
					return false;
				}
                
	        	if(checkStr.substring(b+1,10).length !=4){
					alert("Invalid From Date.\nFormat accepted is dd/mm/yyyy.");
	                return (false); 
	            }
		        if((checkStr.substring(a+1,b).length < 1) || (checkStr.substring(a+1,b).length > 2)){
	                alert("Invalid From Date.\nFormat accepted is dd/mm/yyyy.");
	                return (false); 
		        }
		        if((checkStr.substring(0,a).length < 1) || (checkStr.substring(0,a).length > 2)){
		                alert("Invalid From Date.\nFormat accepted is dd/mm/yyyy.");
		                return (false); 
		        }
		        if(fs_month>12 || fs_month<1){
		                alert("Invalid From Date in month.");
		                return (false); 
		         }
	          	if(fs_date>31 || fs_date<1){
	                alert("Invalid From Date in days.");
	                return (false); 
	        	}
        		if(fs_month==4 || fs_month==6 || fs_month==9 || fs_month==11)
        			if(fs_date>30){
		                alert("Invalid From Date.");
		                return (false); 
  					}
        
         		if(fs_month==2)
        			if(fs_date>29){
		                alert("Invalid From Date .");
		                return (false); 
        			}
        
        		if((fs_year%4)!=0)
        			if(fs_month==2)
        				if(fs_date>28){
                		alert("Invalid From Date.");
                		return (false); 
        			}
        			return true;
	}
	
	this.loadAll();

</script>
