<%@page import="com.ardeo.entities.autoforms.FormView"%>
<%@ include file="/includes.jsp"%>
<%@ taglib prefix="smvc" uri="http://www.springframework.org/tags/form"%>
<%@ page session="true" %>
<link href="../referrals/css/main.css" type="text/css" rel="stylesheet" />
<script type="text/javascript">
	function preSubmit() {
		//ensure multi-selections are selected
		var selectTags = document.getElementsByTagName("select");
		for(var i = 0; i < selectTags.length; i++) {
			if(selectTags[i].multiple) {
				var options = selectTags[i].options;
				for(var y = 0; y < options.length; y++) {
					options[y].selected = true;
				}
			}		
		}
		return true;
	}
	
	function addEvent(dateFieldId, title) {
		var dateField = document.getElementById(dateFieldId);
		if(dateField) {
			if(!title) title = "";
			var date = dateField.value;
			window.open("../calendar/editEventPopup.jsp?forward=closeWindow&id=new&type=event&date=" + date + "&title=" + title,'editEvent','scrollbars=1,toolbar=0,status=1,menubar=1,resizable=1,location=0,directories=0,width=700,height=500,left=0,top=0');
		}
	}
	function lockForm(){
		var res=confirm("This form will be locked and no further changes will be possible. This change is not reversible.\n\nPlease confirm you want to proceed");
		if(res){
			document.getElementById("actionRequired").value = "lockForm";
			document.getElementById("consultationNote").submit();
		}
	}
	function setStyleOnLoad() {
		var tables = document.getElementsByTagName("TABLE");
		for ( var k = tables.length - 1; k >= 0; k -= 1) {
			var table = tables[k];
			if (table != null && table.id.indexOf('dynamicTableId') != -1) {
				var rows = table.getElementsByTagName('tr'), i, j, cells, field;
				for (i = 2, j = rows.length; i < j; ++i) {
					cells = rows[i].getElementsByTagName('td');
					if (!cells.length) {
						continue;
					}
					field = $.trim(cells[0].innerHTML)+"_styles";
					if (document.getElementById(field)) {
						var styleValue = document.getElementById(field).value;
						if (styleValue != null && styleValue != '' && styleValue != 'null' && styleValue != 'undefined' && styleValue != '000000000000') {
							if (styleValue.charAt(0) == '1') {
								cells[0].style.fontWeight = 700;
							} else {
								cells[0].style.fontWeight = 400;
							}
							if (styleValue.charAt(1) == '1') {
								cells[0].style.fontStyle = "italic";
							} else {
								cells[0].style.fontStyle = "";
							}
							if (styleValue.charAt(2) == '1') {
								cells[0].style.textDecoration = "underline";
							} else {
								cells[0].style.textDecoration = "";
							}
							cells[0].style.fontSize = styleValue.substring(3, 5)
									+ 'pt';
							cells[0].style.color = styleValue.substring(5, 12);
						}
					}
				}
			}
		}
	}
	// Set form editor styles when page has loaded
	$(document).ready(function(){
		   setStyleOnLoad();
		   if(document.getElementById("noteModifiedByOtherUser").value == 'yes'){
			   openNoteModificationPopup();
		   }
	});
	document.body.onchange=updateFields;
	function updateFields(e){
		var o = e.target || e.srcElement;
		var tagType =  o.type;	
		var editedFieldName = o.id;
		updateBanding(editedFieldName);
		updateCalculationFields(editedFieldName,tagType)
	}

	function updateBanding(referencedFieldName) {
		var referencedFieldValue = document.getElementById(referencedFieldName).value;
		var data=document.getElementById("csrfparameterName").value;
		data=data+"="+document.getElementById("csrfparametervalue").value;
		$.ajax({
			type : "POST",
			url : "../emdt/bandingDetails.form",
			data : "referencedFieldValue=" + referencedFieldValue + "&referencedFieldName=" + referencedFieldName + "&" + data,
			success : function(msg) {
				if (msg.resultLength >0) {
					for (var j = 0; j< msg.resultLength; j++) {
						var fieldName=msg.result[j][0];
						var fieldType=msg.result[j][1];
						var value=msg.result[j][2];
						document.getElementById(fieldName).value= value;
						var elem = document.getElementById("bandingFieldDiv"+fieldName);
						if(fieldType==11){
							var assignColor=msg.result[j][3];
							elem.style.color = assignColor;
						}else{
							updateCalculationFields(fieldName,document.getElementById(fieldName).nodeName)
						}
						elem.innerHTML = value;
					}
						
				}else if (msg.resultLength ==-1) {
					alert(msg.result)
				}
			}
		});
	}
	
	function updateCalculationFields(editedFieldName, tagType) {
        if (tagType == "checkbox" || tagType == "radio") {
            if (!document.getElementById('includesCount_'+editedFieldName))
                return;
			editedFieldName=document.getElementById('includesCount_'+editedFieldName).value;
        }
		var form = document.getElementById('consultationNote');
 		for (var i = 0; i < form.length; i++) {
			if (form.elements[i].id.indexOf('calculationField_') == 0 && form.elements[i].value.indexOf(editedFieldName) >0) {
				var res = form.elements[i].id.replace("calculationField_", "");
				document.getElementById("onChangeCalculation").value = "score";
				document.getElementById("actionRequired").value = "userCmd";
				document.getElementById("actionButton").value = res;
				preSubmit();
				var data= new FormData($('#consultationNote')[0]);
				var csrfdata=document.getElementById("csrfparameterName").value;
				csrfdata=csrfdata+"="+document.getElementById("csrfparametervalue").value;
				$.ajax({
					type: "POST",
				   	url: "../emdt/consultationNote.form?" + csrfdata,
				   	enctype: 'multipart/form-data',
				   	data : data,
				   	processData: false,
		          	contentType: false,
				   	success: function(msg){
				   		if ((!(msg.indexOf('noResultCalculated')> -1 && msg.indexOf('noResultCalculated')=='noResult' )) && msg.indexOf('resultFieldName') > -1 && msg.indexOf('result') > -1){
				   		   var str = msg.substr(1).slice(0, -1);
	                       var str_array = str.split(',');
	                       var result_array = str_array[0].split(':');
	                       var resultFieldName_array =  str_array[1].split(':');
	                       if(resultFieldName_array[1]!== undefined && result_array[1]!== undefined){
	                    	   var currentId=resultFieldName_array[1].substr(1).slice(0, -1);
		                       var currentValue=result_array[1].substr(1).slice(0, -1);
		                       var elt=  document.getElementById(currentId);
		                       elt.value=currentValue;
		                       updateBanding(currentId);
		                       updateCalculationFields(currentId,elt.nodeName)
	                       }
				   		}
				   	} 
			  });
			}
		}
		document.getElementById("onChangeCalculation").value = "";
	}
	function send() {
		if (confirm('Please confirm that you want to send this message to the referrer')) {
			if ("true" == document.getElementById('roleSupportingStaff').value) {
				chooseSeniors();
			} else {
				document.getElementById("actionRequired").value = "save";
				preSubmit();
				document.getElementById("consultationNote").submit();
			}

		}
	}
</script>
<script type="text/javascript" src="../emdt/tiles/fileContent.js"></script>
<c:choose>
<c:when test="${redirectPageTo ne null and fn:length(redirectPageTo)  gt 0}">
<input type="hidden" id="redirectpath" value="<c:out value="${redirectPageTo}"/>"/>
<script type="text/javascript">
	var filterFormId = getURLParameter('filterFormId');
	document.location=document.getElementById('redirectpath').value+"?filterFormId="+filterFormId;
	
	function getURLParameter(name) {
		var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
		return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
	}
</script>
</c:when>
<c:otherwise>
<smvc:form modelAttribute="consultationNoteForm" id="consultationNote" enctype="multipart/form-data" action="../emdt/consultationNote.form?${_csrf.parameterName}=${_csrf.token}">
 	<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" id="redirectParams" name="redirectParams" value="<c:out value="${requestScope['javax.servlet.forward.query_string']}"/>" />
 	<%@ include file="attachFilePopupInForms.jsp" %>
 	<input id="overrideModifications" name="overrideModifications" value="no" type="hidden"/>
	<c:choose>
		<c:when test="${noteModifiedByOtherUser eq true }">
			<input id="noteModifiedByOtherUser" value="yes"  type="hidden" />
			<%@ include file="noteModifiedDetailPopup.jsp"%>
		</c:when>
		<c:otherwise>
			<input id="noteModifiedByOtherUser" value="no"  type="hidden" />
		</c:otherwise>
	</c:choose>
	<smvc:errors cssClass="error" path="*"></smvc:errors>
	<c:set var="currentFormView" value="${consultationNoteForm.view}"></c:set>
	<%
		FormView currentFormView = (FormView)pageContext.getAttribute("currentFormView");
	    session.setAttribute("currentFormView",currentFormView) ;
	 %>
	<smvc:hidden path="letterPath" />
	<input type="hidden" name="onChangeCalculation" id="onChangeCalculation" value="" />
	<smvc:hidden path="actionRequired" id="actionRequired"  />
	<input type="hidden" name="actionButton" id="actionButton" value="" />
	<input type="hidden" name="gotoPageNum" id="gotoPageNum"/>
	<input type="hidden" id="childListId2Filter" name="childListId2Filter" value=""/>
	<input type="hidden" id="parentListName" name="parentListName" value=""/>
	<div class="container">
		<tiles:insertTemplate template ="emdtFormMenu.jsp" ></tiles:insertTemplate>
		<div class="containerSubPage">
			<c:if test="${requestScope.errorMsg ne null}">
				<span class="error"><c:out value="${requestScope.errorMsg}"/></span>
			</c:if>
			<c:if test="${requestScope.noteSavedSuccess ne null}">
				<span class="info"><c:out value="${requestScope.noteSavedSuccess}"/></span>
			</c:if>
			<div class="rowDivSubPage">
				<div class="fieldSetBoxSub fieldSetBoxSubWidth">
					<c:if test="${consultationNoteForm.view.note.locked eq true}">
						<div style="color:red"><img src="images/16x16/locked.png"/>This form is locked</div>
					</c:if>
					<a href="javascript:patientHistory('<c:out value="${consultationNoteForm.view.form.id}"/>', '<c:out value="${consultationNoteForm.view.form.name}"/>');">
					<div class="leftSaveDiv">
						<br /> Show History/Make new Form
					</div></a>
					<sec:authorize access="hasAnyRole('MEETING_ADMIN','ADMIN')">
						<c:if test="${consultationNoteForm.view.note.locked ne true}">
							<a href="javascript:lockForm();">
							<div class="centerSaveSmallDiv" id="lockForm">
								<br /> Lock Form
							</div></a>
						</c:if>
					</sec:authorize>
					<c:if test="${consultationNoteForm.view.note.locked ne true}">
						<a href="javascript:save()"><div id="save" class="rightSaveSmallDiv" ><br /><c:out value="${consultationNoteForm.view.buttonValue}"/></div></a>
					</c:if>
					<c:set var="consultationNotePath" value="${consultationNoteForm.view.renderer}"></c:set>
					<tiles:insertTemplate template="${consultationNotePath}" />
					<br/>
					<c:if test="${consultationNoteForm.view.form.showNotes}">
						<tiles:insertTemplate template ="commentsPage.jsp"/>
					</c:if>
				</div><br/>
			</div>
			<c:choose>
				<c:when test="${'FormList' eq basePage}">
					&nbsp;
				</c:when>
				<c:otherwise>
					<tiles:insertTemplate template ="consultationNoteButtons.jsp"/>
				</c:otherwise>
			</c:choose>
		</div>
	</div>
	<c:if test="${consultationNoteForm.view.note.locked }">
		<div style="color:red">--Locked by '<c:out value="${consultationNoteForm.view.note.lockedBy }"/>' since <fmt:formatDate value="${consultationNoteForm.view.note.lockedSince}" pattern="HH:mm" />--</div>
	</c:if>
	
</smvc:form>
</c:otherwise>
</c:choose>
