// Javascript file for MpgCalculator and PaymentCalculator controls.

// START - MPG Calculator
function MpgCalculator()
{
	var calc = null;
	var mpgDropdown = null;
	var advancedLink = null;
	var basicLink = null;
	var currentMode = '';
	var expansionLevel = 0;
	var currentMonthlyCost = 0;
	var currentYearlyCost = 0;
	var currentTotalCost = 0;
	var newMonthlyCost = 0;
	var newYearlyCost = 0;
	var newTotalCost = 0;
	var savingsMonthly = 0;
	var savingsYearly = 0;
	var savingsTotal = 0;
	var inputValid = true;
	var hasInventoryId = false;

	this.Init = function(id, startingMode)
	{
		calc = $(id);
		currentMode = startingMode;
		expansionLevel = 0;//compressed
		advancedLink = $get('AdvancedNavLink');
		basicLink = $get('BasicNavLink');
		advancedLink.onclick = this.ChangeView;
		basicLink.onclick = this.ChangeView;
		
		var expand = $get('expander');
		var collapse = $get('collapser');
		expand.onclick = this.Expand;
		collapse.onclick = this.Expand;
		var expand2 = $get('expander2');
		var collapse2 = $get('collapser2');
		expand2.onclick = this.Expand;
		collapse2.onclick = this.Expand;
		
		var compare = $get('comparebutton');
        compare.onclick = this.Compare;
        		
		//$get('divMPGCalc').onkeypress = MPGCheckKey();
        $addHandlers($get('divMPGCalc'), {keypress:this.CheckKey}, this);
        
		hasInventoryId = $get('HasInventoryIdInput').value;
		
		if (hasInventoryId == 'False')
		{
		    $get('bnewmpgreadonly').className = 'hide';
		    $get('anewavgmpgreadonly').className = 'hide';
		    $get('anewavgcityreadonly').className = 'hide';
		    $get('anewavghwyreadonly').className = 'hide';
		    $get('mpgCalcBasicMPG').className = 'mpgCalcText';
		    $get('mpgCalcAdvMPG').className = 'mpgCalcText';
		    $get('mpgCalcAdvCityMPG').className = 'mpgCalcText';
		    $get('mpgCalcAdvHwyMPG').className = 'mpgCalcText';
		}
		else
		{
            $get('bnewmpgreadonly').className = 'mpgCalcReadOnly';
		    $get('anewavgmpgreadonly').className = 'mpgCalcReadOnly';
		    $get('anewavgcityreadonly').className = 'mpgCalcReadOnly';
		    $get('anewavghwyreadonly').className = 'mpgCalcReadOnly';
		    $get('mpgCalcBasicMPG').className = 'hide';
		    $get('mpgCalcAdvMPG').className = 'hide';
		    $get('mpgCalcAdvCityMPG').className = 'hide';
		    $get('mpgCalcAdvHwyMPG').className = 'hide';
		    $get('bnewmpg').value = $get('bnewmpgreadonly').innerHTML;
		    $get('anewavgmpg').value = $get('anewavgmpgreadonly').innerHTML;
		    $get('anewavgcity').value = $get('anewavgcityreadonly').innerHTML;
		    $get('anewavghwy').value = $get('anewavghwyreadonly').innerHTML;
		}
		
		
	}
	
	this.CheckKey = function(evt)
	{
	    if (mapKeyToAction(evt))
        {
            var button = $get('comparebutton');
			button.onclick();
			setFixValidation();
			return false;
        }
	}
	
	this.Compare = function()
	{
		inputValid = true;
		if (currentMode == 'Basic')
		{//basic    ((miles * fuel$) / avgmpg)
			var bCurrentMpg =  FormatInput($get('bcurrentmpg'));
			var bNewMpg =  FormatInput($get('bnewmpg'));
			var bFuelPrice =  FormatInput($get('bfuelprice'));
			var bAvgMiles =  FormatInput($get('bavgmiles'));
			
			if (inputValid)
			{
				currentYearlyCost = ((bAvgMiles * bFuelPrice) / bCurrentMpg);
				newYearlyCost = ((bAvgMiles * bFuelPrice) / bNewMpg);
				savingsYearly = currentYearlyCost - newYearlyCost;
				savingsMonthly = savingsYearly / 12;
			}
			else
			{
				savingsYearly = 0;
				savingsMonthly = 0;
			}

			$get('monthlyamount').innerHTML = (FormatCurrency(savingsMonthly.round().abs()));
			$get('yearlyamount').innerHTML = (FormatCurrency(savingsYearly.round().abs()));	
		}
		else 
		{
			var aCurrentFuelPrice = FormatInput($get('acurrentfuelprice'));
			var aNewFuelPrice = FormatInput($get('anewfuelprice'));
			var aAvgMiles = FormatInput($get('aavgmiles'));
				
			if (expansionLevel == 0)
			{//advanced collapse((miles * fuel$) / avgmpg)	
				var aCurrentAvgMpg = FormatInput($get('acurrentavgmpg'));
				var aNewAvgMpg = FormatInput($get('anewavgmpg'));
				
				if (inputValid)
				{
					currentYearlyCost = ((aAvgMiles * aCurrentFuelPrice) / aCurrentAvgMpg);
					newYearlyCost = ((aAvgMiles * aNewFuelPrice) / aNewAvgMpg);
				}
				else
				{
					currentYearlyCost = 0;
					newYearlyCost = 0;
				}
			}
			else if (expansionLevel == 1)
			{//advanced expanded((miles * city% * fuel$) / citympg) + ((miles * hwy% * fuel$) / hwympg)
				var aCurrentAvgCity = FormatInput($get('acurrentavgcity'));
				var aCurrentAvgHwy = FormatInput($get('acurrentavghwy'));
				var aNewAvgCity = FormatInput($get('anewavgcity'));
				var aNewAvgHwy = FormatInput($get('anewavghwy'));
				var aPctCity = FormatInput($get('apctcity'));
				var aPctHwy = FormatInput($get('apcthwy'));
				
				if (inputValid)
				{
					currentYearlyCost = ((aAvgMiles * (aPctCity / 100) * aCurrentFuelPrice) / aCurrentAvgCity) + 
											((aAvgMiles * (aPctHwy / 100) * aCurrentFuelPrice) / aCurrentAvgHwy);
					newYearlyCost = ((aAvgMiles * (aPctCity / 100) * aNewFuelPrice) / aNewAvgCity) + 
										((aAvgMiles * (aPctHwy / 100) * aNewFuelPrice) / aNewAvgHwy);
				}
				else
				{
					currentYearlyCost = 0;
					newYearlyCost = 0;
				}

			}
			
			if (inputValid)
			{
				currentMonthlyCost = currentYearlyCost / 12;
				newMonthlyCost = newYearlyCost / 12;
				savingsYearly = currentYearlyCost - newYearlyCost;
				savingsMonthly = savingsYearly / 12;
			}
			else
			{
				savingsYearly = 0;
				savingsMonthly = 0;
				newMonthlyCost = 0;
				currentMonthlyCost = 0;
			}
				
			$get('monthlyamount').innerHTML = (FormatCurrency(savingsMonthly.round().abs()));
			$get('yearlyamount').innerHTML =(FormatCurrency(savingsYearly.round().abs()));
			$get('currentmonthlycost').innerHTML =(FormatCurrency(currentMonthlyCost.round()));
			$get('currentyearlycost').innerHTML =(FormatCurrency(currentYearlyCost.round()));
			$get('newmonthlycost').innerHTML =(FormatCurrency(newMonthlyCost.round()));
			$get('newyearlycost').innerHTML =(FormatCurrency(newYearlyCost.round()));
		}
		
		if (savingsYearly < 0)
		{
			$get('monthlylabel').innerHTML = "Monthly Increase:";
			$get('yearlylabel').innerHTML = "Yearly Increase:";
		}
		else
		{
			$get('monthlylabel').innerHTML = "Monthly Savings:";
			$get('yearlylabel').innerHTML = "Yearly Savings:";
		}
	}
	
	this.ChangeView = function()
	{
	    var basic = $get('UserInputBasicSection');
	    var advanced = $get('UserInputAdvancedSection');
	    
		if  (advanced.className == 'hide')
		{
		    currentMode = 'Advanced';
			advanced.className = 'show';
			basic.className = 'hide';
			advancedLink.className = 'hide';
			basicLink.className = 'show';
		}
		else
		{
			currentMode = 'Basic';
			advanced.className = 'hide';
			basic.className = 'show';
			basicLink.className = 'hide';
			advancedLink.className = 'show';
		}	
		
		$get('monthlyamount').innerHTML = '';
		$get('yearlyamount').innerHTML = '';
		
		if (typeof adjustToolsHeight=="function")
        {
            adjustToolsHeight();
        }
		
		fixIEHeight()		
			
		return false;
	}
	
	this.Expand = function()
	{
		if (expansionLevel == 0)
		{	
		    $get('mpgCalcMPGColl').className = 'hide';
			$get('mpgCalcMPGExp').className = 'show';
			$get('mpgCalcNewMPGColl').className = 'hide';
			$get('mpgCalcNewMPGExp').className = 'show';
			$get('mpgCalcPercent').className = 'show';
			expansionLevel = 1;//expanded
		}
		else
		{
		    $get('mpgCalcMPGColl').className = 'mpgCalcBlock';
			$get('mpgCalcMPGExp').className = 'hide';
			$get('mpgCalcNewMPGColl').className = 'mpgCalcBlock';
			$get('mpgCalcNewMPGExp').className = 'hide';
			$get('mpgCalcPercent').className = 'hide';
			expansionLevel = 0;//compressed
		}
		
		if (typeof adjustToolsHeight=="function")
        {
            adjustToolsHeight();
        }
		
		fixIEHeight()
		return false;
	}
	
	
	function FormatCurrency(num)
	{
		var s = num.toString();
		var reversed = ReverseString(s);
		var formattedString = '';
		
		var i = 0;
		var j = 0;
		while (i < reversed.length)
		{
			formattedString += reversed.substring(i,i+1);
			if (j==2 && i+1 < reversed.length)
				formattedString += ',';
			
			if (j == 2)
				j = 0;
			else 
				j++;
				
			i++;
		}
		formattedString += '$';
		
		return ReverseString(formattedString);
	}

	function FormatInput(e)
	{
		var input = e.value;
		input = input.gsub(',','');
		input = input.gsub('\\$','');
		input = input.gsub('%','');
		
		if (isNaN(input) || input == 0 || input == '')
		{
			inputValid = false;
			e.value = 0;
			e.style.color = 'red';
			return '0'
		}
		else
		    e.style.color = 'black';
			return input;
	}	

	function ReverseString(s)
	{
		var sArray = s.toArray();
		var reversed = sArray.reverse();
		return reversed.join('');
	}
	
}
// END - MPG Calculator



// START - Finance Calculator
function pageLoad()
{
    // Add handlers to map the enter key to the Calculate button.
    $addHandler($get('divCalcCont'), 'keypress', PaymentCheckKey);
}

function Calculate(monthly, price, rate, down, trade, payoff, term)
{
   var payment = 0;
   //if(!monthly)
   //{
       if(rate == 0)
       {
         payment = (price - down - trade + payoff) / term;
       }
       else
       {
         payment = (price - down - trade + payoff) * ((rate / 100 / 12) / (1 - (1 / Math.pow((1 + rate / 100 / 12), term))));
       }
   //}
   //else
   //{
   //    if(rate == 0)
   //    {
   //      payment = ((monthly * term) - title - trade + down + payoff) / (1 + tax /100);
   //    }
   //    else
   //    {
   //      payment = (monthly / ((rate / 1200) / (1 - (1 / Math.pow((1 + rate / 1200), term)))) - title + down - trade + payoff) * (1 / (1 + tax / 100));
   //    }
   //}
   return formatCurrency(payment);
}

function formatCurrency(val)
{
    var i = parseFloat(val).toFixed(2);
    var s = new String(i);
    var delimiter = ','; // replace comma if desired
    var a = s.split('.',2)
    var d = a[1];
    var i = parseInt(a[0]);
    if (isNaN(i)) { return ''; }
    var minus = '';
    if (i < 0) { minus = '-'; }
    i = Math.abs(i);
    var n = new String(i);
    var a = [];
    while (n.length > 3) {
        var nn = n.substr(n.length-3);
        a.unshift(nn);
        n = n.substr(0,n.length-3);
    }
    if (n.length > 0) { a.unshift(n); }
    n = a.join(delimiter);
    if (d.length < 1) { s = n; }
    else { s = n + '.' + d; }
    return minus + s;
}

function CalculatePayments()
{
    //var monthly = parseFloat($get('monthly').value.replace(/[$,%]/ig, ''));
    var price = parseFloat($get('price').value.replace(/[$,%]/ig, ''));
    var rate = parseFloat($get('rate').value.replace(/[$,%]/ig, ''));
    //var tax = parseFloat($get('tax').value.replace(/[$,%]/ig, ''));
    //var title = parseFloat($get('title').value.replace(/[$,%]/ig, ''));
    var down = parseFloat($get('downpmt').value.replace(/[$,%]/ig, ''));
    var trade = parseFloat($get('trade').value.replace(/[$,%]/ig, ''));
    var payoff = parseFloat($get('payoff').value.replace(/[$,%]/ig, ''));
    var term = parseFloat($get('term').value);
    //if (isNaN(monthly))
    //{
       monthly = null;
    //}
    if (isNaN(price))
    {
       price = null;
    }
    //if (isNaN(tax))
    //{
    //   tax = 0;
    //   $get('tax').value = "0.00";
    //}
    //if (isNaN(title))
    //{
    //   title = 0;
    //   $get('title').value = "0.00";
    //}
    if (isNaN(down))
    {
       down = 0;
       $get('downpmt').value = "0.00";
    }
    if (isNaN(trade))
    {
       trade = 0;
       $get('trade').value = "0.00";
    }
    if (isNaN(payoff))
    {
       payoff =0;
       $get('payoff').value = "0.00";
    }
    if (isNaN(term))
    {
       term =60;
       $get('term').value = "60";
    }
    var val = Calculate(monthly, price, rate, down, trade, payoff, term);
    //if (monthly)
    //{
    //  $get('price').value = val;
    //}
    //else
    //{
       $get('monthly').value = val;
    //}
    
    //unlockFields();
}

function ResetPayments()
{
   var el1 = $get('monthly');
   var el2 = $get('price');
   el1.value = "";
   //el1.disabled = false;
   //el1.className = 'finCalcTextBox';
   el2.value = "";
   el2.disabled = false;
   el2.className = 'finCalcTextBox';
   $get('rate').value = "";
   //$get('tax').value = "";
   //$get('title').value = "";
   $get('downpmt').value = "";
   $get('trade').value = "";
   $get('payoff').value = "";
   $get('term').value = "";
}

function unlockFields()
{
   //on calculate, revert the disabled fields to editable fields.
   //var el1 = $get('monthly');
   var el2 = $get('price');
   //el1.disabled = false;
   //el1.className = 'finCalcTextBox';
   el2.disabled = false;
   el2.className = 'finCalcTextBox';
}

function lockBox()
{
    var el1 = $get('monthly');
    el1.disabled = true;
    el1.blur();
    var el2 = $get('calcButtonAnchor');
    el2.focus();
    el1.disabled = false;
}

function unlockBox()
{
    var el1 = $get('monthly');
    el1.disabled = false;
}

function financeChange(el, e)
{
    //clear out monthly or price if the user makes a change in the opposite input.
    //catch tab and enter press
    if(e && (e.charCode ==  13 || e.charCode == 9))
    {
        return false;
    }
    else if (window.event && (window.event.keyCode == 13 || window.event.keyCode == 9))
    { 
        return false;
    }
    else
    {
        if (el == 'monthly')
        {
            $get('price').value = "";
        }
        else
        {
            //$get('monthly').value = "";
        }
        //disableFields();
    }
}

function disableFields()
{
    //var monthly = parseFloat($get('monthly').value.replace(/[$,%]/ig, ''));
    var price = parseFloat($get('price').value.replace(/[$,%]/ig, ''));
    //setting class name is for an IE fix to show the field as disabled.
    if ((isNaN(monthly) && isNaN(price)) || (!isNaN(monthly) && !isNaN(price)))
    {
        $get('price').disabled = false;
        $get('price').className = 'finCalcTextBox';
        //$get('monthly').disabled = false;
        //$get('monthly').className = 'finCalcTextBox';
    }
    else
    {
        if (!isNaN(monthly))
        {
            $get('price').disabled = true;
            $get('price').className = 'finCalcTextBoxDis';
        }
        else
        {
            $get('price').disabled = false;
            $get('price').className = 'finCalcTextBox';
        }

        if (!isNaN(price))
        {
            //$get('monthly').disabled = true;
            //$get('monthly').className = 'finCalcTextBoxDis';
        }
        else
        {
            //$get('monthly').disabled = false;
            //$get('monthly').className = 'finCalcTextBox';
        }
    }
}

function enableFields()
{
    //var monthly = parseFloat($get('monthly').value.replace(/[$,%]/ig, ''));
    var price = parseFloat($get('price').value.replace(/[$,%]/ig, ''));
    
    if (isNaN(monthly) && isNaN(price))
    {
        $get('price').disabled = false;
        $get('price').className = 'finCalcTextBox';
        //$get('monthly').disabled = false;
        //$get('monthly').className = 'finCalcTextBox';
    }
}

function PaymentCheckKey(evt)
{
    // evt is a Sys.UI.DomEvent object
 
    if (mapKeyToAction(evt))
    {
        CalculatePayments();
        setFixValidation();
        return false;
    }
}

// END - Finance Calculator
//

