var $estimatedLeasePrice, $monthlyDesired, $tradeIn, $annualPercentageRate, $term, currentValue = 0, ajaxSetTimer = false, showAllURL = 'http://www.paulmillermazda.com/inventory.php?search=true&min_price=0&max_price=100000';
$(document).ready(function(){
	$estimatedLeasePrice = $('#estimatedLeasePrice');
	$monthlyDesired = $('#monthlyDesired').keyup( doCalc );
	$tradeIn = $('#tradeIn').keyup( doCalc );
	$annualPercentageRate = $('#annualPercentageRate').keyup( doCalc );
	$term = $('#term').change( doCalc );
	$('#credit-calculation-form #showAll').click(function(){
			if(showAllURL)
			{
				window.location = showAllURL;
			}
		});
});

function doCalc()
{
	var newValue = calculatePurchasingPower();
	if(newValue != currentValue)
	{
		currentValue = newValue;
		$estimatedLeasePrice.text('$' + currentValue);
		if(ajaxSetTimer)
		{
			clearTimeout(ajaxSetTimer);
		}
		$('#credit-calculation-form #loading-ajax:visible, #credit-calculation-form #showAll:visible').hide();
		$('#credit-calculation-form #before-ajax:hidden').show();
		ajaxSetTimer = setTimeout(fireCarAjax, 3000);
	}
}

function calculatePurchasingPower() {
    var purchasingPower,
		monthlyPayment = parseFloat(0 + $monthlyDesired.attr('value').replace(/[^0-9\.]/g, '')),
		cashTrade      = parseFloat(0 + $tradeIn.attr('value').replace(/[^0-9\.]/g, '')),
		rate = parseFloat(0 + $annualPercentageRate.attr('value').replace(/[^0-9\.]/g, '')) / 1200,
		term = parseFloat(0 + $term.attr('value')),
		salesTax = 0,
		divisor = 1;  // divisor modifies the overall purchasingPower to account for tax, if any
	
	divisor += (salesTax / 100);
	
    if( rate == 0 ) {
        purchasingPower = ( monthlyPayment * term ) + cashTrade;
    } else {
        purchasingPower = monthlyPayment * ( ( 1 - ( 1 / Math.pow( 1 + rate, term ) ) ) / rate ) + cashTrade;
	}
	
    return format(purchasingPower / divisor);
}

function MonthlyPaymentCalculator(carValue, tradeIn, annualPercentage, term)
{
	annualPercentage = parseFloat(annualPercentage) / 1200;

	if(annualPercentage == 0)
	{
		return (parseFloat(carValue) - parseFloat(tradeIn)) / parseFloat(term);
	}
	else
	{
		return (parseFloat(carValue) - parseFloat(tradeIn)) * (annualPercentage / (1 - ( 1 / Math.pow( 1 + annualPercentage, parseFloat(term) ))));
	}
}


function format( str )
{
	var fraction;
	numerals = new String(str);
	index = numerals.indexOf(".");
	if( index != -1 )
	{
		fraction = numerals.substring( index, index + 3 );
		numerals = numerals.substring( 0, index );
	}
	ln = numerals.length;
	beg = numerals.substring( 0, ln - 3 );
	end = numerals.substring( ln - 3 );
	retVal = beg + ((ln > 3) ? "," : "") + end + ((fraction==null) ? "" : fraction);

	return retVal;
}

function fireCarAjax()
{
	var amt = parseFloat(0 + $estimatedLeasePrice.html().replace(/[^0-9\.]/g,''));

	$('#credit-calculation-form #before-ajax:visible, #credit-calculation-form #showAll:visible').hide();
	$('#credit-calculation-form #loading-ajax:hidden').show();
	$.ajax({
		url: 'ajax_inventory.php',
		data: { min_price:0, max_price: Math.ceil(amt) },
		dataType: 'json',
		success: function(json) {
			
			$('#credit-calculation-form #before-ajax:visible, #credit-calculation-form #loading-ajax:visible').hide();
			$('#credit-calculation-form #showAll:hidden').show();
			var carListHTML = '';
			if(json.error)
			{
				$('#credit-calculation-ajax').html('<div class="ajax-error">'+json.error+'</div>');
			}
			else if(json.cars.length == 0)
			{
				$('#credit-calculation-ajax').html('<div class="ajax-error">No cars were found in our inventory at the given price</div>');
			}
			else
			{
				carListHTML += '<table width="100%" cellpadding="1" cellspacing="0">';
				for(i in json.cars)
				{
						carListHTML += '<tr class="ajax-'+(i % 2 == 0 ? 'even' : 'odd')+'">';
							carListHTML += '<td rowspan="2" class="border-bottom"><a href="'+json.cars[i].url+'" class="car-image"' + (json.cars[i].image ? ' style="background-image:url(' + json.cars[i].image + ');"' : '') + '></a></td>';
							carListHTML += '<td colspan="2"><strong><a href="'+json.cars[i].url+'" class="car-name">' + json.cars[i].year + ' ' + json.cars[i].make + ' ' + json.cars[i].model + '</a></strong></td>';
						carListHTML += '</tr>';
						carListHTML += '<tr class="ajax-'+(i % 2 == 0 ? 'even' : 'odd')+'">';
							carListHTML += '<td class="border-bottom"><strong class="car-price">$'+json.cars[i].price+'</strong></td>';
							carListHTML += '<td class="border-bottom"><strong class="car-miles">'+json.cars[i].miles+' miles</strong></td>';
						carListHTML += '</tr>';
				}
				carListHTML += '</table>';
				showAllURL = 'http://www.paulmillermazda.com/inventory.php?search=true&min_price=0&max_price='+Math.ceil(amt);
				$('#credit-calculation-ajax').html(carListHTML);
			}
		},
		error: function(e1, e2, e3) {
		}
	});
}
