
<%@ include file="../shared/inc_header.jsp"%>

<c:if test="${FORM_READ_ONLY}">
	<%@ include file="../shared/inc_modifyToView.jsp"%>
</c:if>

<c:if
	test="${command.organization.persistent}">

		<jsp:include page="/WEB-INF/jsp/shared/inc_jqueryTable.jsp">
				<jsp:param name="dataTableId" value="localBranchList" />
				<jsp:param name="refreshDataMethod" value="localBranchRefreshData" />
			</jsp:include>
		
		<%@ include
			file="/WEB-INF/jsp/organization/localBranchDetail.jsp"%>
</c:if>


<script type="text/javascript">
	var fromPage = "<c:out value="${command.fromPage}" default=""/>"
	var organiazationPersistent = <c:out value="${command.organization.persistent}" default="false"/>
	var isProcessingEDonation = <c:out value="${command.processingEDonation}" default="false"/>
	
$(function() {	
		<c:if test="${command.organization.scope == 'NATIONAL'}">
		
			<c:if test="${command.organization.persistent}">
				refreshOfficialsTable();
			</c:if>
		
			var isNACVal = ${command.organization.onNationalAdvisoryCommittee == 'true'}
				setupNACFields(isNACVal, true);
			
			$("input[name='organization.onNationalAdvisoryCommittee']:radio").on('change', function() {	
				setupNACFields(($(this).val() == "true"), false);
			}) 
		</c:if>
		
		<c:if
			test="${command.organization.persistent}">
			refreshLocalBranchTable()
		</c:if>
})


	var officialsList = new Object()
	
	function refreshOfficialsTable() {
	 	officialsList = new Object()
		
		$.ajax({
			url : ajaxHomePath + '/nationalOfficialList',
			dataType : 'json',
			data : {
				 orgId: '${command.organization.id}'
			},
			error : commonAjaxErrorHandler,
			success : function(response) {
				/* array of rows */
				
				var rArray = new Array()
				var curDate = new Date()
				for (var i = 0; i < response.length; i++) {
					officialsList[response[i].id] = response[i]
					
					/* array of columns for current row */
					rArray[rArray.length] = new Array(									
							'<a href="javascript:showOfficialDetailsPopup(' + response[i].id + ', ${command.organization.id}' + ')">'+ 
							escapeHTML(response[i].stdVAVSTitle ? response[i].stdVAVSTitle.name : 'None') +'</a>',
										escapeHTML(response[i].prefix),
						escapeHTML(response[i].lastName), 
						escapeHTML(response[i].firstName), 
						escapeHTML(response[i].middleName), 
						escapeHTML(response[i].certifyingOfficial ? 'Yes' : 'No'), 
						'<div style="margin:0 auto; text-align:center"><a class="confirm" alt="Delete Entry" title="Are you sure you want to delete this official?" href="javascript:deleteOfficial('
								+ response[i].id + ')"><img alt="Delete Entry" src="'+ imgHomePath + '/permanently_delete_18x18.png" border="0" hspace="5" align="center"/></a></div>')
				}

				/* generated by inc_jqueryTable.jsp, see below */
				officialsRefreshData(rArray)
			}
		})
	}
	
	var localBranchList = new Object()
	var popupAlreadyShown = false
	
	function refreshLocalBranchTable() {
	 	localBranchList = new Object()
		
		$.ajax({
			url : ajaxHomePath + '/localBranchList',
			dataType : 'json',
			data : {
				 orgId: '${command.organization.id}'
			},
			error : commonAjaxErrorHandler,
			success : function(response) {
				/* array of rows */
				
				var rArray = new Array()
				var curDate = new Date()
				for (var i = 0; i < response.length; i++) {
					localBranchList[response[i].id] = response[i]
					
					/* array of columns for current row */
					rArray[rArray.length] = new Array(		
							escapeHTML(response[i].facility ? response[i].facility.displayName : ''), 
							'<a href="javascript:showLocalBranchPopup(' + response[i].id + ', ${command.organization.id}' + ')">'+ 
							escapeHTML(response[i].name) +'</a>',
							escapeHTML(response[i].contactName),
							escapeHTML(response[i].contactTitle), 
							'<span><pre>' + escapeHTML(response[i].addressMultilineDisplay) + '</pre></span>', 
							getDisplayEmail(response[i].email),
							escapeHTML(response[i].active? 'Active' : 'Inactive')
						)
				}
	
				/* generated by inc_jqueryTable.jsp, see below */
				localBranchRefreshData(rArray)
				$('select', '#localBranchStatusFilter').val('Active')
				$('select', '#localBranchStatusFilter').change()
				<c:if test="${not empty branchLoad}">
					if (!popupAlreadyShown) {
						showLocalBranchPopup("${branchLoad}", "${command.organization.id}")
						popupAlreadyShown = true
					}
				</c:if>
			}
		})
	}
		
	function deleteOfficial(officialId) {
		var fullObj = officialsList[officialId]
	
		confirmDialog('Are you sure you want to delete this National Official ' + fullObj.lastName + ', ' + fullObj.firstName + '?',
		function() {
			$.ajax({
				url : ajaxHomePath + '/nationalOfficialDelete',
				dataType : 'json',
				data : {
					officialId: officialId
				 },
				
				error : commonAjaxErrorHandler,
				success : function() {
					/* generated by inc_jqueryTable.jsp, see below */
					refreshOfficialsTable()
			    }
			})
		})
	}  
	
	function setupNACFields(isNACVal, isPageLoad) {
		if (isNACVal) {
			$("#nacExecutiveMemberRadioButtonId1").prop("disabled", false);
			$("#nacExecutiveMemberRadioButtonId2").prop("disabled", false);
			if (!isPageLoad) {
				$("#nacStatusSelect").val("-1");
			}
			$("#nacStatusSelect").prop("disabled", false);
			$("#ajrMonthSelect").prop("disabled", false);
		} else {
			$("#nacExecutiveMemberRadioButtonId2").prop('checked', true);
			$("#nacExecutiveMemberRadioButtonId1").prop("disabled", true);
			$("#nacExecutiveMemberRadioButtonId2").prop("disabled", true);
			if (!isPageLoad) {
				$("#nacStatusSelect").val("${inactiveNACStatus}");
			}
			$("#nacStatusSelect").prop("disabled", true);
			$("#ajrMonthSelect").prop("disabled", true);
		}
	
	}
	
	function getDisplayEmail(emailTxt) {
		var emailHtml = ""
			if (emailTxt)
				emailHtml = escapeHTML(emailTxt) + '<a href="mailto:'
						+ escapeHTML(emailTxt)
						+ '"><img alt="Click to email '
						+ escapeHTML(emailTxt) + '"' + 'src="' + imgHomePath
						+ '/envelope.jpg" height="14"'
						+ ' width="18" border="0" align="absmiddle"'
						+ ' style="padding-left: 4px; padding-right: 4px" /></a>'
		return emailHtml
	}


var wasFullNamePopulated = ("${command.organization.fullName}".length > 0);

	$(function() {
		$("#submitButton").click(submitForm);
		
		$("#displayNameInput").change(function() {
			if (!wasFullNamePopulated) {
				$("#fullNameInput").val($("#displayNameInput").val());
			}
		})
		
		/*
		$("#displayNameInput").autocomplete({
			source : function(request, response) {
				var theVal = $.trim($("#displayNameInput").val())
				if (theVal == '') return
				
				var ajaxParms = []
				ajaxParms.push({name: 'wt', value: 'json'})
				ajaxParms.push({name: 'omitHeader', value: 'true'})
				ajaxParms.push({name: 'fl', value: 'name'})
				ajaxParms.push({name: 'fl', value: 'scope'})
				ajaxParms.push({name: 'fl', value: 'id'})
				ajaxParms.push({name: 'q', value: 'name:' + theVal.match(/\S+/g).join(' name:')})
				
				$.ajax({
					url : "${solrBaseURL}/organizations/select/",
					data : $.param(ajaxParms),
					dataType : 'jsonp',
					jsonp : 'json.wrf',
					success : function(data) {
						var docs = JSON.stringify(data.response.docs)
						var jsonData = JSON.parse(docs)
						response($.map(jsonData, function(value, key) {
							return {
								label : value.name,
								// replace this with value.id if needed
								value : value.name
								// , category : value.scope == 'L' ? 'Local' : 'National',
							}
						}))
					},
					error: function() {
						console.log("Couldn't communicate with SOLR.")
					}
				})
			},
			minLength : 1
		})
		*/
		
		
		<c:if test="${command.organization.persistent && command.organization.inactive == 'true' }">
			// When editing an inactive org, the record is readonly except for the Status field
			$('.organizationInputFields input', '#appContainerDiv').not(".keepEnabledForInactive").attr(
				'disabled', 'disabled')
			$('.nacInputFields input', '#appContainerDiv').attr(
				'disabled', 'disabled')
			$('.contactInputFields input', '#appContainerDiv').attr(
				'disabled', 'disabled')
				
			$('#organizationForm select', '#appContainerDiv').each(
					function() {
						var selectedVal = $(this).find("option:selected").val();
						if (selectedVal == "-1" || selectedVal == "") {
							$(this).replaceWith("None")
						} else {
							$(this).replaceWith(
									escapeHTML($(this).find("option:selected")
											.text()))
						}
					})
			$('.requdIndicator', '#appContainerDiv').remove()
		</c:if>

		var isLocalOrg = ${command.organization.scope == 'LOCAL'}
		$('.nacInputFields').toggle(!isLocalOrg)

	})

	function submitForm(evt) {
		if (evt != null) {
			doubleClickSafeguard($(evt.currentTarget));
		}
		
	    if (!validate()) return;
	    
	    <c:if test="${command.organization.active}">
	    if ($("#statusRadioId2").is(":checked")) {
	    	confirmDialog('Are you sure you want to inactivate this organization?<p><span class="redText" style="font-weight:bold">ALL volunteers assigned to this organization (or to any of its branches) will have their organizations inactivated!</span>', function() {
	    		$('#organizationForm').submit()
	    	})
	    } else {
	    	$('#organizationForm').submit()
	    }
	    </c:if>
	    <c:if test="${command.organization.inactive}">
	    	$('#organizationForm').submit()
	    </c:if>
	}
	
	function validate() {
	    var errors = new Array();
	 
	   	if ($.trim($("#displayNameInput").val()) == '') {
			errors.push("Display Name is required.")
		}
	       
	   	if ($.trim($("#fullNameInput").val()) == '') {
			errors.push("Full Name is required.")
		}

	   	if ($.trim($("#typeSelect").val()) == '-1') {
			errors.push("Type is required.")
		}
	   	
	   	if ($("input[name='organization.onNationalAdvisoryCommittee']:checked").val() == "true") {
		  if ($('#nacStatusSelect').val() == "-1") {
		   errors.push("Membership Status is required for NAC Members.");
		  }
		}
		
		var thePhone = $("#contactPhoneInput").val()
		if ($.trim(thePhone) != '' && !validatePhone(thePhone)) {
			errors.push('Please enter a valid phone number.')
		}
		
		var theEmail = $("#contactEmailInput").val()
		if ($.trim(theEmail) != '' && !validateEmail(theEmail)) {
			errors.push('Please enter a valid email address.')
		}

		if (errors.length > 0) {
		   displayAttentionDialog("Please correct the following errors: <ul><li>"
		                 + errors.join("</li><li>") + "</li></ul>");                   
		}
		
		return errors.length == 0;
	}
	
	function cancelOrgForm(orgId) {
	 	var redirectPage = ''
	 
	 	if (isProcessingEDonation) {
	 		redirectPage = 	'manageDonationLog.htm'
	 	} else {
		 	redirectPage = organiazationPersistent ? 'organizationEdit.htm?id=' + orgId : 'organizationCreate.htm'
	 	} 
	 	    document.location.href = homePath + '/' + redirectPage;
	}
</script> 


<style>
.ui-autocomplete-category {
	font-weight: bold;
	padding: .2em .4em;
	margin: .8em 0 .2em;
	line-height: 1.5;
}
</style>

<form:form method="post" action="${home}/organizationSubmit.htm"
	id="organizationForm">
	<div class="clearCenter">
		<div class="leftHalf organizationInputFields">
			<fieldset>
				<legend>Organization</legend>
				<table>
					<tr>
						<td class='appFieldLabel' nowrap>Facility:</td>
						<td></td>
						<td style="text-align: left"><c:out
								value="${command.organization.scope}" /> <c:if
								test="${command.organization.scope == 'LOCAL'}">
								-- <c:out
									value="${command.organization.facility.displayName}" />
							</c:if></td>
					</tr>
					
					<tr>
						<td class='appFieldLabel' nowrap><label
							for='displayNameInput'>Display Name: <span
								class="invisibleRequiredFor508">*</span>
						</label></td>
						<td style="padding: 4px; text-align: left"><span
							class='requdIndicator'>*</span></td>
						<td style="text-align: left"><app:input id="displayNameInput"
								path="organization.name" size="50" maxLength="50" /> <app:errors
								path="organization.name" cssClass="msg-error" /></td>
					</tr>

					<tr>
						<td class='appFieldLabel'><label for='fullNameInput'>Full
								Name: <span class="invisibleRequiredFor508">*</span>
						</label></td>
						<td style="padding: 4px; text-align: left"><span
							class='requdIndicator'>*</span></td>
						<td style="text-align: left"><app:input id="fullNameInput"
								path="organization.fullName" size="50" maxLength="255"/> <app:errors
								path="organization.fullName" cssClass="msg-error" /></td>
					</tr>

					<tr>
						<td class='appFieldLabel'><label for='abbreviationInput'>Abbreviation:</label></td>
						<td></td>
						<td style="text-align: left"><app:input
								id="abbreviationInput" path="organization.abbreviation" size="6"
								maxLength="6" /> <app:errors path="organization.abbreviation"
								cssClass="msg-error" /></td>
					</tr>
					<tr>
						<td class='appFieldLabel'><label for='typeSelect'>Type:
								<span class="invisibleRequiredFor508">*</span>
						</label></td>
						<td style="padding: 4px; text-align: left"><span
							class='requdIndicator'>*</span></td>
						<td style="text-align: left"><app:select id="typeSelect"
								path="organization.type" itemLabel="name" itemValue="id">
								<form:option value="-1" label="-- Select --" />
								<form:options items="${allTypes}" itemValue="id"
									itemLabel="name" />
							</app:select> <app:errors path="organization.type" cssClass="msg-error" /></td>
					</tr>
					
					<tr>
						<td class='appFieldLabel'><label for='statusRadio'>Status:
								<span class="invisibleRequiredFor508">*</span>
						</label></td>
						<td style="padding: 4px; text-align: left"><span
							class='requdIndicator'>*</span></td>
						<td style="text-align: left"><form:radiobutton
								id="statusRadioId1" cssClass="keepEnabledForInactive"
								path="organization.inactive" value="false" />Active <form:radiobutton
								id="statusRadioId2" cssClass="keepEnabledForInactive"
								path="organization.inactive" value="true" />Inactive <app:errors
								path="organization.inactive" cssClass="msg-error" /></td>
					</tr>

				</table>
			</fieldset>
		</div>
		
		<div class="rightHalf nacInputFields">
			<fieldset>
				<legend> National Advisory Committee </legend>
				<table>
					<tr>
						<td class='appFieldLabel' nowrap>Member? <span
							class="invisibleRequiredFor508">*</span>
						</td>
						<td style="padding: 4px; text-align: left"><span
							class='requdIndicator'>*</span></td>
						<td style="text-align: left"><form:radiobutton
								id="nacRadioButtonId1"
								path="organization.onNationalAdvisoryCommittee" value="true" />Yes
							<form:radiobutton id="nacRadioButtonId2"
								path="organization.onNationalAdvisoryCommittee" value="false" />No
							<app:errors path="organization.onNationalAdvisoryCommittee"
								cssClass="msg-error" /></td>
					</tr>

					<tr>
						<td class='appFieldLabel' nowrap>Executive Member?</td>
						<td></td>
						<td style="text-align: left"><form:radiobutton
								id="nacExecutiveMemberRadioButtonId1"
								path="organization.nacExecutiveMember" value="true" />Yes <form:radiobutton
								id="nacExecutiveMemberRadioButtonId2"
								path="organization.nacExecutiveMember" value="false" />No <app:errors
								path="organization.nacExecutiveMember" cssClass="msg-error" /></td>
					</tr>

					<tr>
						<td class='appFieldLabel'>Membership Status:</td>
						<td></td>
						<td style="text-align: left"><app:select id="nacStatusSelect"
								path="organization.nacMembershipStatus">
								<form:option value="-1" label="-- Select --" />
								<form:options items="${allNacStatuses}" itemValue="id"
									itemLabel="membershipStatus" />
							</app:select> <app:errors path="organization.nacMembershipStatus"
								cssClass="msg-error" /></td>
					</tr>

					<tr>
						<td class='appFieldLabel'>Annual Joint Review (AJR) Month:</td>
						<td></td>
						<td style="text-align: left"><app:select id="ajrMonthSelect"
								path="organization.annualJointReviewMonth">
								<form:option value="" label="-- Select --" />
								<form:options items="${allMonths}" itemValue="value" />
							</app:select> <app:errors path="organization.annualJointReviewMonth"
								cssClass="msg-error" /></td>
					</tr>
				</table>
			</fieldset>
		</div>
		
		<div class="clearCenter contactInputFields">
			<fieldset>
			<legend>Contact Information</legend>
				<div class="leftHalf">
				<table>
					<tr>
						<td class='appFieldLabel'><label for='contactNameInput'>Name:</label></td>
						<td></td>
						<td style="text-align: left"><app:input id="contactNameInput"
								path="organization.contactName" size="35" maxLegnth="255" /> <app:errors
								path="organization.contactName" cssClass="msg-error" /></td>
					</tr>
					<tr>
						<td class='appFieldLabel'><label for='contactTitleInput'>Title:</label></td>
						<td></td>
						<td style="text-align: left"><app:input id="contactTitleInput"
								path="organization.contactTitle" size="35" maxLegnth="255" /> <app:errors
								path="organization.contactTitle" cssClass="msg-error" /></td>
					</tr>
					<tr>
						<td class='appFieldLabel'><label for='contactPhoneInput'>Phone:</label></td>
						<td></td>
						<td style="text-align: left"><app:input id="contactPhoneInput" cssClass="phoneextmask"
								path="organization.phone" size="20"/> <app:errors
								path="organization.phone" cssClass="msg-error" /></td>
					</tr>			
					<tr>
							<td class='appFieldLabel'><label for='contactEmailInput'>Email:</label></td>
							<td></td>
							<td><app:input id="contactEmailInput" size="35" maxLegnth="250" path="organization.email" />
								<a href="javascript:emailInputContent('orgEmail')"><img
									alt='Click to email contact' src="${imgHome}/envelope.jpg"
									height="14" width="18" border="0" align="absmiddle"
									style="padding-left: 4px; padding-right: 4px" /></a>
									<app:errors path="organization.email"
									cssClass="msg-error" /></td>
					</tr>
				</table>
			</div>
			
				<div class="rightHalf">
					<table>
						<tr>
							<td class='appFieldLabel'><label for='contactAddressLine1Input'>Address Line 1:</label></td>
							<td></td>
							<td style="text-align: left"><app:input id="contactAddressLine1Input"
									path="organization.addressLine1" size="35" maxLegnth="35" /> <app:errors
									path="organization.addressLine1" cssClass="msg-error" /></td>
						</tr>
						<tr>
							<td class='appFieldLabel'><label for='contactAddressLine2Input'>Address Line 2:</label></td>
							<td></td>
							<td style="text-align: left"><app:input id="contactNameInput"
									path="organization.addressLine2" size="35" maxLegnth="35" /> <app:errors
									path="organization.addressLine2" cssClass="msg-error" /></td>
						</tr>
						<tr>
							<td class='appFieldLabel'><label for='contactCityInput'>City:</label></td>
							<td></td>
							<td style="text-align: left"><app:input id="contactCityInput"
									path="organization.city" size="35" maxLegnth="30" /> <app:errors
									path="organization.city" cssClass="msg-error" /></td>
						</tr>
						<tr>
							<td class='appFieldLabel' nowrap><label for='contactStateSelect'>State:</label></td>
							<td></td>
							<td style="text-align: left" nowrap><app:select id="contactStateSelect"
										path="organization.state">
										<form:option value=""></form:option>
										<form:options items="${allStates}" itemLabel="name"
											itemValue="id" />
							</app:select><app:errors path="organization.state" cssClass="msg-error" /></td>
						</tr>
						<tr>
							<td class='appFieldLabel'><label for='contactZipInput'>Zip:</label></td>
							<td></td>
							<td style="text-align: left"><app:input id="contactZipInput"
									path="organization.zip" size="13" maxLegnth="10" /> <app:errors
									path="organization.zip" cssClass="msg-error" /></td>
						</tr>
						
				</table>
				</div>
			</fieldset>
		</div>
		
		<div class="clearCenter">
			<c:if test="${not FORM_READ_ONLY}">
				<a id="submitButton" class="buttonAnchor keepEnabledForInactive"
					href="#">Submit</a>
			</c:if>
			
			<a id="cancelFormButton" class="buttonAnchor keepEnabledForInactive"
				href="javascript:cancelOrgForm(${command.organization.id})">Cancel</a>
		</div>
	</div>
</form:form>

<c:if
	test="${command.organization.scope == 'NATIONAL' && command.organization.persistent}">
	<div class="clearCenter">
		<div class="nationalOfficialInputFields">
			<fieldset>
				<legend>National Officials</legend>

				<div align="center">
					<c:if test="${not FORM_READ_ONLY}">
						<a class="buttonAnchor" id="createButton"
							href="javascript:showOfficialDetailsPopup('',  ${command.organization.id} )">Add</a>
					</c:if>
				</div>
				<table id="officialsList" class="stripe"
					summary="List of National Officials">
					<thead>
						<tr>
							<th width="30%">VAVS Title</th>
							<th width="12%">Prefix</th>
							<th width="12%">Last Name</th>
							<th width="12%">First Name</th>
							<th width="12%">Middle Name</th>
							<th width="12%">National Certifying Official</th>
							<c:if test="${not FORM_READ_ONLY}">
								<th width="10%">Action</th>
							</c:if>
						</tr>
					</thead>
					<tbody>
					</tbody>
				</table>
			</fieldset>
		</div>
		<jsp:include page="/WEB-INF/jsp/shared/inc_jqueryTable.jsp">
				<jsp:param name="dataTableId" value="officialsList" />
				<jsp:param name="refreshDataMethod" value="officialsRefreshData" />
			</jsp:include>
		
		<%@ include
			file="/WEB-INF/jsp/organization/nationalOfficialDetail.jsp"%>
		
</c:if>

<c:if
	test="${command.organization.persistent}">

		<div class="orgLocalBranchInputFields">
			<fieldset>
				<legend>Local Branches</legend>

				<div align="center">
				<c:if test="${not facilityContextIsCentralOffice and command.organization.active == 'true'}">
					<sec:authorize access="hasAnyAuthority('${PERMISSION_ORG_CODE_LOCAL_CREATE}')">
						<a class="buttonAnchor" id="createButton"
							href="javascript:showLocalBranchPopup('',  ${command.organization.id} )">Add</a>
					</sec:authorize>
				</c:if>
				</div>
				<table id="localBranchList" class="stripe"
					summary="List of Local Branchs">
					<thead>
						<tr id="localBranchSearchFilterRow">
							<td class="noborder" title="Filter by Facility">Filters:</td>
							<td class="noborder" title="Filter by Local Branch"></td>
							<td class="noborder"></td>
							<td class="noborder"></td>
							<td class="noborder"></td>
							<td class="noborder"></td>
							<td class="noborder" id="localBranchStatusFilter" title="Filter by Status"></td>
						</tr>
					
						<tr>
							<th class="select-filter">Facility Name (#)</th>
							<th class="select-filter">Local Branch</th>
							<th>Contact Name</th>
							<th>Title</th>
							<th>Address</th>
							<th>Email</th>
							<th class="select-filter">Status</th>
						</tr>
					</thead>
					<tbody>
					</tbody>
				</table>
			</fieldset>
		</div>
			
	</div>
</c:if>