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

<script type="text/javascript">

$(function() {
	
	$("#localBranchDialog").dialog({
		autoOpen : false,
		modal : true,
		width : 950,
		height : 550,
		closeOnEscape : false,
		draggable : true,
		resizable : true,
		buttons : {
				'Submit' : {
					text : 'Submit',
					id : 'localBranchDialogSubmitButton',
					click : submitLocalBranchDetails
				},
			'Cancel' : function() {
				$(this).dialog('close')
			}
		}
	})
	
	$("input[name=localBranchStatus]").click(toggleScreen) 	
	
	$("#localBranchDialog").show()
	/*
	 * Required to solve 508 issue not reading dialog box title. It is also
	 * required to disable dialog animation to enable this functionality
	 */
	$('#localBranchDialog').focus()
})

function toggleScreen() {
	var isActive = $("#localBranchStatusActive").is(":checked")
	
	$('.localBranchInputFields input').not(".keepEnabledForInactive").prop('disabled', !isActive)
	$('.localBranchInputFields select').prop('disabled', !isActive)
}

function disableScreen(isDisabled) {
	$('#localBranchDialogSubmitButton').toggle(!isDisabled)
	$('.localBranchInputFields input').prop('disabled', isDisabled)
	$('.localBranchInputFields select').prop('disabled', isDisabled)
}

function showLocalBranchPopup(localBranchId, organizationId) {
	
	var isDisabled = true
	<sec:authorize access="hasAnyAuthority('${PERMISSION_ORG_CODE_LOCAL_CREATE}')">
		isDisabled = false
	</sec:authorize>
	
	$("#organizationId").val(organizationId)
	
	var hasLocalBranchId = (localBranchId != '' && typeof localBranchId !== 'undefined')
	
	if (hasLocalBranchId) {
		var fullObj = localBranchList[localBranchId]
		var branchFacilityId = fullObj.facility.id
		var currWorkingId = facilityContextId
		
		var isOrgActive = "<c:out value='${command.organization.active}'/>"
		if (!(facilityContextId == branchFacilityId &&  isOrgActive == 'true')) {
			isDisabled = true
		}

		$("#localBranchDialog").data('initialActiveStatus', fullObj.active)
		
		$("#localBranchId").val(localBranchId)
		$("#localBranchName").val(fullObj.name)
		$("input[name=localBranchStatus][value=" + (fullObj.active ? "true" : "false")
		                              + "]").prop("checked", true) 
		$("#branchContactName").val(fullObj.contactName)
		$("#branchContactTitle").val(fullObj.contactTitle)		
		$("#branchContactAddressLine1").val(fullObj.addressLine1)
		$("#branchContactAddressLine2").val(fullObj.addressLine2)
		$("#branchContactCity").val(fullObj.city)
		$("#branchContactStateSelect").val(fullObj.state ? fullObj.state.id : '')
		$("#branchContactZip").val(fullObj.zip)
		$("#branchContactPhone").val(fullObj.phone)
		$("#branchContactEmail").val(fullObj.email)
	}
	
	$("#localBranchDialog").dialog('open')
	
	if (!hasLocalBranchId) {	
		$("#localBranchId").val('')
		$("#localBranchName").val('')
		$("input[name=localBranchStatus][value=true"
		                              + "]").prop("checked", true)
		$("#branchContactName").val('')
		$("#branchContactTitle").val('')		
		$("#branchContactAddressLine1").val('')
		$("#branchContactAddressLine2").val('')
		$("#branchContactCity").val('')
		$("#branchContactStateSelect").val('')
		$("#branchContactZip").val('')
		$("#branchContactPhone").val('')
		$("#branchContactEmail").val('')
	}
	
	disableScreen(isDisabled)
	
	if (!isDisabled) 
		toggleScreen()
}

function submitLocalBranchDetails() {
    if (!validateLocalBranch()) return

    var currentActiveStatus = $("#localBranchDialog").data('initialActiveStatus')
    var newActiveStatus = $("#localBranchStatusActive").is(":checked")
    
    var finalSubmit = function() {
    	/* If validations pass, submit to server - CPB */
    	$.ajax({
    		url : ajaxHomePath + '/localBranchCreateOrUpdate',
    		method: 'POST',
    		dataType : 'json',
    		data : {
    			localBranchId: $("#localBranchId").val(),
    			organizationId: $("#organizationId").val(),
    			status: newActiveStatus,
    			branchName: $("#localBranchName").val(),
    			contactName: $("#branchContactName").val(),
    			contactTitle: $("#branchContactTitle").val(),
    			addressLine1:	$("#branchContactAddressLine1").val(),
    			addressLine2:	$("#branchContactAddressLine2").val(),
    			city: $("#branchContactCity").val(),
    			state: $("#branchContactStateSelect").val(),
    			zip: $("#branchContactZip").val(),
    			phone: $("#branchContactPhone").val(),
    			email: $("#branchContactEmail").val(),
    		},
    		error : commonAjaxErrorHandler,
    		success : function(response) {
    			$("#localBranchDialog").dialog('close')
    			<c:if test="${not empty branchLoad}">
    				document.location.href = homePath + "<c:out value="${targetSubmissionPage}" />"
    			</c:if>
    			<c:if test="${empty branchLoad}">
    				/* generated by inc_jqueryTable.jsp, see below */
    				refreshLocalBranchTable()
    			</c:if>
    	    }
    	})
    }
    
    if (currentActiveStatus && !newActiveStatus) {
	    var msg = 'Are you sure you want to inactivate this branch?'
		msg += ' <span  class="redText" style="font-weight:bold"><p>ALL volunteers assigned to this branch will have their branch association inactivated!</span>'
    	confirmDialog(msg, finalSubmit)
    } else {
    	finalSubmit()
    }
}

function validateLocalBranch() {
    var errors = new Array();

    /* Run some validations*/
	if ($("#organizationId").val() == '') {
		errors.push('Please select an organization first.')
	}
	
	if ($.trim($("#localBranchName").val()) == '') {
		errors.push("Local Branch Name is required.")
	}
	
	var theEmail = $("#branchContactEmail").val()
	if ($.trim(theEmail) != '' && !validateEmail(theEmail)) {
		errors.push('Please enter a valid email address.')
	}
	
	var thePhone = $("#branchContactPhone").val()
	if ($.trim(thePhone) != '' && !validatePhone(thePhone)) {
		errors.push('Please enter a valid phone number.')
	}

    if (errors.length > 0) {
        displayAttentionDialog("Please correct the following errors: <ul><li>"
                     + errors.join("</li><li>") + "</li></ul>");                   
    }

    return errors.length == 0;
}
</script>

<div id="localBranchDialog" style="display: none"
	title="Local Branch Detail">
	<input type="hidden" id="localBranchId" value="" /> <input type="hidden"
		id="organizationId" value="" />

	<div class="localBranchInputFields LocalBranchDisplay">
		<fieldset>
			<legend>Organization</legend>
			<div class="clearCenter">
				<table>
					<tr>
						<td class='appFieldLabel' nowrap>Scope:</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><span
							style="padding-left: 30px">Name:</span>
						<td></td>	
						</td>
						<td><c:out value="${command.organization.displayName}" /></td>
					</tr>
				</table>
			</div>
		</fieldset>
		
		<fieldset>
			<legend>Local Branch</legend>
			<div class="clearCenter">
				<table>
					<tr>
						<td class='appFieldLabel' nowrap><label for='localBranchName'>Local Branch Name:</label>
							<span class="invisibleRequiredFor508">*</span></td>
						<td><span class='requdIndicator'>*</span></td>
						<td><input type="text" id="localBranchName" size="50" title="Type a branch name" 
							maxLength="50" /></td>
					</tr>
					<tr>
						<td class='appFieldLabel' nowrap><label for='localBranchStatus'>Status</label>
						<span class="invisibleRequiredFor508">*</span>
						</td>
						<td><span class='requdIndicator'>*</span></td>
						<td><nobr>
								<input type="radio" class="keepEnabledForInactive" name="localBranchStatus"
									id="localBranchStatusActive" value="true" />Active <input
									type="radio" class="keepEnabledForInactive" name="localBranchStatus"
									id="localBranchStatusInactive" value="false" />Inactive
							</nobr></td>
					</tr>

				</table>
			</div>
		</fieldset>



		<fieldset>
			<legend>Contact Information</legend>
			<div class="clearCenter">
				<table>
					<tr>
						<td class='appFieldLabel' nowrap><label for='localBranchName'>Name:</label></td>
						<td></td>
						<td><input type="text" id="branchContactName" size="35" title="Type a branch contact name" 
							maxLength="255" /></td>
					</tr>
					<tr>
						<td class='appFieldLabel' nowrap><label for='branchContactTitle'>Title:</label></td>
						<td></td>
						<td><input type="text" id="branchContactTitle" title="Type a branch contact title" 
							size="35" maxLength="255" /></td>
					</tr>
					<tr>
						<td class='appFieldLabel' nowrap><label for='branchContactPhone'>Phone:</label></td>
						<td></td>
						<td><input type="text" id="branchContactPhone" class="phoneextmask" title="Type a branch contact phone" /></td>
					</tr>
				
					<tr>
						<td class='appFieldLabel' nowrap><label for='branchContactEmail'>Email:</label></td>
						<td></td>
						<td><input type="text" id="branchContactEmail" size="35" title="Type a branch contact email"
							maxLength="250" /> <a
							href="javascript:emailInputContent('localBranchEmail')"><img
								alt='Click to email Local Branch' src="${imgHome}/envelope.jpg"
								height="14" width="18" border="0" align="absmiddle"
								style="padding-left: 4px; padding-right: 4px" /></a></td>							
					</tr>
					<tr>
						<td class='appFieldLabel' nowrap><label for='branchContactAddressLine1'>Address Line 1:</label></td>
						<td></td>
						<td><input type="text" id="branchContactAddressLine1" size="35" title="Type branch address line 1"
							maxLength="35" /></td>
					</tr>
					<tr>
						<td class='appFieldLabel' nowrap><label for='branchContactAddressLine2'>Address Line 2:</label></td>
						<td></td>
						<td><input type="text" id="branchContactAddressLine2" size="35" title="Type branch address line 2"
							maxLength="35" /></td>
					</tr>
					<tr>
						<td class='appFieldLabel' nowrap><label for='branchContactCity'>City:</label></td>
						<td></td>
						<td><input type="text" id="branchContactCity" size="30" title="Type branch city"
							maxLength="30" /></td>
					</tr>
					<tr>
						<td class='appFieldLabel' nowrap><label for='branchContactStateSelect'>State:</label></td>
						<td></td>
						<td><select id="branchContactStateSelect">
								<option value=""> </option>
								<c:forEach items="${allStates}" var="state">
									<option value="${state.id}"><c:out
											value="${state.name}" /></option>
								</c:forEach>
						</select></td>					
					</tr>
					<tr>
						<td class='appFieldLabel' nowrap><label for='branchContactZip'>Zip:</label></td>
						<td></td>
						<td><input type="text" id="branchContactZip" size="13" title="Type branch zip"
							maxLength="10" /></td>
					</tr>
				</table>
			</div>
		</fieldset>

	
	</div>
</div>