$(function() {
	$("#donationDetailsDialog").dialog({
		autoOpen : false,
		modal : true,
		width : 500,
		height : 300,
		closeOnEscape : false,
		draggable : true,
		resizable : true,
		buttons : {
			'Submit' : {
				text : 'Submit',
				id : 'donationDetailDialogSubmitBtn',
				click : submitDonationDetails
			},
			// 'Submit' : submitStaffDetails,
			'Cancel' : function() {
				$(this).dialog('close')
			},
		}
	})

	$("#donationDetailsDialog").show()
	/*
	 * Required to solve 508 issue not reading dialog box title. It is also
	 * required to disable dialog animation to enable this functionality
	 */
	$('#donationDetailsDialog').focus()
	
	refreshDonationDetails()
})

var donationDetailsList = new Object()

function showDonationDetailsPopup(donationDetailId) {
	var hasDonationDetailId = (typeof donationDetailId !== 'undefined')
	$("#donationDetailsDialog").data('donationDetailId', hasDonationDetailId ? donationDetailId : '')

	if (hasDonationDetailId) {
		var fullObj = donationDetailsList[donationDetailId]
		$("#generalPostFund").val(
				fullObj.donGenPostFund ? fullObj.donGenPostFund.id : '')
		$("#donationValue").val(fullObj.donationValue)
	}

	if (!hasDonationDetailId) {
		$("#generalPostFund").val('')
		$("#donationValue").val('')
	}

	$("#donationDetailsDialog").dialog('open')
}

var hasDonationDetailWithRealGPF = false

function refreshDonationDetails() {
	var myDonationSumId = donationSummaryId
	
	$.ajax({
				url : ajaxHomePath + '/donationDetails',
				dataType : 'json',
				data : {
					donationSummaryId : myDonationSumId ? myDonationSumId : 0
				},
				error : commonAjaxErrorHandler,
				success : function(response) {
					var rArray = new Array()
					
					var totalValue = 0
											
					hasDonationDetailWithRealGPF = false
					for (var i = 0; i < response.length; i++) {
						if (response[i].donGenPostFund.generalPostFund != gpfNoneValue)
								hasDonationDetailWithRealGPF = true
						totalValue += response[i].donationValue;
						donationDetailsList[response[i].id] = response[i]
						var newRow = new Array()
						if (!formReadOnly) {
							newRow.push('<a href="javascript:showDonationDetailsPopup('
									+ response[i].id
									+ ')">'
									+ escapeHTML(response[i].donGenPostFund.generalPostFund)
									+ '</a>')
						} else {
							newRow.push(escapeHTML(response[i].donGenPostFund.generalPostFund))
						}
						newRow.push(escapeHTML('$'+ formatAndAddThousandSeparators(response[i].donationValue)))
						newRow.push('<a href="javascript:deleteDonationDetail('
										+ response[i].id + ')"><img alt="Delete Donation GPF" src="'+ imgHomePath
										+ '/permanently_delete_18x18.png" border="0" hspace="40" align="center"/></a>')
						rArray[rArray.length] = newRow
					}
					
					$("#totalValueSpan").text(formatAndAddThousandSeparators(totalValue))
					
					$(".confirm").easyconfirm()
					
					refreshDonationDetailsData(rArray)
					// for the case switching donation type to Item/Activity,
					// after user delete all real GPF
					if(!hasDonationDetailWithRealGPF)  
							toggleTheFields()
				}
			})
}

function submitDonationDetails() {
	var myGeneralPostFund = $("#generalPostFund").val()
	if (myGeneralPostFund == '') {
		displayAttentionDialog('General Post Fund is required.')
		return
	}
			
	if ($('#donationValue').val() == '') {
		displayAttentionDialog("Donation Amount is required.")
		return
	}
		
	if ($('#donationValue').val() > 9999999999.99 ) {
		displayAttentionDialog("The maximum donation amount is 9999999999.99.")
		return
	}
			
	if ($('#donationValue').val() != ''
		&& !validateNumericWithoutCommas($('#donationValue').val())) {
		displayAttentionDialog("Donation Amount is invalid [format should be ########## or ##########.##].") 
		return
	}
	
	if (($("#generalPostFund").val() != "NONE") &&  ($('#donationTypeSelect').val() == '3' || $('#donationTypeSelect').val() == '4')) {
		displayAttentionDialog("The general post fund must be NONE for donation type Item/Activity.")
		return
	}

	/* If validations pass, submit to server - CPB */
	$.ajax({
		url : ajaxHomePath + '/donationDetailCreateOrUpdate',
		method : 'POST',
		dataType : 'json',
		data : {
			donationSummaryId : donationSummaryId,
			donationDetailId : $("#donationDetailsDialog").data(
					'donationDetailId'),
			generalPostFund : $("#generalPostFund").val(),
			donationValue : $("#donationValue").val(),
		},
		error : commonAjaxErrorHandler,
		success : function(response) {
			$("#donationDetailsDialog").dialog('close')
			/* generated by inc_jqueryTable.jsp, see below */
			
			
			refreshDonationDetails()
		}
	})
}