// Set up our properties
var defaultValues = {}; // Object - properties are the defaults
var benchmarks = []; // Array of benchmark objects
var activeBenchmark; // Which selection we chose on the start screen
var activeScreenID = 'step_1'; // Which screen is currently active

var currencySymbol; // Currency Symbol to use
var exchangeRate; // Exchange Rate (multiplier) to use for pricing calc
var availableCurrencySymbols = ["€", "£", "R$", "$"]; // Available symbols
var availableCurrencySymbolsPattern = /€|£|(R?\$)/; // Available symbols pattern (for replacing them in strings)
var pricingTotal; // Final GS NX price to use for calculations (w/ exchange rate/currency, rep-submitted price)

// Initialize our calculation total vars
var paperCostTotalNumber,
	copierCostTotalNumber,
	copierGSCostTotalNumber,
	phoneBillNum,
	phoneBillTotalNumber,
	domesticCourierCostTotalNumber,
	intlCourierCostTotalNumber,
	deliveryGSCostTotalNumber,
	domesticMailCostTotalNumber,
	intlMailCostTotalNumber,
	mailGSCostTotalNumber,
	docPersonnelCostTotal,
	docPersonnelCostTotalWithGS,
	processPersonnelCostTotal = 0, // default to 0 because it may not be shown
	processPersonnelCostTotalWithGS = 0, // default to 0 because it may not be shown
	leasedRentalCostTotalNumber;

$(function() {
	
	/**
	 * Initialize
	 */
	$('body').addClass('home');
	
	/**
	 * Exchange Rate selection
	 */
	$('#exchangeRates').change(function() {
		// Show the loader
		$('#loader').show();
		
		// Get the currency and rate
		var currency = $('#exchangeRates option:selected').html();
		exchangeRate = $(this).val();
		
		log('Selected Currency: ' + currency);
		log('Selected Exchange Rate (multiplier): ' + exchangeRate);
		
		// Set the currency Symbol
		switch (currency)
		{
			case 'Euro':
				currencySymbol = availableCurrencySymbols[0];
				break;
			case 'British Pound':
				currencySymbol = availableCurrencySymbols[1];
				break;
			case 'Brazilian Real':
				currencySymbol = availableCurrencySymbols[2];
				break;
			default:
				currencySymbol = availableCurrencySymbols[3];
				break;
		}
		log('Currency Symbol: ' + currencySymbol);
		
		// Initialize the benchmarks and defaults
		if (exchangeRate !== '')
		{
			$.getJSON('/calculations/initialize/' + currency, function(data) {
				log('Initialize AJAX data returned:');
				log(data);
				
				// Set the defaultValues
				defaultValues = data.defaults.DefaultValue;
				populateDefaultValues();
				log('Default Values: ');
				log(defaultValues);
				
				// Set and populate the benchmark values
				$("#benchmarks option").remove(); // reset
				$('#benchmarks select').append('<option value="">-- Select a Configuration -- </option>');
				for (var i=0; i < data.benchmarks.length; i++)
				{
					$('#benchmarks select').append('<option value="' + data.benchmarks[i].Benchmark.name + '">' + data.benchmarks[i].Benchmark.name + '</option>');
					
					var benchmark = {};
					benchmark.name = data.benchmarks[i].Benchmark.name;
					benchmark.price = data.benchmarks[i].Benchmark.price;
					benchmark.cms_scan_plugin_price = data.benchmarks[i].Benchmark.cms_scan_plugin_price;
					
					benchmarks.push(benchmark);
				}
				log('Benchmarks: ');
				log(benchmarks);
				
				// Show the next dropdown
				$('#benchmarks').slideDown(animSpeed, function() {
					$('#loader').hide();
				});
			});
		}
		else
		{
			$('#loader').hide();
			$('#benchmarks').slideUp(animSpeed);
			
			$('#ecm').fadeOut(animSpeed, function() {
				$('#ecmCheck').prop('checked', false); // Using .prop() rather than .attr() which requires initial value in HTML
			});
			
			$('#getStarted').addClass('disabled');
		}
	});
	
	// Changing benchmark selection
	$('#benchmarks select').change(function() {
		if ($(this).val() !== '')
		{
			// Check value to see if we should show ECM option (not available for Serverless)
			if (!$(this).val().match(/Serverless/))
				$('#ecm').fadeIn(animSpeed);
			else
			{
				$('#ecm').fadeOut(animSpeed, function() {
					$('#ecmCheck').prop('checked', false); // Using .prop() rather than .attr() which requires initial value in HTML
				});
				$('#getStarted').addClass('disabled');
			}
			
			$('#getStarted').removeClass('disabled');
		}
		else
		{
			$('#ecm').fadeOut(animSpeed, function() {
				$('#ecmCheck').prop('checked', false); // Using .prop() rather than .attr() which requires initial value in HTML
			});
			$('#getStarted').addClass('disabled');
		}
	});
	
	/**
	 * Formatted inputs
	 */
	// Clicking Enter..
	$('.formatted').keypress(function(e)
	{
		var code = (e.keyCode ? e.keyCode : e.which);
		if (code == 13)
		{
			// Trigger focusout functionality
			$(this).focusout();
			e.preventDefault();
		}
	});
	
	// Gaining focus
	$('.formatted').click(function() {
		// Unformat
		var unformatted = format($(this).val(), { unformat: true });
		$(this).val(unformatted);
		
		$(this).select();
	});
	
	// Losing focus
	$('.formatted').focusout(function() {
		var num;
		var append = '';
		
		// Percentages
		if ($(this).hasClass('per'))
			num = format($(this).val()) + '%';
		
		// Currencies
		else if ($(this).hasClass('cur'))
			num = format($(this).val(), {places: 2, currencySymbol: currencySymbol});
		
		// Default (just commas)
		else
			num = format($(this).val());
		
		$(this).val(num);
		
		calculate();
	});
	
	/**
	 * Get Started
	 */
	$('#getStarted').click(function() {
		if (!$(this).hasClass('disabled'))
		{
			// Hide the start screen
			$('#start').hide();
			
			// Populate the chosen benchmark
			activeBenchmark = getBenchmark($("#benchmarks select").val());
			
			var benchmarkSelText = activeBenchmark.name;
			var configSelText = activeBenchmark.name;
			$('.benchmarkSelection').html(benchmarkSelText + ":");
			
			if ($('#ecmCheck').is(':checked'))
			{
				benchmarkSelText += '<br /><span>Including EFI Plug-ins for GlobalScan NX*<br />(to scan directly into document/content management systems)</span>';
				configSelText += '<br />Including EFI Plug-ins for GlobalScan NX (to scan directly into document/content management systems)';
			}
			
			$('.benchmarkSelection').html(benchmarkSelText + ":");
			log('Active Benchmark Price: $' + activeBenchmark.price);
			
			// Add to right column
			$('#steps .screen').append('<div class="config"><h3>Selected Configuration:</h3><p>' + configSelText + '</p></div>');
			
			// Is the ECM option checked?  Remove Step 6 if not
			if (!$('#ecmCheck').is(':checked'))
				$('#step_6').remove();
				
			// Initialize counter
			$('#counterTotal').html($('#steps .screen').length);
			
			$('#header').fadeIn(animSpeed, function() {
				// Setup the steps to animate
				$('#steps')
				.cycle({ 
					fx: 'scrollHorz',
					speed:  animSpeed, 
					timeout: 0,
					next: '#nextButton:not(.nextDisabled)',
					prev: '#prevButton',
					nowrap: 1,
					height: getScreenHeight(),
					before: onCycleBefore,
					after: onCycleAfter
				})
				.slideDown(500, function() {
					$("#progress").fadeIn(animSpeed);
				});
			});
		}
	});
	
	// Callback for Cycle before event
	function onCycleBefore(currSlideElement, nextSlideElement, options) {
		// Remove the home class
		$('body').removeClass('home');
		
		// Active Screen
		activeScreenID = $(nextSlideElement).attr('id');
		var activeScreenHeight = $('#'+activeScreenID).actual('height');
		
		// Move the nav stuff below the active screen
		var add = 54;
		
		// If we're mobile, we need to fully clear the steps
		if ($('.mobile').length > 0)
			add = 72;
		
		$('#progress').animate({
			top: (activeScreenHeight + add)
		}, animSpeed);
		
		var index = options.nextSlide;
		if (index < (options.slideCount - 1))
			$('#calculateROI').slideUp(animSpeed);
		
		// Update calculations
		calculate();
	}
	
	// Callback for Cycle after event
	function onCycleAfter(currSlideElement, nextSlideElement, options) {
		var index = options.currSlide;
	    $('#prevButton')[index == 0 ? 'addClass' : 'removeClass']('prevDisabled');
	    $('#nextButton')[index == options.slideCount - 1 ? 'addClass' : 'removeClass']('nextDisabled');
		
		// Show override?
		if (index == options.slideCount - 1)
			$("#override").fadeIn(animSpeed);
		else
		{
			$('#overridePanel').slideUp(animSpeed);
			$("#override").fadeOut(animSpeed);
		}
		
		// Calculate ROI button
		var index = options.currSlide;
		if (index == (options.slideCount - 1))
			$('#calculateROI').slideDown(animSpeed);
		
		// Set the counter
		$('#counterHere').html(index + 1);
		
		// If mobile, scroll to top
		if ($('.mobile').length > 0)
			$('body').scrollTo(0, 300);
	}
	
	/**
	 * Function to calculate the tallest screen and returns the size (sets the Cycle to that height)
	 */
	function getScreenHeight()
	{
		var height = 0;
		
		if ($(document).width() > 768)
		{
			if (!$('#ecmCheck').is(':checked'))
				height = 460;
			else
				height = 574; // Step 6 is a biggie
		}
		else
		{
			$('.screen').each(function() {
			
				var curHeight = $(this).actual('height');
			
				if ($(document).width() < 480)
					curHeight = (curHeight + 18); // not sure why we have to...
			
				if (curHeight > height)
					height = curHeight;
			});
		}
		
		log('Height: ' + height);
		return height;
	}
	
	/**
	 * Assumptions
	 */
	$('.assumptionUpdate').click(function() {
		// Toggle and editing class so we know if we are editing or submitting
		$(this).toggleClass('editing');
		
		// Get our parent ID
		var parentID = $(this).parent().attr('id');
		
		// Editing?
		if ($(this).hasClass('editing'))
		{
			// Swap out values for inputs
			var field = 0;
			$('#'+parentID+' .assumptionValue').each(function() {
				
				var value = format($(this).html(), {unformat: true});
				
				// If percentage, make more user friendly
				if ($(this).hasClass('pct'))
					value *= 100;
				
				$(this).html('<input type="text" name="field_'+field+'" value="'+value+'" />');
				
				field++;
			});
			
			// Update label
			$(this).html($(this).html().replace(/Update/, 'Use'));
		}
		// Submitting
		else
		{
			$('#'+parentID+' .assumptionValue').each(function() {
				var value = $(this).children('input').val();
				
				// Currency field?
				if ($(this).hasClass('cur'))
					value = format(value, {places: 2, currencySymbol: currencySymbol});
				
				// Percent?
				else if ($(this).hasClass('pct'))
					value = format((value / 100), {percentage: true});
				
				$(this).html(value);
			});
			
			// Update label
			$(this).html($(this).html().replace(/Use/, 'Update'));
			
			calculate();
		}
	});
	
	/**
	 * Final Calcuation
	 */
	$('#calculateROI').click(function() {
		$(this).slideUp(animSpeed, function() {
			$('#progress').fadeOut(animSpeed, function() {
				$('#steps').fadeOut(animSpeed, function() {
					calculate('final');
					
					// If mobile, scroll to top
					if ($('.mobile').length > 0)
						$('body').scrollTo(0, 300);
				});
			});
		});
	});
	
	/**
	 * Pricing override
	 */
	$('#override').click(function() {
		$('#overridePanel').slideToggle(animSpeed);
	});
	
	$('#overridePanel #saveOverride').click(function() {
		// Just hide the panel
		$('#override').click();
	});
	
	$('#overridePanel #cancelOverride').click(function() {
		// Clear the field value, then close panel
		$("#costOverride").val('');
		$('#override').click();
	});
});

/**
 * Formats and populates the defaults into the calculator screens
 */
function populateDefaultValues()
{
	for (var prop in defaultValues)
	{
		var formatting = {};
		var append = '';
		
		// Look for keywords to know formatting
		var curPattern = /cost/;
		var perPattern = /percent/;
		
		if (prop.match(curPattern))
			formatting = {places: 2, currencySymbol: currencySymbol};
		
		else if (prop.match(perPattern))
			append = '%';
		
		// If the element exists, populate it
		var value = format(defaultValues[prop], formatting);
		value += append;
		
		if ($('#'+prop).length > 0)
		{
			if ($('#'+prop).is('input'))
				$('#'+prop).attr('value', value);
			else
				$('#'+prop).html(value);
		}
	}
}

/**
 * Helper to get the benchmark data from the array based on name
 * @param String name
 * @return Object
 */
function getBenchmark(name)
{
	for (var i=0; i < benchmarks.length; i++)
	{
		var obj = benchmarks[i];
		if (obj.name == name)
		{
			log('getBenchmark(): Found ' + obj.name);
			return obj;
		}
	}
	
	log('getBenchmark(): Nothing found for ' + name);
	return {};
}

/**
 * Calculates everything on the active screen
 */
function calculate(step)
{
	if (step == undefined)
		step = activeScreenID;
	
	log('Calculating screen...' + step);
	
	switch (step)
	{
		case 'step_1':
			try {
				// Paper Cost
				var copyNum = format($('#copies_num_copies').val(), {unformat: true});
				paperCostTotalNumber = (((copyNum / 500) * $("#copies_cost_per_ream").html().replace(availableCurrencySymbolsPattern, '')));
				$('#paperCostTotal').html(format(paperCostTotalNumber, {currencySymbol: currencySymbol}));

				// Copier Cost
				copierCostTotalNumber = ((copyNum * $('#copies_per_copy_cost').html().replace(availableCurrencySymbolsPattern, '')));
				$('#copierCostTotal').html(format(copierCostTotalNumber, {currencySymbol: currencySymbol}));

				// Copier Cost using GlobalScan
				var copiesEmailPercentage = ($('#copies_percent_email').html().replace(/%/, '') * 0.01);
				copierGSCostTotalNumber = ((paperCostTotalNumber + copierCostTotalNumber) * (1 - copiesEmailPercentage));
				$('#copierCostTotalWithGS').html(format(copierGSCostTotalNumber, {currencySymbol: currencySymbol}));

				// Monthly Copier Savings
				var savingsTotalNumber = ((paperCostTotalNumber + copierCostTotalNumber) - copierGSCostTotalNumber);
				$('#step_1_savings').html(format(savingsTotalNumber, {currencySymbol: currencySymbol}) + " Savings!");

				return true;
			}
			catch(e)
			{
				log("Error: " + e);
				return false;
			}
			break;
			
		case 'step_2':
			try {
				// Monthly Phone Bill Costs & Savings
				if ($('#phone_monthly_cost').val() == "") phoneBillNum = 0.00;
				else phoneBillNum = format($('#phone_monthly_cost').val(), { unformat: true });

				// Phone
				$('#phoneCostTotal').html(format(phoneBillNum, { currencySymbol: currencySymbol }));
				
				// Fax
				var faxNum = (phoneBillNum * format($('#phone_percent_fax').html(), { unformat: true }));
				
				// with GS
				phoneBillTotalNumber = (phoneBillNum - faxNum);
				$('#phoneTotalWithGS').html(format(phoneBillTotalNumber, { currencySymbol: currencySymbol }));
				
				// Monthly Phone Savings
				var savingsTotalNumber = (phoneBillNum - phoneBillTotalNumber);
				$('#step_2_savings').html(format(savingsTotalNumber, { currencySymbol: currencySymbol }) + " Savings!");
				
				return true;
			}
			catch(e)
			{
				log("Error: " + e);
				return false;
			}
			break;
			
		case 'step_3':
			try {
				// Domestic Cost
				var domMailNum = format($('#courier_num_domestic').val(), { unformat: true});
				domesticCourierCostTotalNumber = (domMailNum * format($('#courier_domestic_cost').html(), { unformat: true }));
				$('#domesticCourierCostTotal').html(format(domesticCourierCostTotalNumber, { currencySymbol: currencySymbol }));
				
				// Int'l Cost
				var intlMailNum = format($('#courier_num_intl').val(), { unformat: true });
				intlCourierCostTotalNumber = (intlMailNum * format($('#courier_intl_cost').html(), { unformat: true }));
				$('#intlCourierCostTotal').html(format(intlCourierCostTotalNumber, { currencySymbol: currencySymbol }));
				
				// Delivery Cost using GlobalScan
				var deliveryEmailPercentage = format($('#courier_percent_email').html(), { unformat: true });
				deliveryGSCostTotalNumber = ((domesticCourierCostTotalNumber + intlCourierCostTotalNumber) * (1 - deliveryEmailPercentage));
				$('#courierCostTotalwithGS').html(format(deliveryGSCostTotalNumber, { currencySymbol: currencySymbol }));
				
				// Monthly Copier Savings
				var savingsTotalNumber = ((domesticCourierCostTotalNumber + intlCourierCostTotalNumber) * deliveryEmailPercentage);
				$('#step_3_savings').html(format(savingsTotalNumber, { currencySymbol: currencySymbol }) + " Savings!");
				
				return true;
			}
			catch(e)
			{
				log("Error: " + e);
				return false;
			}
			break;
			
		case 'step_4':
			try {
				// Domestic Cost
				var domMailNum = format($('#mail_num_domestic').val(), { unformat: true});
				domesticMailCostTotalNumber = (domMailNum * format($('#mail_domestic_cost').html(), { unformat: true }));
				$('#domesticMailCostTotal').html(format(domesticMailCostTotalNumber, { currencySymbol: currencySymbol }));

				// Int'l Cost
				var intlMailNum = format($('#mail_num_intl').val(), { unformat: true });
				intlMailCostTotalNumber = (intlMailNum * format($('#mail_intl_cost').html(), { unformat: true }));
				$('#intlMailCostTotal').html(format(intlMailCostTotalNumber, { currencySymbol: currencySymbol }));

				// Delivery Cost using GlobalScan
				var mailEmailPercentage = format($('#mail_percent_email').html(), { unformat: true });
				mailGSCostTotalNumber = ((domesticMailCostTotalNumber + intlMailCostTotalNumber) * (1 - mailEmailPercentage));
				$('#mailCostTotalwithGS').html(format(mailGSCostTotalNumber, { currencySymbol: currencySymbol }));

				// Monthly Copier Savings
				var savingsTotalNumber = ((domesticMailCostTotalNumber + intlMailCostTotalNumber) * mailEmailPercentage);
				$('#step_4_savings').html(format(savingsTotalNumber, { currencySymbol: currencySymbol }) + " Savings!");
				
				return true;
			}
			catch(e)
			{
				log("Error: " + e);
				return false;
			}
			break;
		
		case 'step_5':
			try {
				var numJobs = format($('#doc_copy_distribute_jobs').val(), { unformat: true });
				var pctElectronic = format($('#doc_percent_electronic').html(), { unformat: true });
				
				// cost per manual copy/distribute job
				var personnelCopyCostPerMin = ((format($('#doc_personnel_cost').html(), { unformat: true }) / 60) * $('#doc_avg_copy_time').html());
				
				// cost per electronic scan/distribute job
				var personnelScanCostPerMin = ((format($('#doc_personnel_cost').html(), { unformat: true }) / 60) * $('#doc_avg_scan_time').html());
				
				// # of copy/distribute jobs that could be performed electronically
				var numElectronicJobs = (numJobs * pctElectronic);
				
				// # of copy/distribute jobs that are performed manually 
				var numManualJobs = (numJobs * (1 - pctElectronic));
				
				// Personnel Cost without GS
				docPersonnelCostTotal = (numJobs * personnelCopyCostPerMin);
				$('#docPersonnelCostTotal').html(format(docPersonnelCostTotal, { currencySymbol: currencySymbol }));
				
				// Personnel Cost With GS
				docPersonnelCostTotalWithGS = ((personnelCopyCostPerMin * numManualJobs) + (personnelScanCostPerMin * numElectronicJobs));
				$('#docPersonnelCostTotalWithGS').html(format(docPersonnelCostTotalWithGS, { currencySymbol: currencySymbol }));
				
				// Monthly Savings
				var savingsTotalNumber = (docPersonnelCostTotal - docPersonnelCostTotalWithGS);
				$('#step_5_savings').html(format(savingsTotalNumber, {currencySymbol: currencySymbol}) + " Savings!");
				
				return true;
			}
			catch(e)
			{
				log("Error: " + e);
				return false;
			}
			break;
		
		// (Optional Step)
		case 'step_6':
			try {
				var numJobs = format($('#process_num_jobs').val(), { unformat: true });
				var pctDirect = format($('#process_percent_direct').html(), { unformat: true });
				
				// cost per manual copy/distribute job
				var personnelCopyCostPerMin = ((format($('#process_personnel_cost').html(), { unformat: true }) / 60) * $('#process_avg_load_time').html());
				
				// cost per electronic scan/distribute job
				var personnelScanCostPerMin = ((format($('#process_personnel_cost').html(), { unformat: true }) / 60) * $('#process_avg_scan_time').html());
				
				// # of copy/distribute jobs that could be performed electronically
				var numElectronicJobs = (numJobs * pctDirect);
				
				// # of copy/distribute jobs that are performed manually 
				var numManualJobs = (numJobs * (1 - pctDirect));

				// Personnel Cost without GS
				docPersonnelCostTotal = (numJobs * personnelCopyCostPerMin);
				$('#processPersonnelCostTotal').html(format(docPersonnelCostTotal, { currencySymbol: currencySymbol }));

				// Personnel Cost With GS
				docPersonnelCostTotalWithGS = ((personnelCopyCostPerMin * numManualJobs) + (personnelScanCostPerMin * numElectronicJobs));
				$('#processPersonnelCostTotalWithGS').html(format(docPersonnelCostTotalWithGS, { currencySymbol: currencySymbol }));

				// Monthly Savings
				var savingsTotalNumber = (docPersonnelCostTotal - docPersonnelCostTotalWithGS);
				$('#step_6_savings').html(format(savingsTotalNumber, {currencySymbol: currencySymbol}) + " Savings!");
				
				return true;
			}
			catch(e)
			{
				log("Error: " + e);
				return false;
			}
			break;
			
		case 'step_7':
			try {
				// Leased and Rental Copier Cost
				var copierNum;
				var copierAmt;

				if ($('#lease_num').val() == "") copierNum = 0;
				else copierNum = format($('#lease_num').val(), { unformat: true });

				if ($('#lease_avg_cost').val() == "") copierAmt = 0.00;
				else copierAmt = format($('#lease_avg_cost').val(), { unformat: true });

				leasedRentalCostTotalNumber = (copierNum * copierAmt);
				$('#totalLeasedRentalCosts').html(format(leasedRentalCostTotalNumber, { currencySymbol: currencySymbol }));
				
				return true;
			}
			catch(e)
			{
				log("Error: " + e);
				return false;
			}
			break;
		
		case 'final':
			try {
				
				// Monthly cost without GS
				var monthlyWithoutGS = (paperCostTotalNumber + 
					copierCostTotalNumber + 
					phoneBillNum + 
					domesticCourierCostTotalNumber + 
					intlCourierCostTotalNumber + 
					domesticMailCostTotalNumber + 
					intlMailCostTotalNumber + 
					docPersonnelCostTotal +
					processPersonnelCostTotal +
					leasedRentalCostTotalNumber);
				
				$('#totalMonthlyCostWithoutGS').html(format(monthlyWithoutGS, { currencySymbol: currencySymbol }));
				log('Monthly Total without GS: ' + monthlyWithoutGS);
				
				// Monthly cost with GS
				var monthlyWithGS = (copierGSCostTotalNumber + 
					phoneBillTotalNumber + 
					deliveryGSCostTotalNumber + 
					mailGSCostTotalNumber + 
					docPersonnelCostTotalWithGS +
					processPersonnelCostTotalWithGS + 
					leasedRentalCostTotalNumber);
					
				$('#totalMonthlyCostWithGS').html(format(monthlyWithGS, { currencySymbol: currencySymbol }));
				log('Monthly Total with GS: ' + monthlyWithGS);
				
				// Monthly Savings
				var monthlySavings = (monthlyWithoutGS - monthlyWithGS);
				$('#totalMonthlySavings').html(format(monthlySavings, { currencySymbol: currencySymbol }));
				log('Monthly Savings: ' + monthlySavings);
				
				// Annual Savings
				var annualSavings = (monthlySavings * 12);
				$('#totalAnnualSavings').html(format(annualSavings, { currencySymbol: currencySymbol }));
				log('Annual Savings: ' + annualSavings);
				
				// Calculate the costs for the software/plugins/options
				// Check if the salesperson has changed the price default for GS
				if ($("#costOverride").val() !== "")
					pricingTotal = format($("#costOverride").val(), { unformat: true });
				else
				{
					// If we want to include the plugin
					if ($('#ecmCheck').is(':checked'))
					{
						log('Total price includes plugin: ' + activeBenchmark.cms_scan_plugin_price);
						pricingTotal = ((parseInt(activeBenchmark.price) + parseInt(activeBenchmark.cms_scan_plugin_price)) * exchangeRate);
					}
					else
						pricingTotal = (activeBenchmark.price * exchangeRate);
				}
				
				log("Total price for GS: " + pricingTotal);
				
				// ROI
				var roi = (pricingTotal / monthlySavings),
					unit = ' Months';
				
				// Convert to years?
				if (roi > 12)
				{
					roi = (roi / 12);
					unit = ' Years';
				}
				
				$('#roi').html(format(roi, { places: 2 }) + unit);
				log("ROI: " + roi + unit)
				
				// Get the values and send to app
				var values = getCalculatorValues();
				$.post('/calculations/process', values, function(data) {
					log("Sent to app:");
					log(values);
					log("Saved Calculation ID: " + data);
				});
				
				// Hide override
				$("#override").fadeOut(animSpeed);
				
				// Show the final screen
				$("#final").fadeIn(animSpeed);
				
				return true;
			}
			catch(e)
			{
				log("Error: " + e);
				return false;
			}
			break;
	}
}

/**
 * Gathers all calculator values and returns a value object to send to the app
 */
function getCalculatorValues()
{
	// Set up the value object for DB.  The ID of each .post element is our property name
	var values = {};
	
	// Loop through .left_col .post first (these are Calculation entries)
	$('.left_col .post').each(function() {
		// input or span?
		if ($(this).val() !== '')
			values[$(this).attr('id')] = $(this).val();
		else
			values[$(this).attr('id')] = $(this).html();
	});
	
	// Loop through .right_col .post and #final .post (these are Totals)
	$('.totals .post').each(function() {
		
		var name = '';
		
		// Is this a savings field?
		if ($(this).attr('id').match(/step_1_savings/))
		{
			name = 'total_totalCopierCostSavings';
		}
		else if ($(this).attr('id').match(/step_2_savings/))
		{
			name = 'total_totalPhoneSavings';
		}
		else if ($(this).attr('id').match(/step_3_savings/))
		{
			name = 'total_totalOvernightSavings';
		}
		else if ($(this).attr('id').match(/step_4_savings/))
		{
			name = 'total_totalPostageSavings';
		}
		else if ($(this).attr('id').match(/step_5_savings/))
		{
			name = 'total_totalDocPersonnelSavings';
		}
		else if ($(this).attr('id').match(/step_6_savings/))
		{
			name = 'total_totalProcessPersonnelSavings';
		}
		else
		{
			name = 'total_' + $(this).attr('id');
		}
		
		// Prepend total_ to name
		values[name] = $(this).html();
	});
	
	// Add the total GS costs and ROI
	values['currency'] = $('#exchangeRates option:selected').html();
	values['total_totalGSCosts'] = pricingTotal;
	values['total_totalMonthlyCostWithoutGS'] = $('#totalMonthlyCostWithoutGS').html();
	values['total_totalMonthlyCostWithGS'] = $('#totalMonthlyCostWithGS').html();
	values['total_totalMonthlySavings'] = $('#totalMonthlySavings').html();
	values['total_totalAnnualSavings'] = $('#totalAnnualSavings').html();
	values['total_roi'] = $('#roi').html();
	
	return values;
}
















