<%@page import="com.ardeo.util.PropertiesUtils"%>
<%@page import="java.util.Properties"%>
<%@ include file="/includes.jsp"%>
<jsp:useBean id="helper" scope="page" class="com.ardeo.autoforms.FileUploadDispatcher"/>

<script type="text/javascript">
function setClinicians(){
	var table = document.getElementById("clinicianTblId");
	if (table == null)
		return;
	var rowCount = table.rows.length;
	var str = "";
	if (rowCount > 0) {
		for ( var i = 0; i < rowCount; i++) {
			str = str + " " + table.rows[i].cells[2].innerHTML + ",";
		}
		
		document.getElementById('clinicianList').value = str;
	}
}

function showAttachmentInCommentsPage(){
	var name = document.getElementById('my_file'); 
	var fileToUpload  = document.getElementById('attachedDocumentDisplay');
	fileToUpload.innerHTML = "";

	var size =  name.files.item(0).size;
    var sizeText;
	if (size > 1024*1024)
        sizeText = "(" + (Math.floor(size / (1000000))) + " MB)";
	else
        sizeText = "(" + (Math.floor(size / 1000)) + " KB)";
	var fileText = "File to attach: '" + document.getElementById('patientDocumentMetaDatatitle').value + "'";
	fileToUpload.innerHTML = fileText + " " + sizeText;
	disablePopup('attachFilePopupStrutsId','');
	fileToUpload.style.display='block';

}

function saveComments() {
	document.getElementById('saveCommentsButton').disabled=true;
	// file attachment is optional
	if (document.getElementById('attachFileCommentsDivId'))
		document.getElementById('attachFileCommentsDivId').innerHTML="";
	var comment  = document.getElementById('comments').value;
	comment = trimAll(comment);
	var formName = document.getElementById("formName");
	var fileControl = document.getElementById('my_file');
	var fileAttached;
	if (fileControl != null)
		fileAttached = fileControl.value;
	setClinicians();
	var formValue=null;
	if(formName!=null){
		formValue = document.getElementById("formName").value;
	}
	var maxLen = 64000;
	if((comment == null || (trimAll(comment).length === 0))  && !fileAttached){
		alert("Notes cannot be blank: please enter a comment or attach a document ");
		document.getElementById('saveCommentsButton').disabled=false;
		return false;
	}
	if((comment!=null && trimAll(comment).length>maxLen)){
		alert("Maximum " + maxLen + " characters only");
		document.getElementById('saveCommentsButton').disabled=false;
		return false;
	} else {
		document.getElementById("actionRequired").value = "savecomments";
		fullScreenPleaseWait();
		preSubmit();
		document.getElementById("consultationNote").submit();
	}
}
function trimAll(sString){
	while (sString.substring(0,1) == ' '){
		sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' '){
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
} 
if (!String.prototype.trim) {
	  (function() {
	    // Make sure we trim BOM and NBSP
	    var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
	    String.prototype.trim = function() {
	      return this.replace(rtrim, '');
	    };
	  })();
}
	
function submitForm(action,fileName){
	document.getElementById("actionRequired").value=action;
	document.getElementById("fileName").value=fileName;
	document.getElementById("consultationNote").submit();
}
function commentsFileDeleteAction(fileNameSel) {
	if(confirm("Are you sure that you want to delete the file?")){
		document.getElementById("actionRequired").value= "commentsFileDelete";
		document.getElementById("fileName").value=fileNameSel;
		document.getElementById("consultationNote").submit();
	}
}
function addClinician() {
	var table = document.getElementById("clinicianTblId");
	var rowCount = table.rows.length;
	var userName = document.getElementById('clinician').value;
	var fullname = document.getElementById(userName).value;
	if (rowCount > 0) {
		for ( var i = 0; i < rowCount; i++)
			if (table.rows[i].cells[2].innerHTML == userName) {
				alert("Clinician '" + fullname + "' is already present");
				return false;
			}
	}
	var row = table.insertRow(rowCount);
	row.setAttribute("id", "cliniciantable" + userName);

	var column = row.insertCell(0);
	column.setAttribute("width", "70%");
	var element = document.createTextNode(fullname);
	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");
	element.setAttribute("id", "removecomment");
	var newlink = document.createElement('a');
	newlink.appendChild(element);
	var value1="cliniciantable"+userName;
	newlink.setAttribute("onclick", "deleteRow('"+value1+"','clinicianTblId');");
	newlink.setAttribute("onmouseover", "this.style.cursor = cursorPointer");
	column.appendChild(newlink);
	var column = row.insertCell(2);
	column.style.display = 'none';
	var element = document.createTextNode(userName);
	column.appendChild(element);
}
function deleteRow(row, tableId) {
	var isProceed = true;
	if (!confirm("Don't notify this clinician?")) {
		isProceed = false;
	}
	if (isProceed) {
		var table = document.getElementById(tableId);
		var tableRow = document.getElementById(row);
		tableRow.parentNode.removeChild(tableRow);

	}
}

</script>

<%-- Show comments UI on forms --%>
<div id="commentsDiv" class="commentsBox" >
<div class="commentsHeading"><img
	src="../images/16x16/comments.png" /> Notes <br />
&nbsp;</div>

<table>
	<c:forEach var="report" items="${commentsList}">
	<c:set var="filename" value="${report.attachedNotes}" />
	<%--
	not sure why we are doing this, but it prevented the comments from displaying
		<c:if test="${formView.currentPageIndex eq report.formPageIndex }">
	 --%>
			<tr>
				<td width="20%" class="commentsUserName"><c:out value="${report.username}"/><br/><c:out value="${report.hospitalCode}"/></td>
				<td width="60%" class="commentsText"><pre><c:out value="${report.comment}"/></pre></td>
				<td width="20%" class="commentsDate"><fmt:formatDate value="${report.dateOfComment}" pattern="dd MMM yyyy, HH:mm" /></td>
			</tr>
			<c:if test="${! empty report.notifyingUsers}">
			<tr>
				<td class="commentsUserName"></td>
				<td class="commentsText">Notified users: <c:choose><c:when test="${! empty report.notifyingUsers}"><c:out value="${report.notifyingUsers}"/></c:when><c:otherwise>-</c:otherwise></c:choose></td>
				<td></td>
			</tr>
			</c:if>
			<c:if test="${not empty(report.attachedNotes)}">
			<tr>
				<td class="commentsText"><input type="hidden" name="fileName" id="fileName" /></td>
				<td class="commentsAttachments">
					<c:set var="actualfileName" value="${report.attachedNotes}"></c:set>
					<% String filename=(String)pageContext.getAttribute("actualfileName"); %>
					<a href="#" onclick="javascript:submitForm('commentsFileView','<%=helper.escapeJavaScript(filename)%>');" title="Click to View or download file" > 
					<img src="../images/16x16/page.png" alt="Document" /> 
					<%int dotIndex =  ((String)pageContext.getAttribute("actualfileName")).lastIndexOf(".");%>
					<%int underScoreIndex =  ((String)pageContext.getAttribute("actualfileName")).indexOf("_Cnid");%>
					<c:set var="dotIndex" value="<%=dotIndex%>" /> 
					<c:set var="underScoreIndex" value="<%=underScoreIndex%>" /> 
					<c:out value="${fn:substring(report.attachedNotes, 0, underScoreIndex)}${fn:substring(report.attachedNotes, dotIndex, fn:length(report.attachedNotes))}" />
					</a>
				&#160;&#160; <a href="#" class="commentsAttachmentsDelete" onclick="commentsFileDeleteAction('<%=helper.escapeJavaScript(filename)%>');"
				title="Delete file..."><img src="../images/delete.png" alt="Delete" />Delete</a>
				</td>
				<td></td>
			</tr>
			</c:if>
			<tr>
				<td colspan="3">
				<hr color="lightgray" size="1" />
				</td>
			</tr>
			<%--
		</c:if>
			 --%>
	</c:forEach>



	<tr>
		<td class="commentsLabel">Entry text - Include treatment stage and reason:</td>
		<td colspan="2">
		<textarea id="comments" name="comments" cols="80" rows="3" <c:if test="${(consultationNoteForm.view.note.id eq null)}"> disabled="disabled"</c:if> ></textarea></td>
	</tr>
	<c:if test="${(consultationNoteForm.view.form.allowNotesAttachment)}">
		<tr>
			<td class="commentsLabel">Attach Document:</td>
			<td colspan="2"><c:choose>
					<c:when test="${(consultationNoteForm.view.note.id eq null)}">
                        <input type="file" onchange="setFileSize(this);" name="notesUpload" id="my_file" disabled="disabled"/>
                    </c:when>
					<c:otherwise>
                        <div>
                            <input type="button" value="Add File" onclick="openAttachFilePopupStruts('attachFileCommentsDivId');"/> <span id="attachedDocumentDisplay" class="commentsText"></span>
                        </div>

                        <div id="attachFileCommentsDivId"  style="display: none;">
								File:<input type="file" name="notesUpload" id="my_file" onchange="setFileSize(this);setTitle();"/> &#160;
								<input type="button" name="attachBtn" value="Attach" onclick="showAttachmentInCommentsPage();"/><br />
							</div>
					</c:otherwise>
				</c:choose> 
			</td>
			
		</tr>
	</c:if>

		<c:if test="${consultationNoteForm.view.form.allowNotification}">
			<tr>
				<td class="commentsLabel">Notify users at:</td>
				<td align="left" valign="top" colspan="4">
					<select id="clinician" name="clinician">
						<c:forEach var="userCategory" items="${webapp.userCategory}">
							<c:if test="${userCategory.name eq  consultationNoteForm.view.form.notifingUsers}">
								<c:forEach var="usersByHospitalMap" items="${webapp.usersByHospitalIdMap}">
									<optgroup label="<c:out value="${webapp.hospMap[usersByHospitalMap.key]}"/>">
										<c:forEach var="userId" items="${usersByHospitalMap.value}">
											<c:forEach var="pair" items="${userCategory.pairs}">
												<c:if test="${pair.first eq webapp.userIdUsernameMap[userId] }">
													<option value="${pair.first}"><c:out value="${pair.second}"/></option>
												</c:if>
											</c:forEach>
										</c:forEach>
									</optgroup>
								</c:forEach>
							</c:if>
						</c:forEach>
					</select>
					<c:forEach var="userCategory" items="${webapp.userCategory}">
						<c:if test="${userCategory.name eq  consultationNoteForm.view.form.notifingUsers}">
							<c:forEach var="pair" items="${userCategory.pairs}">
								<input type="hidden" id="<c:out value="${pair.first}"/>" value="<c:out value="${pair.second}"/>"/>
							</c:forEach>
						</c:if>
					</c:forEach>
				 	<a onclick="addClinician();" title="Add selected Clinician"> <img
						src="../images/add.png" border="0" alt="Add" id="Addcomment"
						onmouseover="this.style.cursor = cursorPointer;" /></a></td>
			</tr>

			<tr>
				<td class="commentsLabel"><input type="hidden"
					name="clinicianList" id="clinicianList"></td>
				<td colspan="2">

					<table width="40%" id="clinicianTblId">
						<c:if test="${fn:length(clinicianList)>0}">
							<c:forEach var="user" items="${clinicianList}" varStatus="i">
								<tr id="cliniciantable<c:out value="${user.name}"/>">
									<td><c:out value="${user.name}"/></td>
									<td align="center"><a
										onclick="deleteRow('cliniciantable<c:out value="${user.name}"/>','clinicianTblId')">
											<img src="../images/delete.png" border="0" alt="Delete"
											onmouseover="this.style.cursor = cursorPointer; " />
									</a></td>
									<td style="display: none;"><c:out value="${user.username}"/></td>
								</tr>
							</c:forEach>
						</c:if>
					</table>
				</td>
			</tr>
		</c:if>
		<tr>
		<td>&nbsp;</td>
		<c:if test="${(consultationNoteForm.view.note.id ne null)}">
			<td colspan="2"> <div class="rightSaveDiv" id="saveCommentsButton"  onclick="saveComments();"><br /> Add note</div></td>
		</c:if>
		<c:if test="${(consultationNoteForm.view.note.id eq null)}">
			<td colspan="2"> <div class="rightSaveDivDisabled"><br />Add note</div> </td>
		</c:if>
	</tr>
</table>
</div>