<%@page import="com.ardeo.entities.Hospitals"%>
<%@ include file="/includes.jsp"%>
<%@ taglib prefix="smvc" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<br/>
<c:if test="${fn:length(redirect) gt 0}">
<input type="hidden" id="redirectpath" value="<c:out value="${redirect}"/>"/>
<Script type="text/javascript">
	document.location=document.getElementById('redirectpath').value;
</Script>
</c:if>
<style>
input.mediumTxtBox {
	width:80px;
}
</style>
<script>
    function validateMeetingForm() {
        if (document.getElementById("cancelOnly").value == "true")
            return true;
        var existErrors = "true"
        var title, from, until, meetingnotes;
        title = document.getElementById("meetingtitle").value;
        title = trim(title, " ");
        meetingnotes = document.getElementById("meetingnotes").value;
        meetingnotes = trim(meetingnotes, " ");
        if(title.length == 0) {
            alert("Please provide a title for the meeting"); 
	        existErrors = false;
        }
        else if(meetingnotes.length >= 254) {
            alert("Not possible to enter more than 254 characters in the Notes input field. \nPlease try again."); 
            existErrors = false;
        } 
        if(document.getElementById('startTime').value.length>0){
    		document.getElementById('startTime').value=document.getElementById('startTime').value.replace('.',':');
    		document.getElementById('startTime').value=document.getElementById('startTime').value.replace(',',':');
    		document.getElementById('startTime').value=document.getElementById('startTime').value.replace(';',':');
    		var result=validateTime(document.getElementById('startTime').value);
    		if(result){
    		  return false;
    		}
    	}
        if(document.getElementById('endTime').value.length>0){
    	  document.getElementById('endTime').value=document.getElementById('endTime').value.replace('.',':');
    	  document.getElementById('endTime').value=document.getElementById('endTime').value.replace(',',':');
    	  document.getElementById('endTime').value=document.getElementById('endTime').value.replace(';',':');
    		var result=validateTime(document.getElementById('endTime').value);
    		if(result)
    		return false;
    	}
        return existErrors;
    }
    
    function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
	}
	 
	function ltrim(str, chars) {
	    chars = chars || "\\s";
	    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
	}
	 
	function rtrim(str, chars) {
	    chars = chars || "\\s";
	    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
	}
    
    function update(button) {
        document.getElementById("updateOnly").value = "true";
        if(validateMeetingForm()){
        	button.disabled=true; 
        	button.value='Saving...'; 
        	document.getElementById("movForm").submit();
        }
    }
    
    function deleteMeeting() {
        var isDeleted = "false";
        isDeleted = confirm("Are you sure you want to delete this meeting?");
        if(isDeleted) {
	        document.getElementById("deleteOnly").value = "true";
	        document.getElementById("movForm").submit();
        }
        else {
	        document.getElementById("deleteOnly").value = "false";
        }
    }
    function unlockMeeting() {
        document.getElementById("unlockOnly").value = "yes";
        document.getElementById("movForm").submit();
    }
    function cancel() {
        document.getElementById("cancelOnly").value = "true";
		console.log("cancelling - value is " + document.getElementById("cancelOnly").value);
        document.getElementById("movForm").submit();
    }
    function validateTime(time){
        if(time.length>5){
    		alert('invalid time format');
    		return true;
    	}
    	var val=time.replace('.',':');
    	val=val.replace(':',''); 
    	if(val.length>4){
    		alert('invalid time format');
    		return true;
    	}
    	if(!(/^\d+$/.test(val))){
    		alert('invalid time format');
    	 	return true;
    	}
    	var index=time.indexOf(':');
    	if(index>=0){
    		var str1=time.substring(0, index);
    		if(str1<0 || str1>24){
    		  alert('invalid time format');
    			return true;
    		}
    		var str2=time.substring(index+1,time.length);
    		if(str2<0 || str2>60){
    		  alert('invalid time format');
    			return true;
    		}
    	}else{
    	  if(time.length>2){
    		alert('invalid time format');
    		return true;
    		}
    	}
    	return false;
    }
    
    function changeLocationByHospital(){
    	var selectedHospitalId= document.getElementById("selectedHospital").value;
    	var select=document.getElementById("meetingLocationSelect");
    	while (select.options.length>1){
    		var j=1;
   			select.remove(j);
   			select=document.getElementById("meetingLocationSelect");
    	 }
         
    	if(selectedHospitalId==""){
    		
    	}else{
    		var locationList=document.getElementById("locationList"+selectedHospitalId).value;
    		
    		var res = locationList.split(",");
    		for(var i = 0; i <res.length; i++) {
    			if(res[i].length>0){
    				var opt = document.createElement('option');
    		        opt.value = res[i];
    		        opt.innerHTML = res[i];
    		        select.appendChild(opt);
    			}
    		}
    	}
    	
    }
</script>
<br /><br />
<c:if test="${fn:length(requestScope.message) gt 0 }">
	<div align="center">
		<span class="info"><c:out value="${requestScope.message}"/></span>
	</div>
</c:if>
<c:if test="${fn:length(requestScope.error) gt 0 }">
	<div align="center">
		<span class="error"><c:out value="${requestScope.error}"/></span>
	</div>
</c:if>
<c:if test="${fn:length(redirect) le 0}">

<smvc:form modelAttribute="meetingForm" id="movForm" action="../meetings/createAndEditMeeting.form">
<input type="hidden" name="redirectParams" value="<c:out value="${requestScope['javax.servlet.forward.query_string']}" />" />
<%@ include file="lockMeetingPopUp.jsp" %>

<c:set var="hospitals" value="${webapp.hospitalsList}"/>
<c:forEach var="hospitals" items="${hospitals}">
	<%
		Hospitals hospitals = (Hospitals) pageContext.getAttribute("hospitals");
		String locationList = "";
			for (String location : hospitals.getMeetingLocations()) {
				locationList = locationList + "," + location;
			}
	%>
	<input type="hidden" id="locationList${hospitals.id}" value="<%=locationList%>" />
</c:forEach>


<c:set var="readOnly" value="false" scope="request"/>
<c:if test="${meetingForm.locked eq 'true'}">
<c:set var="readOnly" value="true" scope="request"/>
</c:if>
<table width="100%">
	<tr>
		<td align="center" valign="top"><br />
			<input type="hidden" id="updateOnly" name="updateOnly" value="false" />
			<input type="hidden" id="deleteOnly" name="deleteOnly" value="false" />
			<input type="hidden" id="lockOnly" name="lockOnly" value="no" />
			<input type="hidden" id="unlockOnly" name="unlockOnly" value="no" />
			<input type="hidden" id="cancelOnly" name="cancelOnly" value="false" />
			<input type="hidden" name="page" value="Overview" />
			

		 <table cellpadding="0" cellspacing="0">
         <tr>
            <td valign="top">
            	<c:choose>
            		<c:when test="${fn:length(meetingForm.meetingId) le 0}">
            		   <c:set var="title" value="Add a new Meeting"></c:set>
            		</c:when>
            		<c:otherwise>
            			<smvc:hidden path="meeting.id"/>
            			<c:set var="title" value="Meeting Overview"></c:set>
            		</c:otherwise>
            	</c:choose>
            	<div class="dialogBox">
				<div class="dialogTitle"><c:out value="${title}"/></div>
				<div class="dialogContent">
                  <table>
                       <tr>
                           <td  class="label">Title</td>
                           <td class="input"><smvc:input size="70" path="meeting.title" id="meetingtitle" maxlength="254" cssStyle="width: 350px;" readonly="${readOnly}"/></td>
                       </tr>
                         <tr>
                            <td  class="label">
                                Date
                            </td>
                           <td class="input">
                           		<spring:bind path="startDate">
                           			<c:choose>
                           				<c:when test="${readonly eq 'true' }">
                           				    <input type="text" name="startDate" class="mediumTxtBox" id="meetingDate" readonly="readonly" value="<c:out value="${meetingForm.startDate}"/>" placeholder="dd/mm/yyyy"/>
                           				</c:when>
                           				<c:otherwise>
                           				     <input type="text" name="startDate" class="mediumTxtBox" id="meetingDate" placeholder="dd/mm/yyyy" value="<c:out value="${meetingForm.startDate}"/>" />
                           				</c:otherwise>
                           			</c:choose>
                                </spring:bind>
                                <img title='Click to choose date' style='cursor: pointer' src='../images/16x16/date.png' id="meetingDate_DateTrigger" />
                            </td> 
                        </tr>
                         <tr>
                          <td class="label">
                          	<table width="100%">
                          		<tr><td>Time</td><td align="right">From: </td></tr>
                          	</table>
                          </td>
                            <td class="input">
                                <smvc:input path="startTime" size="5" id="startTime"  readonly="${readOnly}"/> 
                                Until: <smvc:input path="endTime" size="5" id="endTime"  readonly="${readOnly}"/> 
                            </td>
                        </tr>
                         <tr><td class="label">Hospital</td>
							<td class="input">
								<smvc:select path="selectedHospital"  id="selectedHospital" onchange="changeLocationByHospital();">
									<smvc:option value="">---select a hospital----</smvc:option>
									<c:forEach var="hospitals" items="${webapp.hospMap}">
										<smvc:option value="${hospitals.key}"><c:out value="${hospitals.value}"/></smvc:option>
									</c:forEach>
								</smvc:select>
					
							</td>
						</tr>
                         <tr>
                            <td class="label">Location</td>
                            <td class="input" >
                            	<smvc:select  path="meeting.location" id="meetingLocationSelect">
                            		<smvc:option value=""></smvc:option>
                            		<c:forEach var="hospitals" items="${webapp.hospitalsList}">
                            			<c:if test="${hospitals.id eq meetingForm.selectedHospital}">
                            				<c:forEach var="meetingLocations" items="${hospitals.meetingLocations}">
	                            				<c:choose>
													<c:when test="${meetingForm.meeting.location eq meetingLocations}">
														<smvc:option value="${meetingLocations }" selected="selected"><c:out value="${meetingLocations }"/></smvc:option>
													</c:when>
													<c:otherwise>
														<smvc:option value="${meetingLocations }>"><c:out value="${meetingLocations }"/></smvc:option>
													</c:otherwise>
												</c:choose>
                            				</c:forEach>
                            			</c:if>
                            		</c:forEach>
                            	</smvc:select>
                            </td>
                        </tr>
                          <tr><td class="label">Virtual Meeting?</td>
							<td class="input">
							<!-- if not creating a meeting, disable this field -->
							<c:choose>
								<c:when test="${meetingForm.meetingId gt 0}">
									<smvc:hidden path="virtualMeeting" />
									<c:if test="${meetingForm.virtualMeeting eq 1}">
										Yes, Virtual Meeting discussion is enabled
									</c:if>
									<c:if test="${meetingForm.virtualMeeting eq 0}">
										No, this is a physical meeting
									</c:if>
								</c:when>
								<c:otherwise>
									<smvc:select path="virtualMeeting"  id="virtualMeeting" disabled="${virtualIsDisabled}">
										<smvc:option value="1">Yes, enable Virtual Meeting discussion</smvc:option>
										<smvc:option value="0">No, this is a physical meeting</smvc:option>
									</smvc:select>
								</c:otherwise>
							</c:choose>
							</td>
						</tr>
                        <tr>
                            <td class="label">
                                Speciality
                            </td>
                            <td class="input">
                             <webapp:selectAndEditList domain="EMDT" path="meeting.tumourGroup"
								list="speciality" includeEmpty="true"
								currentValue="${meetingForm.meeting.tumourGroup}" 
								 disabled="${readOnly}"/>
                            </td>
                        </tr>
                    	<tr>
							<td class="label">Forms</td>
							<td class="input"> <smvc:select path="meeting.formPath" disabled="${readOnly}">
								<smvc:option value=""></smvc:option>
										<c:forEach var="formGroup" items="${meetingForm.formDomain.children}">
											<optgroup label="<c:out value="${formGroup.label}"/>">
												<c:forEach var="formDef" items="${formGroup.children}">
													<c:if test="${formDef.liveStatus != 0}">
														<smvc:option value="${formDef.path}"><c:out value="${formDef.label}"/></smvc:option>
													</c:if>
												</c:forEach>
											</optgroup>
										</c:forEach>
								</smvc:select>
							</td>
						</tr>
						<tr>
							<td class="label">Summary</td>
							<td class="input">
								<smvc:select path="meeting.summaryId">
									<smvc:option value=""></smvc:option>
									<c:forEach var="summary" items="${meetingForm.patientSummaryList}">
								 		<smvc:option value="${summary.id}"><c:out value="${summary.title}"/></smvc:option>
									</c:forEach>
								</smvc:select>
							</td>
						</tr>
						<tr>
                            <td class="label" colspan="2">
                                Notes:
                            </td>
                        </tr>
						<tr>
                            <td class="label" colspan="2" align="center">
                                <smvc:textarea rows="12" cols="80" path="meeting.notes" id="meetingnotes"  readonly="${readOnly}"/>
                            </td>
                        </tr>
						<tr>
                            <td class="label" colspan="2">
                                <!-- spacer -->
                            </td>
                        </tr>
                        <tr>
							<td align="left">
								<sec:authorize access="hasAnyRole('MEETING_ADMIN','ADMIN')" >
									<c:choose>
										<c:when test="${meetingForm.locked eq 'false'}">
											<c:if test="${fn:length(meetingForm.meetingId) gt 0 and meetingForm.pastMeeting eq 'true'}">
													<input type="button" value="Lock Meeting" onclick="confirmLockMeeting()"/>
											</c:if>
										</c:when>
										<c:otherwise>
											<c:if test="${fn:length(meetingForm.meetingId) gt 0}">
												<input type="button" value="Unlock Meeting" onclick="unlockMeeting()" style="display: none;"/>
											</c:if>
										</c:otherwise>
									</c:choose>
									<c:if test="${meetingForm.locked eq false}">
										<c:choose>
											<c:when test="${fn:length(meetingForm.meetingId) gt 0}">
												<input type="button" value="Delete" onclick="deleteMeeting()"/>
											</c:when>
											<c:otherwise>
												<input type="button"  value="Delete" onclick="deleteMeeting()" disabled="disabled"/>
											</c:otherwise>
										</c:choose>
									</c:if>
                                </sec:authorize>
                            </td>
							<td align="right">
								<c:if test="${meetingForm.locked ne 'true'}">
									<input type="button" value="cancel" onclick="cancel()" />&nbsp;
                                    <input type="button" value="Save" onclick="this.disabled=true; this.value='Saving...'; update(this)" />
                                 </c:if>
							</td>
						</tr>
						<tr>
						<td align="center" colspan="2">
							<c:if test="${meetingForm.locked eq true}">
								<span class="info">This meeting is locked: changes are not permitted.</span>
							</c:if>
						
                 	</table>
                </div>
                </div>
            </td>
        </tr>
    </table>
		
		<br/>

		<%@ include file="meetingsNavigationPanel.include.jsp"%>
		
		<br/>
		
		</td>
	</tr>
</table></smvc:form></c:if>
