var DEFAULT_INTEREST_RATE = 5.5;

if(document.getElementById)
{
	window.onload = onLoad;
}

function onLoad()
{
	setValidationEventHandlers();
	setTextareaMaxlengthEventHandlers();
	setExpenseWorksheetEventHandlers();
	setApprovedTermEventHandlers();
	calculateTotalExpenses();
	calculateDesiredTerm();
	setBorrowerAndCoborrowerTotalIncome();
	setAmountOverUnder();
	initializeAdminReports();
	setAdminEstimatedTerm();
}

function setAdminEstimatedTerm()
{
	if(document.getElementById("adminDesiredTerm") && document.getElementById("adminDesiredTerm").value == "" && document.getElementById("desiredTerm"))
	{
		document.getElementById("adminDesiredTerm").value = document.getElementById("desiredTerm").value;
	}
}

function setExpenseWorksheetEventHandlers() {
	if (document.getElementById("expenseWorkSheet")) {
		var inputs = document.getElementById("expenseWorkSheet").getElementsByTagName("input");
		for (i = 0; i < inputs.length; i++) {
			inputs[i].onblur = validateAndCalculateExpenseAmount;
		}
	}
}

function validateAndCalculateExpenseAmount() {
	if (this.value != "") {
		var thisMatch = this.value.replace(/[^\d.]/g, "").match(/\d*.?\d*/)
		if (thisMatch != "") {
			this.value = Math.round(this.value.replace(/[^\d.]/g,""));
		}
		else {
			showError(this, errorInvalidInteger)
		}
		calculateTotalExpenses();
	}
}

function calculateTotalExpenses() {
	if (document.getElementById("expenseWorkSheet") && document.getElementById("expensesTotal")) {
		var total = 0;
		var inputs = document.getElementById("expenseWorkSheet").getElementsByTagName("input");
		for (i = 0; i < inputs.length; i++)	{
			if (isFinite(inputs[i].value)) {
				total += Number(inputs[i].value);
			}
		}
		document.getElementById("expensesTotal").value = total;
	}
}

function createTotalExpensesContainer(borrowerTotalIncomeLabel, coborrowerTotalIncomeLabel, expenseTotalLabel, amountOverUnderLabel)
{
	document.write(	'<div class="fieldset">');

	//create the borrower total income text box (if available)
	createBorrowerTotalIncomeTextBox(borrowerTotalIncomeLabel);
	createcoborrowerTotalIncomeTextBox(coborrowerTotalIncomeLabel);
	createExpenseTotalIncomeTextBox(expenseTotalLabel);
	createAmountOverUnderTextBox(amountOverUnderLabel);

	document.write('</div>');
}

function createBorrowerTotalIncomeTextBox(label)
{
	document.write(	'<div>' +
						'<label for="borrowerTotalIncome">' + label + ': </label>' +
						'<input type="text" id="borrowerTotalIncome" name="borrowerTotalIncome" readOnly="readonly" value="0" />' +
					'</div>');
}

function createcoborrowerTotalIncomeTextBox(label)
{
	document.write(	'<div>' +
						'<label for="coborrowerTotalIncome">' + label + ': </label>' +
						'<input type="text" id="coborrowerTotalIncome" name="coborrowerTotalIncome" readOnly="readonly" value="0" />' +
					'</div>');
}

function setBorrowerAndCoborrowerTotalIncome()
{
	var borrowerTotalIncome = document.getElementById("borrowerTotalIncome");
	var coborrowerTotalIncome = document.getElementById("coborrowerTotalIncome");
	var amountOverUnderTextBox = document.getElementById("amountOverUnderTextBox");

	//make sure the appropriate fields exist before setting the total income values.
	//if the fields don't exist remove the two text boxes from the page.
	//Also the coborrower text boxes may not be on the page if the user has not filled out any coborrower information.
	if(		document.getElementById("borrowerCurrentEmployerGrossSalary") == null
		||	document.getElementById("borrowerCurrentEmployerNetSalary") == null
		||	document.getElementById("borrowerOtherIncomeMonthlyAmount") == null
		||	borrowerTotalIncome == null
		||	amountOverUnderTextBox == null)
	{
		if(borrowerTotalIncome != null)
			borrowerTotalIncome.parentElement.parentElement.removeChild(borrowerTotalIncome.parentElement);
		if(coborrowerTotalIncome != null)
			coborrowerTotalIncome.parentElement.parentElement.removeChild(coborrowerTotalIncome.parentElement);
		if(amountOverUnderTextBox != null)
			amountOverUnderTextBox.parentElement.parentElement.removeChild(amountOverUnderTextBox.parentElement);

		return;
	}

	//if it gets to here then the borrower total income and coborrower total income fields exist.
	var borrowerIncome = 0;

	if(isFinite(document.getElementById("borrowerOtherIncomeMonthlyAmount").value) == true)
		borrowerIncome += new Number(document.getElementById("borrowerOtherIncomeMonthlyAmount").value);

	//use the net salary if availble else use the gross salary.
	if(		isFinite(document.getElementById("borrowerCurrentEmployerNetSalary").value) == true
		&&	document.getElementById("borrowerCurrentEmployerNetSalary").value != "")
	{
		borrowerIncome += Number(document.getElementById("borrowerCurrentEmployerNetSalary").value);
	}
	else if(	isFinite(document.getElementById("borrowerCurrentEmployerGrossSalary").value) == true
			&&	document.getElementById("borrowerCurrentEmployerGrossSalary").value != "")
	{
		borrowerIncome += Number(document.getElementById("borrowerCurrentEmployerGrossSalary").value);
	}

	borrowerTotalIncome.value = borrowerIncome;

	var coborrowerIncome = 0;

	if(document.getElementById("coborrowerOtherIncomeMonthlyAmount") != null && isFinite(document.getElementById("coborrowerOtherIncomeMonthlyAmount").value) == true)
		coborrowerIncome += Number(document.getElementById("coborrowerOtherIncomeMonthlyAmount").value);

	//use the net salary if availble else use the gross salary.
	if(		document.getElementById("coborrowerCurrentEmployerNetSalary") != null
		&&	isFinite(document.getElementById("coborrowerCurrentEmployerNetSalary").value) == true
		&&	document.getElementById("coborrowerCurrentEmployerNetSalary").value != "")
	{
		coborrowerIncome += Number(document.getElementById("coborrowerCurrentEmployerNetSalary").value);
	}
	else if(	document.getElementById("coborrowerCurrentEmployerGrossSalary") != null
			&&	isFinite(document.getElementById("coborrowerCurrentEmployerGrossSalary").value) == true
			&&	document.getElementById("coborrowerCurrentEmployerGrossSalary").value != "")
	{
		coborrowerIncome += Number(document.getElementById("coborrowerCurrentEmployerGrossSalary").value);
	}
	coborrowerTotalIncome.value = coborrowerIncome;
}

function createExpenseTotalIncomeTextBox(label)
{
	document.write( '<div>' +
						'<label for="expensesTotal">' + label + ': </label>' +
						'<input type="text" id="expensesTotal" name="expensesTotal" readOnly="readonly">' +
					'</div>');
}

function createAmountOverUnderTextBox(label)
{
	document.write( '<div>' +
						'<label for="amountOverUnderTextBox">' + label + ': </label>' +
						'<input type="text" id="amountOverUnderTextBox" name="amountOverUnderTextBox" readOnly="readonly">' +
					'</div>');
}

function setAmountOverUnder()
{
	if(		document.getElementById("amountOverUnderTextBox") == null
		||	document.getElementById("borrowerTotalIncome") == null
		||	document.getElementById("coborrowerTotalIncome") == null
		||	document.getElementById("expensesTotal") == null)
	{
		return;
	}

	//figure out the amount over/under based on the combined income of the borrower and coborrower minus the total expenses.
	//also the value should be rounded to the nearest cent.
	document.getElementById("amountOverUnderTextBox").value = Math.round(100 * Math.abs(Number(document.getElementById("borrowerTotalIncome").value) + Number(document.getElementById("coborrowerTotalIncome").value) - Number(document.getElementById("expensesTotal").value))) / 100;
}

function createInterestRateTextBox(label) {
	document.write( 	'<div>' +
								'<label for="interestRate">' + label + ':</label>' +
								'<input type="text" id="interestRate" name="interestRate" readOnly="readonly" value="' + DEFAULT_INTEREST_RATE + '%">' +
								'</div>');
}

function createDesiredTermTextBox(label) {
	document.write( 	'<div>' +
								'<label for="desiredTerm">' + label + ':</label>' +
								'<input type="text" id="desiredTerm" name="desiredTerm" readOnly="readonly">' +
								'</div>');
}

function setApprovedTermEventHandlers() {
	if (document.getElementById("statusApprovedAmount") && document.getElementById("statusApprovedMonthlyPayment") && document.getElementById("statusInterestRate") && document.getElementById("statusApprovedTerm")) {
		document.getElementById("statusApprovedAmount").onblur = calculateApprovedTerm;
		document.getElementById("statusApprovedMonthlyPayment").onblur = calculateApprovedTerm;
		document.getElementById("statusInterestRate").onblur = calculateApprovedTerm;
		if(document.getElementById("statusApprovedTerm").value == "") {
			calculateApprovedTerm();
		}
	}
}

function calculateApprovedTerm() {
	// validate
	if (this.className != null) {
		var classList = " " + this.className.toLowerCase() + " "
		if (classList.indexOf("money") != -1) {
			validateInteger(this);
		}
		else if (classList.indexOf("percent") != -1) {
			validatePercent(this);
		}
	}
	if (document.getElementById("statusApprovedTerm") && document.getElementById("statusApprovedAmount") && document.getElementById("statusApprovedMonthlyPayment") && document.getElementById("statusInterestRate")) {
		var term = 0
		var loanAmount = Number(document.getElementById("statusApprovedAmount").value);
		var monthlyPayment = Number(document.getElementById("statusApprovedMonthlyPayment").value);
		var interestRate = Number(document.getElementById("statusInterestRate").value.replace(/%/, "")) / 100;
		term = -(Math.log(1 - (loanAmount / monthlyPayment) * (interestRate / 12)) / Math.log(1 + (interestRate / 12)));
		term = Math.round(term);
		if (isFinite(term)) {
			document.getElementById("statusApprovedTerm").value = term;
		}
	}
}

function calculateDesiredTerm() {
	if (document.getElementById("desiredTerm") && document.getElementById("fundingLoanAmount") && document.getElementById("fundingDesiredMonthlyPayment") && document.getElementById("interestRate")) {
		var term = 0
		var loanAmount = Number(document.getElementById("fundingLoanAmount").value);
		var monthlyPayment = Number(document.getElementById("fundingDesiredMonthlyPayment").value);
		var interestRate = Number(document.getElementById("interestRate").value.replace(/%/, "")) / 100;
		term = -(Math.log(1 - (loanAmount / monthlyPayment) * (interestRate / 12)) / Math.log(1 + (interestRate / 12)));
		term = Math.round(term);
		if (isFinite(term)) {
			document.getElementById("desiredTerm").value = term;
			
			if(document.getElementById("statusApprovedTerm") != null && document.getElementById("statusApprovedTerm").value == "")
			{
				document.getElementById("statusApprovedTerm").value = term;
			}
		}
	}
}

function setValidationEventHandlers() {
	var inputs = document.getElementsByTagName("input");
	for (i = 0; i < inputs.length; i++) {
		var classList = " " + inputs[i].className.toLowerCase() + " "
		if (classList.indexOf(" date ") != -1) {
			inputs[i].onblur = validateDate;
		}
		else if (classList.indexOf(" integer ") != -1) {
			inputs[i].onblur = validateInteger;
		}
		else if (classList.indexOf(" phone ") != -1) {
			inputs[i].onblur = validatePhone;
		}
		else if (classList.indexOf(" zip ") != -1) {
			inputs[i].onblur = validateZip;
		}
		else if (classList.indexOf(" ssn ") != -1) {
			inputs[i].onblur = validateSSN;
		}
		else if (classList.indexOf(" money ") != -1) {
			inputs[i].onblur = validateInteger;
		}
		else if (classList.indexOf(" percent ") != -1) {
			inputs[i].onblur = validatePercent;
		}
	}
}

function validateDate(field) {
	if (!field) { field = this; }
	if ((field.value != "") && (field.value.match(/^\d{1,2}[/-]\d{1,2}[/-]\d{4}$/) == null)) {
		var thisDate = new Date(field.value);
		if (isFinite(thisDate)) {
			var currentDate = new Date();
			if(thisDate.getFullYear() <= currentDate.getFullYear() - 100) {
				field.value = (thisDate.getMonth() + 1) + "/" + thisDate.getDate() + "/" + (thisDate.getFullYear() + 100);
			}
			else {
				field.value = (thisDate.getMonth() + 1) + "/" + thisDate.getDate() + "/" + thisDate.getFullYear();
			}
		}
		else {
			showError(field, errorInvalidDate)
		}
	}
}

function validateInteger(field) {
	if (!field) { field = this; }
	if (field.value != "") {
		var thisMatch = field.value.replace(/[^\d.]/g, "").match(/\d*.?\d*/)
		if (thisMatch != "") {
			field.value = Math.round(field.value.replace(/[^\d.]/g,""));
		}
		else {
			showError(field, errorInvalidInteger)
		}
	}
}

function validatePhone(field) {
	if (!field) { field = this; }
	if (field.value != "") {
		var thisMatch = field.value.replace(/\D/g, "").match(/(1?)(\d{3})(\d{3})(\d{4})/)
		if (thisMatch) {
			field.value = field.value.replace(/\D/g,"").replace(/(1?)(\d{3})(\d{3})(\d{4})\d*/,"($2) $3-$4");
		}
		else {
			showError(field, errorInvalidPhone)
		}
	}
}

function validateZip(field) {
	if (!field) { field = this; }
	if (field.value != "") {
		var thisMatch = field.value.replace(/\D/g, "").match(/(\d{5})(\d{4})?/)
		if (thisMatch) {
			field.value = field.value.replace(/\D/g,"").replace(/(\d{5})(\d{4})?\d*/,"$1");
		}
		else {
			showError(field, errorInvalidZip)
		}
	}
}

function validateSSN(field) {
	if (!field) { field = this; }
	if (field.value != "") {
		var thisMatch = field.value.replace(/\D/g, "").match(/(\d{3})(\d{2})(\d{4})/)
		if (thisMatch) {
			field.value = field.value.replace(/\D/g,"").replace(/(\d{3})(\d{2})(\d{4})\d*/,"$1-$2-$3");
		}
		else {
			showError(field, errorInvalidSSN)
		}
	}
}

function validatePercent(field) {
	if (!field) { field = this; }
    if (field.value != "") {
		var thisMatch = field.value.replace(/[^\d.]/g, "").match(/\d*.?\d*/)
		if (thisMatch != "") {
			field.value = field.value.replace(/[^\d.]/g,"");
		}
		else {
			showError(field, errorInvalidPercent)
		}
	}
}

function setTextareaMaxlengthEventHandlers() {
	var textareas = document.getElementsByTagName("textarea");
	for (i = 0; i < textareas.length; i++) {
		textareas[i].onkeypress = checkMaxlength;
		textareas[i].onblur = checkMaxlength;
	}
}

function checkMaxlength(event) {
	var maxLength = 2000 // default maxlength value
	if (document.all) { // Internet Explorer
		event = window.event;
	//	if (isFinite(this.maxlength) && this.maxlength > 0) { maxLength = this.maxlength }
	}
	// else { // Mozilla (does not work in Opera 7.5)
	//	if (isFinite(this.getAttribute("maxlength")) && this.getAttribute("maxlength") > 0) { maxLength = this.getAttribute("maxlength") }
	//}
	if (this.className != "") {
		var thisMatch = this.className.match(/maxlength(\d+)/)
		if (thisMatch) {
			maxLength = this.className.replace(/.*maxlength(\d+).*/,"$1");
		}
	}
	var currentLength = this.value.length;
	if (isFinite(maxLength) && isFinite(currentLength) && ((currentLength + 1) > maxLength)) {
		switch (event.type) {
			case "keypress" :
				var key = event.keyCode;
				if (!event.ctrlKey && key != 8 && key != 9 && key != 46) { // allow ctrl, backspace (8), tab (9), & delete (46)
					if (document.all) { // Internet Explorer
						event.returnValue = false;
					}
					else {
						event.preventDefault();
					}
					// this.value = this.value.substring(0, maxLength); // this works in Netscape 6
				}
			break;
			case "blur" :
				if (currentLength > maxLength) {
					this.value = this.value.substring(0, maxLength);
					showError(this, ("needs to be less than " + maxLength + " characters"))
				}
			break;
		}
	}
}

function showError(field, errorMessage) {
	field.select();
	var label = getLabel(field)

	if (label != "") {
		alert(' "' + label + '" ' + errorMessage);
	}
	else {
		errorMessage = errorMessage.substring(0, 1).toUpperCase() + errorMessage.substring(1, errorMessage.length)
		alert(errorMessage);
	}
}

function getLabel(field) {
	var label = "";
	var labels = document.getElementsByTagName("label");
	for (i = 0; i < labels.length; i++) {
		if (getForAttribute(labels[i]) == field.id) {
			label = labels[i].innerHTML;
		}
	}
	label = label.replace(/(.*): *$/,"$1")
	return label;
}

function getForAttribute(label) {
	if (document.all) { // Internet Explorer
		if (label.attributes[79]) {
			return label.attributes[79].value;
		}
		else {
			return ""
		}
	}
	else { // other browsers (tested w/ Mozilla)
		return label.getAttribute("for");
	}
}

function initializeAdminReports()
{
	if(document.getElementById("AdminReportsDiv") == null)
	{
		return;
	}
	
	var applicationStatusEnabledRadioButtons = new Array(
		document.getElementById("m_typesOfAssistiveTechnologyRadioButton"),
		document.getElementById("m_recipientsPerAgeRadioButton"),
		document.getElementById("m_summaryReportForEachApplicationRadioButton"),
		document.getElementById("m_employmentAndIncomeSourceRadioButton"),
		document.getElementById("m_uicReportRadiobutton"),
		document.getElementById("m_applicationsToUploadToUIC"),
		document.getElementById("BorrowersWithBankruptcyRadioButton"),
		document.getElementById("TechConnectLoanApplicationResultsRadioButton"));
		
	var applicationStatusDisabledRadioButtons = new Array(
		document.getElementById("m_usersByCountyRadioButton"),
		document.getElementById("m_applicationsApprovedPerLoanAmountRangeRadioButton"),
		document.getElementById("LoansApprovedByLoanStatusRadioButton"),
		document.getElementById("LoansApprovedByLoanStatus2RadioButton"),
		document.getElementById("LoansApprovedByMetroNonMetroCountyRadioButton"),
		document.getElementById("LoansApprovedByBorrowerAnnualIncomeRadioButton"),
		document.getElementById("LoansApprovedByBorrowerAnnualIncome2RadioButton"));

	//if the user clicks the back button it pre-selects the last selected radio button
	//however, it will not fire an onclick event on the radio button. Determine
	//which radio button is clicked (if any) and disable / enable the application status list box.
	
	for(var i = 0, n = applicationStatusEnabledRadioButtons.length; i < n; i++)
	{
		if(applicationStatusEnabledRadioButtons[i] != null)
		{
			applicationStatusEnabledRadioButtons[i].onclick = function() { document.getElementById("ApplicationStatusListBox").disabled = false; };
			
			if(applicationStatusEnabledRadioButtons[i].checked == true)
			{
				applicationStatusEnabledRadioButtons[i].click();
			}
		}
	}
	
	for(var i = 0, n = applicationStatusDisabledRadioButtons.length; i < n; i++)
	{
		if(applicationStatusDisabledRadioButtons[i] != null)
		{
			applicationStatusDisabledRadioButtons[i].onclick = function() { document.getElementById("ApplicationStatusListBox").disabled = true; };

			if(applicationStatusDisabledRadioButtons[i].checked == true)
			{
				applicationStatusDisabledRadioButtons[i].click();
			}
		}
	}	
}