// JavaScript Document
function fixFloat(val)
{
	if(val.indexOf(".") != -1)
	{
		while(val.charAt(val.length-1) == "0")
		{
			val = val.substring(0,val.length-1);
		}
		
		if(val.charAt(val.length-1) == ".")
		{
			val = val.substring(0,val.length-1);
		}
	}
	
	if(""+parseFloat(val) != val)
	{
		return false;
	}
	else 
	{
		return ""+parseFloat(val);
	}
}

function fixInt(val)
{
	if(isNaN(val))
	{
		return false;
	}
	else
	{
		return ''+parseInt(val);
	}
}

function parseDollar(val)
{
	if(val.charAt(0) == "$")
	{
		//remove dollar sign
		val = val.substring(1, val.length);
	}
	
	var pos = val.lastIndexOf(",");		//move from the end of the number and remove commas
	while(pos != -1)
	{
		val = val.substring(0,pos)+val.substring(pos+1,val.length);
		pos = val.lastIndexOf(",",pos);
	}
	return parseFloat(val);
}

function monthlyPayment(){
	
	var principle = parseDollar(jQuery('#homePrice').attr('value')) - parseDollar(jQuery('#downPayment').attr('value'));
	var annual_interest = parseFloat(jQuery('#annualInterestRate').attr('value'));
	var monthly_interest = annual_interest / 1200.0;
	var num_months = parseInt(jQuery('#loanTermMonths').attr('value'));
	var monthly_payment = 0;
	if(monthly_interest == 0)
	{
		monthly_payment = principle/num_months;
	}
	else
	{
		var thePow = Math.pow(1 + monthly_interest, -num_months);
		var dividend = 1 - thePow;
		var beforePrinciple = (monthly_interest / (dividend));
		monthly_payment = principle * beforePrinciple;
	}
	monthly_payment = Math.round(monthly_payment*100)/100;
	jQuery('#monthlyPayment').attr('value', ''+monthly_payment);

}

/* round_decimals & pad_with_zeros is from http://www.mcfedries.com/JavaScript/Rounder.asp */
function round_decimals(original_number, decimals) {
    var result1 = original_number * Math.pow(10, decimals)
    var result2 = Math.round(result1)
    var result3 = result2 / Math.pow(10, decimals)
    return pad_with_zeros(result3, decimals)
}

function pad_with_zeros(rounded_value, decimal_places) {

    // Convert the number to a string
    var value_string = rounded_value.toString();
    
    // Locate the decimal point
    var decimal_location = value_string.indexOf(".");

    // Is there a decimal point?
    if (decimal_location == -1) {
        
        // If no, then all decimal places will be padded with 0s
        decimal_part_length = 0;
        
        // If decimal_places is greater than zero, tack on a decimal point
        value_string += decimal_places > 0 ? "." : "";
    }
    else {

        // If yes, then only the extra decimal places will be padded with 0s
        decimal_part_length = value_string.length - decimal_location - 1;
    }
    
    // Calculate the number of decimal places that need to be padded with 0s
    var pad_total = decimal_places - decimal_part_length;
    
    if (pad_total > 0) {
        
        // Pad the string with 0s
        for (var counter = 1; counter <= pad_total; counter++) 
            value_string += "0";
        }
    return value_string;
}

jQuery(document).ready(function(){
	jQuery('#homePrice').keyup(
		function(){
			var payment = parseDollar(jQuery('#downPayment').attr('value'));
			var price = parseDollar(jQuery(this).attr('value'));
			//figure out what precentage payment is of price
			var percent = (payment/price)*100;
			jQuery('#downPaymentPercent').attr('value', Math.ceil(percent) );
			monthlyPayment();
		}
	);
	jQuery('#loanTermYears').keyup(
		function()
		{
			var years = parseFloat(jQuery(this).attr('value'));
			jQuery('#loanTermMonths').attr('value', ''+Math.ceil(years * 12.0));
			monthlyPayment();
		}
	);
	jQuery('#loanTermMonths').keyup(
		function()
		{
			var months = parseInt(jQuery(this).attr('value'));
			jQuery('#loanTermYears').attr('value', ''+round_decimals(parseFloat(months)/12.0, 2));
			monthlyPayment();
		}
	);
	jQuery('#downPaymentPercent').keyup(
		function()
		{
			var perc = parseFloat(jQuery(this).attr('value'));
			var price = parseDollar(jQuery('#homePrice').attr('value'));
			jQuery('#downPayment').attr('value', Math.ceil(''+(price * (perc / 100))) );
			monthlyPayment();
			
		}
	);
	jQuery('#downPayment').keyup(
		function()
		{
			var payment = parseDollar(jQuery(this).attr('value'));
			var price = parseDollar(jQuery('#homePrice').attr('value'));
			//figure out what precentage payment is of price
			var percent = (payment/price)*100;
			jQuery('#downPaymentPercent').attr('value', Math.ceil(percent) );
			monthlyPayment();
		}
	);
	
	jQuery('#annualInterestRate').keyup(monthlyPayment);
	
	jQuery('#calcForm').submit(
		function()
		{
			monthlyPayment();
			return false;
		}
	);
});
