/****************************************************************************

This code is Copyright 2007 Prosperity Concepts LLC.
All Rights Reserved

You may not copy, alter or distribute this code for any purpose,
commercial or otherwise without prior written permission. 

THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTY OF ANY KIND, 
EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES 
THAT THE PROGRAM IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR 
PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND 
PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD ANY PART OF THE PROGRAM 
PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT PROSPERITY CONCEPTS llc) ASSUME 
THE COST OF ANY RESULTING CORRECTIVE ACTIONS. THIS DISCLAIMER OF WARRANTY 
CONSTITUTES AN ESSENTIAL PART THIS CODE'S TERMS OF USE. NO USE OF THE 
PROGRAM CONTAINED HEREIN IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER.

*****************************************************************************/

GROCERY   = 0
GAS       = 1
FAST_FOOD = 2
DRUG      = 3
PHONE     = 4
CABLE     = 5
VIDEO     = 6
DEPT      = 7
DRY_CLEAN = 8
MOVIE     = 9
COMMUTE   = 10
BEAUTY    = 11
GYM       = 12
UTILITY   = 13
OTHER     = 14

function initForm()
{
	calcCashBack();
	document.formCalculator.txtGroceries.focus();
}

function FormatNumber(num,decimalNum,bolLeadingZero,bolParens,bolCommas)
{
    if (isNaN(parseInt(num))) return "NaN";

	var tmpNum = num;
	var iSign = num < 0 ? -1 : 1;		// Get sign of number
	
	// Adjust number so only the specified number of numbers after
	// the decimal point are shown.
	tmpNum *= Math.pow(10,decimalNum);
	tmpNum = Math.round(Math.abs(tmpNum))
	tmpNum /= Math.pow(10,decimalNum);
	tmpNum *= iSign;					// Readjust for sign
	
	// Create a string object to do our formatting on
	var tmpNumStr = new String(tmpNum);

	// See if we need to strip out the leading zero or not.
	if (!bolLeadingZero && num < 1 && num > -1 && num != 0)
		if (num > 0)
			tmpNumStr = tmpNumStr.substring(1,tmpNumStr.length);
		else
			tmpNumStr = "-" + tmpNumStr.substring(2,tmpNumStr.length);
		
	// See if we need to put in the commas
	if (bolCommas && (num >= 1000 || num <= -1000)) {
		var iStart = tmpNumStr.indexOf(".");
		if (iStart < 0)
			iStart = tmpNumStr.length;

		iStart -= 3;
		while (iStart >= 1) {
			tmpNumStr = tmpNumStr.substring(0,iStart) + "," + tmpNumStr.substring(iStart,tmpNumStr.length)
			iStart -= 3;
		}		
	}

	// See if we need to use parenthesis
	if (bolParens && num < 0)
		tmpNumStr = "(" + tmpNumStr.substring(1,tmpNumStr.length) + ")";
		
	tmpNumStr = (tmpNumStr == "" ? "0" : tmpNumStr)

	return tmpNumStr;		// Return our formatted string!
}

function validateAmount(e) {
	var keynum
	var keychar
	var numcheck
	
	if (window.event) {
		keynum = e.keyCode
	} else if (e.which) {
		keynum = e.which
	}
	
	return (keynum >= 48 && keynum <= 57) || (keynum >= 96 && keynum <= 105) || keynum == 8 || keynum == 9 || (keynum >= 35 && keynum <= 39) || keynum == 46
}


function numSortDesc(a,b) { 
	return ( b - a );
}

function calcCitiDpsCashback(year, catTotals, totalMonthlyExpenses) {
	citiUtilityTotal   = catTotals[UTILITY] + catTotals[CABLE]
	citiEnhancedTotal  = catTotals[GROCERY] + catTotals[DRUG] + catTotals[GAS] + citiUtilityTotal
	citiOtherTotal     = totalMonthlyExpenses - citiEnhancedTotal	

	enhancedMultiplier = year == 1 ? 0.05 : 0.02
	citiOtherRebate    = citiOtherTotal * 12 * 0.01
	citiEnhancedRebate = (citiEnhancedTotal * 6 * enhancedMultiplier) + (citiEnhancedTotal * 6 * 0.02)
	citiCashBack       = citiEnhancedRebate + citiOtherRebate
	citiCashBack       = citiCashBack > 300 ? 300 : citiCashBack
	return citiCashBack
}

function calcCitiCashReturnsCashback(year, totalMonthlyExpenses) {
	enhancedMultiplier = year == 1 ? 0.05 : 0.01
	citiCashBack       = (totalMonthlyExpenses * 3 * enhancedMultiplier) + (totalMonthlyExpenses * 9 * 0.01)
	return citiCashBack
}

function calcCitiDriversEdgeCashBack(year, groceryTotal, gasTotal, fastFoodTotal, drugTotal, utilityTotal, otherTotal) {
	enhancedMultiplier    = year == 1 ? 0.06 : 0.03
	driversEnhancedTotal  = gasTotal + groceryTotal + drugTotal
	driversEnhancedRebate = driversEnhancedTotal * 12 * enhancedMultiplier
	driversOtherRebate    = (fastFoodTotal + utilityTotal + otherTotal) * 12 * 0.01
	driversCashBack       = driversEnhancedRebate + driversOtherRebate
	driversCashBack       = driversCashBack > 1000 ? 1000 : driversCashBack
	return driversCashBack	
}

function calcChasePerfectCardCashback(year, catTotals, totalMonthlyExpenses) {
	gasIntroRate        = year == 1 ? 0.06 : 0.03
	gasPerDay           = catTotals[GAS] * 12 / 365
	chaseGasIntroRebate = gasPerDay * 90 * gasIntroRate
	chaseGas3PctRebate  = gasPerDay * 275 * 0.03
	chaseOtherRebate    = (totalMonthlyExpenses - catTotals[GAS]) * 12 * 0.01
	chaseCashBack       = chaseGasIntroRebate + chaseGas3PctRebate + chaseOtherRebate
	return chaseCashBack
}

function calcChaseFreedomCashback(year, catTotals, totalMonthlyExpenses) {
        introRate       = year == 1 ? 0.03 : 0.01
        bonusTotal      = catTotals[GAS] + catTotals[FAST_FOOD] + catTotals[GROCERY]
 	bonus1PctAmt    = (bonusTotal > 600 ? bonusTotal - 600 : 0)
        bonus3PctAmt    = (bonus1PctAmt > 0 ? 600 : bonusTotal)
        otherTotal      = totalMonthlyExpenses - bonus3PctAmt 
        bonusRebate     = bonus3PctAmt * 6 * introRate + bonus3PctAmt * 6 * 0.01
        otherRebate     = otherTotal * 12 * 0.01
        freedomCashBack = bonusRebate + otherRebate
	
	return freedomCashBack
}

function calcAmexBlueCashCashback(year, catTotals, totalMonthlyExpenses) {
	// Year doesn't matter with the Blue Cash card

	var totalDailyExpenses = totalMonthlyExpenses * 12 / 365

	numDaysTo6500      = 6500 / totalDailyExpenses
	numDaysTo6500      = (numDaysTo6500 > 365 ? 365 : numDaysTo6500)
	//numDaysToCap       = 50000 / totalDailyExpenses
	//numDaysToCap       = (numDaysToCap > 365 ? 365 : numDaysToCap)
	numDaysToCap       = 365 // Blue Cash no longer caps at $50K spend
	numDaysAbove6500   = numDaysToCap - numDaysTo6500
		
    gasPerDay          = catTotals[GAS] * 12 / 365
	grocPerDay         = catTotals[GROCERY] * 12 / 365
	drugPerDay         = catTotals[DRUG] * 12 / 365
	otherPerDay        = totalDailyExpenses - gasPerDay - grocPerDay - drugPerDay
	
	amexGasRebate      = (gasPerDay * numDaysTo6500 * 0.01)    + (gasPerDay * numDaysAbove6500 * 0.05)
	amexGrocRebate     = (grocPerDay * numDaysTo6500 * 0.01)   + (grocPerDay * numDaysAbove6500 * 0.05)
	amexDrugRebate     = (drugPerDay * numDaysTo6500 * 0.01)   + (drugPerDay * numDaysAbove6500 * 0.05)
	amexOtherRebate    = (otherPerDay * numDaysTo6500 * 0.005) + (otherPerDay * numDaysAbove6500 * 0.015)
	
	amexCashBack       = amexGasRebate + amexGrocRebate + amexDrugRebate + amexOtherRebate
	return amexCashBack
}

function calcDiscOpenRoadCashBack(year, catTotals, totalMonthlyExpenses) {
	// Year doesn't matter with the Open Road card
	
	var discGasEnhancedTotal = (catTotals[GAS] > 100 ? 100 : catTotals[GAS])
	var discDailyStdExpenses = (totalMonthlyExpenses - discGasEnhancedTotal) * 12 / 365

	numDaysAt025Pct    = 1500 / discDailyStdExpenses
	numDaysAt025Pct    = (numDaysAt025Pct > 365 ? 365 : numDaysAt025Pct)
	numDaysAt050Pct    = (numDaysAt025Pct == 365 ? 0 : numDaysAt025Pct)
	numDaysAt050Pct    = (numDaysAt025Pct > 182.5 ? 365 - numDaysAt025Pct : numDaysAt050Pct)
	numDaysAt1Pct      = 365 - numDaysAt050Pct - numDaysAt025Pct
	numDaysAt1Pct      = (numDaysAt1Pct < 0 ? 0 : numDaysAt1Pct)
	discStandardRebate = (discDailyStdExpenses * numDaysAt025Pct * 0.0025) + 
	                     (discDailyStdExpenses * numDaysAt050Pct * 0.005)  + 
	                     (discDailyStdExpenses * numDaysAt1Pct * 0.01);
	discGasRebate      = discGasEnhancedTotal * 12 * 0.05
	discCashBack       = discGasRebate + discStandardRebate
	
	return discCashBack
}

function calcCashBack() {

	var catTotals = []

	var currTotal        = parseInt(document.formCalculator.txtGroceries.value)
	catTotals[GROCERY]   = (isNaN(currTotal) ? 0 : currTotal)
	currTotal            = parseInt(document.formCalculator.txtGas.value)
	catTotals[GAS]       = (isNaN(currTotal) ? 0 : currTotal)
	currTotal            = parseInt(document.formCalculator.txtFastFood.value)
	catTotals[FAST_FOOD] = (isNaN(currTotal) ? 0 : currTotal)
	currTotal            = parseInt(document.formCalculator.txtDrugstores.value)
	catTotals[DRUG]      = (isNaN(currTotal) ? 0 : currTotal)	
	currTotal            = parseInt(document.formCalculator.txtTelephoneCellular.value)
	catTotals[PHONE]     = (isNaN(currTotal) ? 0 : currTotal)	
	currTotal            = parseInt(document.formCalculator.txtCableSatellite.value)
	catTotals[CABLE]     = (isNaN(currTotal) ? 0 : currTotal)
	currTotal            = parseInt(document.formCalculator.txtVideoRentals.value)
	catTotals[VIDEO]     = (isNaN(currTotal) ? 0 : currTotal)
	currTotal            = parseInt(document.formCalculator.txtDepartmentStores.value)
	catTotals[DEPT]      = (isNaN(currTotal) ? 0 : currTotal)
	currTotal            = parseInt(document.formCalculator.txtDryCleaning.value)
	catTotals[DRY_CLEAN] = (isNaN(currTotal) ? 0 : currTotal)
	currTotal            = parseInt(document.formCalculator.txtMovieTheaters.value)
	catTotals[MOVIE]     = (isNaN(currTotal) ? 0 : currTotal)
	currTotal            = parseInt(document.formCalculator.txtCommuterTransportation.value)
	catTotals[COMMUTE]   = (isNaN(currTotal) ? 0 : currTotal)
	currTotal            = parseInt(document.formCalculator.txtBeautyShops.value)
	catTotals[BEAUTY]    = (isNaN(currTotal) ? 0 : currTotal)
	currTotal            = parseInt(document.formCalculator.txtGymMemberships.value)
	catTotals[GYM]       = (isNaN(currTotal) ? 0 : currTotal)
	currTotal            = parseInt(document.formCalculator.txtUtilities.value)
	catTotals[UTILITY]   = (isNaN(currTotal) ? 0 : currTotal)
	currTotal            = parseInt(document.formCalculator.txtOther.value)
	catTotals[OTHER]     = (isNaN(currTotal) ? 0 : currTotal)
	
	var totalMonthlyExpenses  = 0.0
	
	for ( catIdx in catTotals) {
		totalMonthlyExpenses = totalMonthlyExpenses + catTotals[catIdx];
	}

	document.getElementById("txtTotalExpenses").innerHTML = "$" + FormatNumber(totalMonthlyExpenses,0,false,false,true)
	

	// Calculate Chase Freedom Cash Rebate
	
	var freedomCashBack1Yr = calcChaseFreedomCashback(1, catTotals, totalMonthlyExpenses)
	var freedomCashBack2Yr = calcChaseFreedomCashback(2, catTotals, totalMonthlyExpenses) + freedomCashBack1Yr
	
	document.getElementById("txtFreedomCashBack").innerHTML = "$" + FormatNumber(freedomCashBack1Yr, 0, false, false, true)
	document.getElementById("freedomCell").bgColor = "#FFFFFF"	
	document.getElementById("txtFreedomCashBack2Yr").innerHTML = "$" + FormatNumber(freedomCashBack2Yr, 0, false, false, true)
	document.getElementById("freedomCell2Yr").bgColor = "#FFFFFF"	
	
	highestPayingCard1Yr = 0
	highestPayingCard2Yr = 0
	maxCashBack1Yr       = freedomCashBack1Yr
	maxCashBack2Yr       = freedomCashBack2Yr

	// Calculate Chase PerfectCard Rebate
	
	var perfectCardCashback1Yr = calcChasePerfectCardCashback(1, catTotals, totalMonthlyExpenses)
	var perfectCardCashback2Yr = calcChasePerfectCardCashback(2, catTotals, totalMonthlyExpenses) + perfectCardCashback1Yr
	
	if (perfectCardCashback1Yr > maxCashBack1Yr ) {
		highestPayingCard1Yr = 1
		maxCashBack1Yr = perfectCardCashback1Yr
	}

	if ( perfectCardCashback2Yr > maxCashBack2Yr ) {
		highestPayingCard2Yr = 1
		maxCashBack2Yr = perfectCardCashback2Yr 
	}
	
	document.getElementById("txtChaseCashBack").innerHTML = "$" + FormatNumber(perfectCardCashback1Yr, 0, false, false, true)
	document.getElementById("chaseCell").bgColor = "#FFFFFF"	
	document.getElementById("txtChaseCashBack2Yr").innerHTML = "$" + FormatNumber(perfectCardCashback2Yr, 0, false, false, true)
	document.getElementById("chaseCell2Yr").bgColor = "#FFFFFF"	
	
	// Calculate Blue Cash Rebate
	
	var amexCashBack1Yr = calcAmexBlueCashCashback(1, catTotals, totalMonthlyExpenses)
	var amexCashBack2Yr = calcAmexBlueCashCashback(2, catTotals, totalMonthlyExpenses) + amexCashBack1Yr
	
	document.getElementById("txtAmexCashBack").innerHTML = "$" + FormatNumber(amexCashBack1Yr, 0, false, false, true)
	document.getElementById("amexCell").bgColor = "#FFFFFF"	
	document.getElementById("txtAmexCashBack2Yr").innerHTML = "$" + FormatNumber(amexCashBack2Yr, 0, false, false, true)
	document.getElementById("amexCell2Yr").bgColor = "#FFFFFF"	
	
	if ( amexCashBack1Yr > maxCashBack1Yr ) {
		highestPayingCard1Yr = 2
		maxCashBack1Yr = amexCashBack1Yr
	}	
	
	if ( amexCashBack2Yr > maxCashBack2Yr ) {
		highestPayingCard2Yr = 2
		maxCashBack2Yr = amexCashBack2Yr 
	}

	// Calculuate Discover Open Road Rebate
	
	var discCashBack1Yr = calcDiscOpenRoadCashBack(1, catTotals, totalMonthlyExpenses)
	var discCashBack2Yr = calcDiscOpenRoadCashBack(2, catTotals, totalMonthlyExpenses) + discCashBack1Yr
	
	if ( discCashBack1Yr > maxCashBack1Yr ) {
		highestPayingCard1Yr = 3
		maxCashBack1Yr = discCashBack1Yr
	}
	
	if ( discCashBack2Yr > maxCashBack2Yr ) {
		highestPayingCard2Yr = 3
		maxCashBack2Yr = discCashBack2Yr
	}

	document.getElementById("txtDiscoverCashBack").innerHTML = "$" + FormatNumber(discCashBack1Yr, 0, false, false, true)
	document.getElementById("discoverCell").bgColor = "#FFFFFF"
	document.getElementById("txtDiscoverCashBack2Yr").innerHTML = "$" + FormatNumber(discCashBack2Yr, 0, false, false, true)
	document.getElementById("discoverCell2Yr").bgColor = "#FFFFFF"
	
	// Calculate Citi CashReturns Rebate
	
	citiCashBack1Yr = calcCitiCashReturnsCashback(1, totalMonthlyExpenses);
	citiCashBack2Yr = calcCitiCashReturnsCashback(2, totalMonthlyExpenses) + citiCashBack1Yr;
	
	if (citiCashBack1Yr > maxCashBack1Yr ) {
		highestPayingCard1Yr = 4
		maxCashBack1Yr = citiCashBack1Yr
	}

	if ( citiCashBack2Yr > maxCashBack2Yr ) {
		highestPayingCard2Yr = 4
		maxCashBack2Yr = citiCashBack2Yr 
	}
	
	document.getElementById("txtCashReturnsCashBack").innerHTML = "$" + FormatNumber(citiCashBack1Yr, 0, false, false, true)
	document.getElementById("cashReturnsCell").bgColor = "#FFFFFF"	
	document.getElementById("txtCashReturnsCashBack2Yr").innerHTML = "$" + FormatNumber(citiCashBack2Yr, 0, false, false, true)
	document.getElementById("cashReturnsCell2Yr").bgColor = "#FFFFFF"

	// Set picture and button according to best card for these spending category amounts
	
	var cardArray = new Array( 
		{name:'Citi Freedom Cash Visa', link:'/recommends/freedomcashvisa', img:'images/chase_freedom_cash_small.jpg', cell1Yr:'freedomCell', cell2Yr:'freedomCell2Yr' },
		{name:'Chase PerfectCard', link:'/links/perfectcard', img:'images/chase_perfect_card_big.gif', cell1Yr:'chaseCell', cell2Yr:'chaseCell2Yr' },	
		{name:'Blue Cash from American Express', link:'/recommends/amexbluecash', img:'images/amex_blue_cash_big.jpg', cell1Yr:'amexCell', cell2Yr:'amexCell2Yr' },
		{name:'Discover Platinum Gas Card', link:'/links/openroad', img:'images/discover_gas_big.gif', cell1Yr:'discoverCell', cell2Yr:'discoverCell2Yr' },
		{name:'Citi Cash Returns MasterCard', link:'/links/cashreturns', img:'images/citi_cash_returns_small.jpg', cell1Yr:'cashReturnsCell', cell2Yr:'cashReturnsCell2Yr' }
	);
		
	var bestCardInfo1Yr = cardArray[highestPayingCard1Yr]
	document.getElementById("imageLinkCardCalc").href = bestCardInfo1Yr.link
	document.getElementById("linkHighestCardApply").href = bestCardInfo1Yr.link
	document.getElementById("imageCalcCard").src = bestCardInfo1Yr.img
	document.getElementById(bestCardInfo1Yr.cell1Yr).bgColor = "#FFFF00"
	document.getElementById("txtHighestCashBack").innerHTML = "$" + FormatNumber(maxCashBack1Yr, 0, false, false, true) + " in 1 year"

	var bestCardInfo2Yr = cardArray[highestPayingCard2Yr]
	document.getElementById("imageLinkCardCalc2Yr").href = bestCardInfo2Yr.link
	document.getElementById("linkHighestCardApply2Yr").href = bestCardInfo2Yr.link
	document.getElementById("imageCalcCard2Yr").src = bestCardInfo2Yr.img
	document.getElementById(bestCardInfo2Yr.cell2Yr).bgColor = "#FFFF00"
	document.getElementById("txtHighestCashBack2Yr").innerHTML = "$" + FormatNumber(maxCashBack2Yr, 0, false, false, true) + " in 2 years"
}
