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

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

<jsp:include page="../shared/inc_expenditureDetail.jsp">
	<jsp:param name="resultCallbackMethod"
		value="refreshGeneralLedgerTable" />
	<jsp:param name="getGPFBalanceMapFn" value="getGPFBalanceMap" />
</jsp:include>

<jsp:include page="../shared/inc_adjustmentDetail.jsp">
	<jsp:param name="resultCallbackMethod"
		value="refreshGeneralLedgerTable" />
	<jsp:param name="getGPFBalanceMapFn" value="getGPFBalanceMap" />
</jsp:include>

<script>
	var isReadOnly = ${FORM_READ_ONLY}
	var canCreateExpenditures = false
	var ledgerEntries = []
	
	var gpfBalances = {}
	
	<sec:authorize
	access="hasAnyAuthority('${PERMISSION_EDONATION_MANAGE}')">
		canCreateExpenditures = true
	</sec:authorize>

	$(function() {
		buildGeneralLedgerTable()
		
		if ("<c:out value="${dateRangeType}" />" != "") {
			$("#dateRangeType").val("<c:out value="${dateRangeType}" />")
		} else {
			$("#dateRangeType option:eq(0)").prop('selected', true)
		}
		
		if ("<c:out value="${specificFY}" />" != "") {
			$("#specificFY").val("<c:out value="${specificFY}" />")
		} else {
			$("#specificFY option:eq(0)").prop('selected', true)
		}
		
		if ("<c:out value="${specificStartMonth}" />" != "") {
			$("#specificStartMonth").val("<c:out value="${specificStartMonth}" />")
		} else {
			$("#specificStartMonth option:eq(0)").prop('selected', true)
		}
		
		if ("<c:out value="${specificStartYear}" />" != "") {
			$("#specificStartYear").val("<c:out value="${specificStartYear}" />")
		} else {
			$("#specificStartYear option:eq(0)").prop('selected', true)
		}
		
		if ("<c:out value="${specificEndMonth}" />" != "") {
			$("#specificEndMonth").val("<c:out value="${specificEndMonth}" />")
		} else {
			$("#specificEndMonth option:eq(0)").prop('selected', true)
		}
		
		if ("<c:out value="${specificEndYear}" />" != "") {
			$("#specificEndYear").val("<c:out value="${specificEndYear}" />")
		} else {
			$("#specificEndYear option:eq(0)").prop('selected', true)
		}
		
		$("#dateRangeType").change(function() {
			$(".specificFYInput").toggle("specificfy" == $(this).val())
			$(".specificMonthsInput").toggle("custom" == $(this).val())
		})
		$("#dateRangeType").trigger('change')
		
		refreshGeneralLedgerTable()
	})
	
	function getGPFBalanceMap(callback) {
		if (!$.isEmptyObject(gpfBalances))
			callback(gpfBalances)
	}
	
	function getStartAndEndDate() {
		var dateRangeType = $("#dateRangeType").val()
		var startDate = null
		var endDate = null
		
		if (dateRangeType == 'specificfy') {
			var selectedOpt = $("#specificFY option:selected")
			startDate = selectedOpt.attr('startdate')
			endDate = selectedOpt.attr('enddate')
		} else if (dateRangeType == 'custom') {
			startDate = pad($("#specificStartMonth").val(), 2) + '/01/' + $("#specificStartYear").val()
			endDate = pad($("#specificEndMonth").val(), 2) + '/01/' + $("#specificEndYear").val()
		} else {
			startDate = $("#dateRangeType option:selected").attr('startDate')
			endDate = $("#dateRangeType option:selected").attr('endDate')
		}
		
		return {
			startDate : startDate,
			endDate : endDate
		}
	}
	
	function getTotalsRow() {
		var newRow = ['Total']
    	for (var i = 1; i <= 4; i++)
    		newRow.push($("#totalRow td:eq(" + i + ")").text())
    	return newRow
	}
	
	function buildGeneralLedgerTable() {
		var theDataTable = $('#generalLedgerList').DataTable({
			buttons: [{
	            extend: 'excelHtml5',
	            customizeData: function(docModel) {
	            	var totalsRow = getTotalsRow()
	            	docModel.body.splice(0, 0, totalsRow)
	            },
	            customize: function( xlsx ) {
	                var sheet = xlsx.xl.worksheets['sheet1.xml'];
	                $('row:eq(1) c', sheet).attr( 's', '5' );
	            }
	        }, {
				extend : 'pdfHtml5',
				orientation : 'landscape',
				customize: function(docObj) {
					var totalsRow = getTotalsRow()
					docObj.content[1].table.body.splice(1, 0, totalsRow)
	            }
			}, {
				extend : 'print',
				customize: function(win) {
					// $(win.document.body).find('table').addClass('display').css('font-size', '9px');
	                $(win.document.body).find('tr:nth-child(odd) td').each(function(index){
	                    $(this).css('background-color','#D0D0D0');
	                });
	                
	                var html = $('<tr />', win.document)
	                var totalsRow = getTotalsRow()
					for (var i = 0; i < totalsRow.length; i++)
						html.append($('<td style="border-bottom:2px solid black" />', win.document).text(totalsRow[i]))
	                $(win.document.body).find('table').prepend(html);
	                
	                $(win.document.body).find('h1').css('text-align','center');
	            },
	            autoPrint : false
			}],
			"columns" : [ {
		        	"render" : function(row, type, val, meta) {
		        		if (!val.gpf) return ''
		        		
		        		var dateRangeType = $("#dateRangeType").val()
		        		var specificStartMonth = $("#specificStartMonth").val()
		        		var specificStartYear = $("#specificStartYear").val()
		        		var specificEndMonth = $("#specificEndMonth").val()
		        		var specificEndYear = $("#specificEndYear").val()
		        		
		        		if (type === 'display')
							return '<a href="' + homePath + '/ledgerDaily.htm?donGenPostFundId=' + val.gpf.id + '&dateRangeType=' 
									+ dateRangeType
									+ (dateRangeType == 'specificfy' ? '&specificFY=' + $("#specificFY").val() : '')
									+ (dateRangeType == 'custom' ? '&specificStartMonth=' + specificStartMonth
										+ '&specificStartYear=' + specificStartYear
										+ '&specificEndMonth=' + specificEndMonth
										+ '&specificEndYear=' + specificEndYear : '')
									+ '" class="appLink"><nobr>'
									+ val.gpf.generalPostFund + '</nobr></a>'
						return val.gpf.generalPostFund
		        	}
				}, {
					"render" : function(row, type, val, meta) {
						if (type === 'display')
							return "$" + formatAndAddThousandSeparators(val.balance)
						return val.balance
					} 
				}, {
					"render" : function(row, type, val, meta) {
						if (type === 'display') {
							var x = getStartAndEndDate()	
						
							return '<a class="appLink" href="' + homePath + '/donationList.htm?listDonationsMode=timeperiodsearch&startDate='
								+ x.startDate + '&endDate=' + x.endDate + '">$' + formatAndAddThousandSeparators(val.donationTotal)
								+ '</a> <a href="javascript:popupDonorSearch(\'menuAdd\')"><img align="right" style="margin-right:5px" src="'
								+ imgHomePath + '/add.png" border="0" /></a>'
						}
						return val.donationTotal
					}
				}, {
					"render" : function(row, type, val, meta) {
						if (!val.gpf) return ''
						var dateRangeType = $("#dateRangeType").val()
						
						if (type === 'display') {
							var x = getStartAndEndDate()
							
							return '<a href="' + homePath + '/expenditureList.htm?donGenPostFundId=' + val.gpf.id + '&startDate='
									+ x.startDate + '&endDate=' + x.endDate + '" class="appLink">$' + formatAndAddThousandSeparators(val.expenditureTotal)
									+ '</a> <a href="javascript:newExpenditure(' + val.gpf.id + ')"><img align="right" style="margin-right:5px" src="'
									+ imgHomePath + '/add.png" border="0" /></a>'
						}
						return val.expenditureTotal
					}
				}, {
					"render" : function(row, type, val, meta) {
						if (type === 'display') {
							var x = getStartAndEndDate()
							
							return '<a href="' + homePath + '/ledgerAdjustmentList.htm?donGenPostFundId=' + val.gpf.id + '&startDate='
								+ x.startDate + '&endDate=' + x.endDate + '" class="appLink">$' + formatAndAddThousandSeparators(val.ledgerAdjustmentTotal)
								+ '</a> <a href="javascript:newAdjustment(' + val.gpf.id
								+ ')"><img align="right" style="margin-right:5px" src="' + imgHomePath + '/add.png" border="0" /></a>'
						}
						return val.ledgerAdjustmentTotal
					}
				}
			],
	    	"dom": '<"top"fBi>rt<"bottom"pl><"clear">',
	    	"lengthMenu" : [ [ 20, 50, -1 ],
	    	 				[ 20, 50, "All" ] ],
			"order": [],
	    	"pageLength": 20,
	    	"pagingType": "full_numbers",
	    	"stripeClasses" : [],
	    	"drawCallback" : function() {
	    		var totals = [0, 0, 0, 0]
	    		
	    		for (var i = 0; i < ledgerEntries.length; i++) {
	    			totals[0] += ledgerEntries[i].balance
	    			totals[1] += ledgerEntries[i].donationTotal
	    			totals[2] += ledgerEntries[i].expenditureTotal
	    			totals[3] += ledgerEntries[i].ledgerAdjustmentTotal
	    		}
	    		for (var i = 0; i < 4; i++)
					$("#totalRow td:eq(" + (i+1) + ")")
							.text('$'+ formatAndAddThousandSeparators(totals[i]));
			}
		})
	}
	
	function refreshGeneralLedgerTable() {
		var dateRangeType = $("#dateRangeType").val()
		var specificFY = $("#specificFY").val()
		var specificStartMonth = $("#specificStartMonth").val()
		var specificStartYear = $("#specificStartYear").val()
		var specificEndMonth = $("#specificEndMonth").val()
		var specificEndYear = $("#specificEndYear").val()
		
		window.history.replaceState({}, '', homePath + '/ledger.htm?dateRangeType=' + dateRangeType
				+ (dateRangeType == 'specificfy' ? '&specificFY=' + specificFY : '')
				+ (dateRangeType == 'custom' ? '&specificStartMonth=' + specificStartMonth
						+ '&specificStartYear=' + specificStartYear
						+ '&specificEndMonth=' + specificEndMonth
						+ '&specificEndYear=' + specificEndYear : ''))
		
		$.ajax({
			url : ajaxHomePath + '/ledger/summary',
			dataType : 'json',
			data : {
				"dateRangeType" : dateRangeType,
				"specificFY" : specificFY,
				"specificStartMonth" : specificStartMonth,
				"specificStartYear" : specificStartYear,
				"specificEndMonth" : specificEndMonth,
				"specificEndYear" : specificEndYear
			},
			error : commonAjaxErrorHandler,
			success : function(response) {
				ledgerEntries = response
				
				gpfBalances = {}
				for (var i = 0; i < response.length; i++)
					gpfBalances[response[i].gpf.id] = response[i].balance
				
				var table = $('#generalLedgerList').DataTable()
				table.clear()
				table.rows.add(response)
				table.draw()				
		    }
		})
	}
</script>

<style>
#generalLedgerList tr.serviceRow {
	background-color: #dddddd;
}

#generalLedgerList {
	border-collapse: collapse;
	min-width: 400px;
}

#generalLedgerList td {
	margin: 3px;
}
</style>

<div class="clearCenter">
	<table>
		<tr>
			<td align="right">Date Range:</td>
			<td><select id="dateRangeType">
					<option value="fy"
						startDate="<vss:localDate date="${currentfy[0]}" pattern="${TWO_DIGIT_DATE_ONLY}" />"
						endDate="<vss:localDate date="${currentfy[1]}" pattern="${TWO_DIGIT_DATE_ONLY}" />">Current Fiscal Year</option>
					<option value="lastfy"
						startDate="<vss:localDate date="${lastfy[0]}" pattern="${TWO_DIGIT_DATE_ONLY}" />"
						endDate="<vss:localDate date="${lastfy[1]}" pattern="${TWO_DIGIT_DATE_ONLY}" />">Previous Fiscal Year</option>
					<option value="specificfy">Other Fiscal Year</option>
					<option value="month"
						startDate="<vss:localDate date="${month[0]}" pattern="${TWO_DIGIT_DATE_ONLY}" />"
						endDate="<vss:localDate date="${month[1]}" pattern="${TWO_DIGIT_DATE_ONLY}" />">Current Month</option>
					<option value="lastmonth"
						startDate="<vss:localDate date="${lastmonth[0]}" pattern="${TWO_DIGIT_DATE_ONLY}" />"
						endDate="<vss:localDate date="${lastmonth[1]}" pattern="${TWO_DIGIT_DATE_ONLY}" />">Previous Month</option>
					<option value="custom">Specific Month(s)</option>
			</select></td>
			<td width="30">&nbsp;</td>
			<td class="specificFYInput" style="display: none">
				<table>
					<tr>
						<td align="right">Fiscal Year:</td>
						<td><select id="specificFY"><c:forEach begin="0"
									end="${currentFY - 1995}" var="i">
									<c:set var="y">${currentFY - i}</c:set>
									
									<option value="${y}"
										startDate="<vss:localDate date="${fyDates[y][0]}" pattern="${TWO_DIGIT_DATE_ONLY}" />"
										endDate="<vss:localDate date="${fyDates[y][1]}" pattern="${TWO_DIGIT_DATE_ONLY}" />"><c:out value="${y}" /></option>
								</c:forEach></select></td>
					</tr>
				</table>
			</td>
			<td width="30" class="specificFYInput" style="display: none">&nbsp;</td>
			<td class="specificMonthsInput" style="display: none">
				<table>
					<tr>
						<td align="right">Start Month/Year:</td>
						<td><select id="specificStartMonth"><c:forEach items="${allMonths}" var="m">
							<option value="${m.value}"><c:out value="${m.key}" />
								<c:out value="(${m.value})" />
							</option>
						</c:forEach></select> <select id="specificStartYear"><c:forEach begin="0"
									end="${currentFY - 1995}" var="i">
									<c:set var="y">${currentFY - i}</c:set>
									
									<option value="${y}"><c:out value="${y}" /></option>
								</c:forEach></select></td>
					</tr>
					<tr>
						<td align="right">End Month/Year:</td>
						<td><select id="specificEndMonth"><c:forEach items="${allMonths}" var="m">
							<option value="${m.value}"><c:out value="${m.key}" />
								<c:out value="(${m.value})" />
							</option>
						</c:forEach></select> <select id="specificEndYear"><c:forEach begin="0"
									end="${currentFY - 1995}" var="i">
									<c:set var="y">${currentFY - i}</c:set>
									
									<option value="${y}"><c:out value="${y}" /></option>
								</c:forEach></select></td>
					</tr>
				</table>
			</td>
			<td width="30" class="specificMonthsInput" style="display: none">&nbsp;</td>
			<td><a class="buttonAnchor"
				href="javascript:refreshGeneralLedgerTable()">Submit</a></td>
		</tr>
	</table>
</div>

<div id="generalLedgerWrapper" class="clearCenter"
	style="max-width: 75%">
	<fieldset>
		<legend>General Ledger</legend>

		<table class="formatTable" id="generalLedgerList" border="1"
			summary="General Ledger">
			<thead>
				<tr id="totalRow">
					<td class="noborder">TOTAL</td>
					<td class="noborder"></td>
					<td class="noborder"></td>
					<td class="noborder"></td>
					<td class="noborder"></td>
				</tr>
				<tr>
					<th>General Post Fund</th>
					<th>Current Balance</th>
					<th>Total Donations</th>
					<th>Total Expenditures</th>
					<th>Total Adjustments</th>
				</tr>
			</thead>
			<tbody>
			</tbody>
		</table>
	</fieldset>
</div>
