/// <reference path="jquery-1.4.4.min.js" />

$(document).ready(function () {
	// Set currency
	$("span.currency").html(currency);

	if (typeof intervalObj != "undefined") {
		$('#sliderDept').slider({
			max: maxDebt,
			min: minDebt,
			value: minDebt,
			step: stepValue,
			slide: function (event, ui) {
				ui.value = giveValueInRange(ui.value, minDebt, maxDebt);

				var currDeptVal = ui.value;
				$("#dept").val(format(currDeptVal));
				$('#debtSpan').html(format(currDeptVal));

				activatePerMonthSlider();
			},
			stop: function () {
				focusDeals();
			}
		});

		$('#sliderPayoff').slider({
			min: 1,
			max: monthsSliderPointsCount,
			step: 1,
			value: monthsSliderPointsCount,
			isRTL: true,
			slide: function (event, ui) {
				ShowSutablePlans(ui.value);
			}
		});

		InitializePlansPanelsForAnonymousUser();

		$('.editValue').click(function () {
			$('#editDebtAndMonthsDialog').dialog('open');
		});

		$('.popupSelect').keypress(function (args) {
			if (args.which == '13') {
				args.preventDefault();
				$('.setSliderValues').click();
			}
		});

		$('.setSliderValues').click(function () {
			activatePerMonthSlider();
			removeNonDigits($('.debtPopupValue'));
			var tempValue = removeComma($('.debtPopupValue').val());
			var debt = giveValueInRange(tempValue, minDebt, maxDebt);
			var months = $('.monthsPopupValue').val();

			$('#sliderPayoff').slider('option', 'value', months);
			$('#sliderDept').slider('option', 'value', debt);
			$('#dept').val(debt);
			$('#debtSpan').html(format(debt));

			$("#editDebtAndMonthsDialog").dialog('close');
			InitializePlansPanelsForAnonymousUser();
			ShowSutablePlans(months);
			$('.debtPopupValue').val('');
		});

		$('#editDebtAndMonthsDialog').dialog({
			width: 520,
			modal: true,
			autoOpen: false,
			resizable: false
		});
	}
	else {

		var largestMaxMonth = -1;
		$('.plan>.planMaxMonths').each(function (index, element) {
			jElement = $(element);
			if (largestMaxMonth < jElement.val()) {
				largestMaxMonth = jElement.val();
			}
		});

		InitializePlansPanelsForLoggedInUser();

		$('#monthlyPaymentsSlider').slider({
			step: stepValue,
			min: minMonthlyPayment,
			max: maxMonthlyPayment,
			value: maxMonthlyPayment,
			isRTL: true,
			slide: function (event, ui) {
				ui.value = giveValueInRange(ui.value, minMonthlyPayment, maxMonthlyPayment);
				showPlanForLoggedInUser(ui.value);
				$('#monthlyPaymentsField').val(format(ui.value));
				$('#monthlyPaymentsSpan').html(format(ui.value));
			},
			stop: function (event, ui) {
				focusDeals();
			}
		});
		//$('#monthlyPaymentsSlider').trigger('slide');

		$('#editValuePopup').dialog({
			width: 300,
			modal: true,
			autoOpen: false,
			resizable: false
		});

		$('.editValue').click(function () {
			$('#editValuePopup').dialog('open');
		});

		$('.monthlyPaymentsPopupValue').keypress(function (args) {
			if (args.which == '13') {
				args.preventDefault();
				$('.setMonthlyPayments').click();
			}
		});

		$('.setMonthlyPayments').click(function () {
			removeNonDigits($('.monthlyPaymentsPopupValue'));
			var currentMonthlyPayments = removeComma($('.monthlyPaymentsPopupValue').val());
			currentMonthlyPayments = currentMonthlyPayments != '' ? currentMonthlyPayments : 0;
			currentMonthlyPayments = parseInt(giveValueInRange(currentMonthlyPayments, minMonthlyPayment, maxMonthlyPayment));

			$("#monthlyPaymentsSlider").slider({ value: currentMonthlyPayments });
			$('#monthlyPaymentsField').val(format(currentMonthlyPayments));
			$('#monthlyPaymentsSpan').html(format(currentMonthlyPayments));

			showPlanForLoggedInUser(currentMonthlyPayments);
			$('#editValuePopup').dialog('close');
			$('.monthlyPaymentsPopupValue').val('');
		});
	}
});

function InitializePlansPanelsForLoggedInUser() {
	$('.plan, .shortPlanPanel').each(function (index, item) {
		var selectedMonthlyPayments = $(item).find('.planMaxMonthlyPayment').val(); // maxMonthlyPayment;
		var pInterestRate = $(item).find('.planInterestRate:first').val();
		var pDiscount = $(item).find('.planDiscountPercent:first').val();

		var monthsNumber = calculateNumberOfMonths(pInterestRate, totalUserDebt, pDiscount, selectedMonthlyPayments);
		var totalDebtWithInterest = calculateTotalDebtAndInterest(totalUserDebt, monthsNumber, pInterestRate);
		var youCouldSave = calculateSavings(totalDebtWithInterest, monthsNumber, selectedMonthlyPayments);
		var totalPayments = calculateTotalPayments(selectedMonthlyPayments, selectedMonthlyPayments, monthsNumber);
		var lastPayment = calculateLastPayment(selectedMonthlyPayments, selectedMonthlyPayments, monthsNumber);

		$(item).find('.discountField').html(moneyFormat(Math.round(youCouldSave)));
		$(item).find('.monthlyPaymentsField').html(moneyFormat(Math.round(selectedMonthlyPayments)));
		$(item).find('.maxMonthsField').html(Math.ceil(monthsNumber));
		$(item).find('.totalPayments').html(moneyFormat(Math.round(totalPayments)));
		$(item).find('.lastPayment').html(moneyFormat(Math.round(lastPayment)));
	});
	$('.plan:first').show();
	$('.shortPlanPanel.purplePlan').hide();
}

function showPlanForLoggedInUser(selectedMonthlyPayments) {
	$('.plan').each(function (index, item) {
		var allowedMinMonthlyPayments = $(item).find('.planMinMonthlyPayment').val();
		var allowedMaxMonthlyPayments = $(item).find('.planMaxMonthlyPayment').val();

		if (selectedMonthlyPayments <= allowedMaxMonthlyPayments && selectedMonthlyPayments >= allowedMinMonthlyPayments) {
			var pInterestRate = $(item).find('.planInterestRate:first').val();
			var pDiscount = $(item).find('.planDiscountPercent:first').val();

			var monthsNumber = calculateNumberOfMonths(pInterestRate, totalUserDebt, pDiscount, selectedMonthlyPayments);
			var totalDebtWithInterest = calculateTotalDebtAndInterest(totalUserDebt, monthsNumber, pInterestRate);
			var youCouldSave = calculateSavings(totalDebtWithInterest, monthsNumber, selectedMonthlyPayments);
			var totalPayments = calculateTotalPayments(selectedMonthlyPayments, allowedMaxMonthlyPayments, monthsNumber);
			var lastPayment = calculateLastPayment(selectedMonthlyPayments, allowedMaxMonthlyPayments, monthsNumber);

			var ceiledMonthsNumber = Math.ceil(monthsNumber);
			$(item).find('.discountField').html(moneyFormat(Math.round(youCouldSave)));
			$(item).find('.monthlyPaymentsField').html(moneyFormat(selectedMonthlyPayments));
			$(item).find('.totalDebtField').html(moneyFormat(Math.round(totalDebtWithInterest)));
			$(item).find('.maxMonthsField').html(ceiledMonthsNumber);
			$(item).find('.totalPayments').html(moneyFormat(Math.round(totalPayments)));
			$(item).find('.lastPayment').html(moneyFormat(Math.round(lastPayment)));
			$(item).show();
		}
		else {
			$(item).hide();
		}
	});
	$('.shortPlanPanel').each(function (index, item) {
		var allowedMinMonthlyPayments = $(item).find('.planMinMonthlyPayment').val();
		var allowedMaxMonthlyPayments = $(item).find('.planMaxMonthlyPayment').val();

		if (selectedMonthlyPayments <= allowedMaxMonthlyPayments && selectedMonthlyPayments >= allowedMinMonthlyPayments) {
			$(item).hide();
		}
		else {
			if (!$(item).hasClass('purplePlan')) { // only one purple plan should be visible. Its shown below
				$(item).show();
			}
		}
	});

	$('.shortPlanPanel.purplePlan').hide(); 
	if ($('.plan.purplePlan:visible').length < 1) {
		$('.shortPlanPanel.purplePlan:first').show();
	}
}

function calculateTotalPayments(selectedMonthlyPayments, allowedMaxMonthlyPayments, monthsNumber) {
	if (selectedMonthlyPayments == allowedMaxMonthlyPayments) {
		return allowedMaxMonthlyPayments;
	}
	return selectedMonthlyPayments * monthsNumber;
}

function calculateLastPayment(monthlyPayments, allowedMaxMonthlyPayments, monthsNumber) {
	if (monthlyPayments == allowedMaxMonthlyPayments) {
		return allowedMaxMonthlyPayments;
	}
	return monthlyPayments * (monthsNumber - Math.floor(monthsNumber));
}

function convertInterestRateToMonthlyRate(pInterestRate) {
	return Math.pow(1 + pInterestRate / 100, 1 / 12) - 1;
}

function calculateNumberOfMonths(pInterestRate, outstandingBalance, pOrdinaryDiscount, monthlyPayments) {
	var result;
	if (pInterestRate == 0) {
		result = (outstandingBalance * (1 - pOrdinaryDiscount / 100)) / monthlyPayments;
		return result;
	} else {
		var qInterestConvertedToMonthlyRate = convertInterestRateToMonthlyRate(pInterestRate);
		var dividend = Math.log(monthlyPayments) - Math.log(monthlyPayments - outstandingBalance * qInterestConvertedToMonthlyRate * (1 - pOrdinaryDiscount / 100));
		var divider = Math.log(1 + qInterestConvertedToMonthlyRate);
		result = dividend / divider;
		return result;
	}
}

function calculateSavings(debtAndInterest, numberOfMonths, monthlyPayments) {
	if (isNaN(numberOfMonths)) { 
		return 0;
	}

	return debtAndInterest - (numberOfMonths * monthlyPayments);
}

function calculateTotalDebtAndInterest(outstandingBalance, numberOfMonths, pInterestRate) {
	if (pInterestRate == 0) {
		return outstandingBalance;
	} else { 
		var qInterestRateConvertedToMonthlyRate = convertInterestRateToMonthlyRate(pInterestRate);
		var result = numberOfMonths * outstandingBalance * Math.pow(1 + qInterestRateConvertedToMonthlyRate, numberOfMonths) * qInterestRateConvertedToMonthlyRate / (Math.pow(1 + qInterestRateConvertedToMonthlyRate, numberOfMonths) - 1);
		return result;
	}
}

// Amount-per-month slider activation control
function activatePerMonthSlider()  {
    $("#payoff").val("1");
    $("#deals > div").hide();
    $("#sliderPayoff").slider({ value: monthsSliderPointsCount });
    $(".PaymentPlansWrapper").show();

    InitializePlansPanelsForAnonymousUser();
    ShowSutablePlans(monthsSliderPointsCount);
}

function InitializePlansPanelsForAnonymousUser() {
	for (var index = 0; index < intervalObj.intervals.length; index++) {
		var values = calculatePanelValuesForAnonymousUser(index, intervalObj.intervals[index].min);
		setShortPanelValues(values, index);
		$('#shortPaymentPlan' + index).show();
	}

	var values = calculatePanelValuesForAnonymousUser(0, intervalObj.intervals[0].min);
	setFullPanelValues(values, 0);
	$("#paymentPlan0, #paymentPlan0 .plan").show();
	$("#shortPaymentPlan0").hide();
}

function ShowSutablePlans(selectedItemIndex) {
	var realDeptVal = getRealDebtVal();

    var plansMonthesAmountMap = GetSliderValuesToMonthsNumberMap();
    var sliderValue = selectedItemIndex;
    var monthsNumber = GetSliderValuesToMonthsNumberMap()[sliderValue];
    var totalPlansNumber = intervalObj.intervals.length;

    $("#payoff").val(sliderValue);
    $("#payoffValue").html(monthsNumber);

    for (var i = 0; i < totalPlansNumber; i++) {
        var isPlanFitsInRange = monthsNumber >= intervalObj.intervals[i].min && monthsNumber <= intervalObj.intervals[i].max;
        if (isPlanFitsInRange && realDeptVal != 0) {
            var recommendedPlanSelector = "#paymentPlan" + i;
            $(recommendedPlanSelector).show();
            $(recommendedPlanSelector + " .plan").show();

            var values = calculatePanelValuesForAnonymousUser(i, monthsNumber);
            //log(values);
            setFullPanelValues(values, i);
            $('#shortPaymentPlan' + i).hide();
        }
        else {
        	$("#paymentPlan" + i + ":visible").hide();
			$('#shortPaymentPlan' + i).show();
        }
    }
	
}

function calculatePanelValuesForAnonymousUser(panelIndex, monthsNumber) {
	var recommendedPlanSelector = "#paymentPlan" + panelIndex;
	var realDeptVal = getRealDebtVal();

	var largestMaxMonths = intervalObj.intervals[intervalObj.intervals.length - 1].max;
	var pOrdinaryDiscount = $(recommendedPlanSelector + " .discountValue").val();

	var dInterestRateConvertedToMonthly = convertInterestRateToMonthlyRate(pInterestRate);
	var monthlyPayments = calculateMonthlyPaymentsForAnonymousUser(realDeptVal, dInterestRateConvertedToMonthly, monthsNumber, pOrdinaryDiscount);
	var totalDebtAndInterest = calculateDebtWithInterestForAnonymousUser(realDeptVal, dInterestRateConvertedToMonthly, monthsNumber);
	var savings = calculateSavings(totalDebtAndInterest, monthsNumber, monthlyPayments);
	
	var values = {
		savings: savings,
		monthlyPayments: monthlyPayments,
		monthsNumber: monthsNumber,
		totalDebtAndInterest: totalDebtAndInterest,
		largestMaxMonths: largestMaxMonths
	};

	return values;
}

function setFullPanelValues(values, panelIndex) {
	var recommendedPlanSelector = "#paymentPlan" + panelIndex;

	$(recommendedPlanSelector + " .discountField").html(moneyFormat(Math.round(values.savings)));
	$(recommendedPlanSelector + " .monthlyPaymentsField").html(moneyFormat(Math.round(values.monthlyPayments)));
	$(recommendedPlanSelector + " .maxMonthsField").html(values.monthsNumber);
	$(recommendedPlanSelector + " .totalDebtField").html(moneyFormat(Math.round(values.totalDebtAndInterest)));
	$(recommendedPlanSelector + " .mounthsLevel").css("width", Math.round(values.monthsNumber / values.largestMaxMonths * 100) + "%");
}

function setShortPanelValues(values, panelIndex) {
	$('#shortPaymentPlan' + panelIndex + ' .discountField').html(moneyFormat(Math.round(values.savings)));
	$('#shortPaymentPlan' + panelIndex + ' .monthlyPaymentsField').html(moneyFormat(Math.round(values.monthlyPayments)));
	$('#shortPaymentPlan' + panelIndex + ' .maxMonthsField').html(values.monthsNumber);
}

function calculateMonthlyPaymentsForAnonymousUser(outstandingBalance, dInterestRateConvertedToMonthly, months, pOrdinaryDiscount) {
	if (dInterestRateConvertedToMonthly == 0) { 
		return outstandingBalance * (1 - pOrdinaryDiscount / 100) / months;
	}

	return (outstandingBalance * Math.pow((1 + dInterestRateConvertedToMonthly), months) * dInterestRateConvertedToMonthly
				/ (Math.pow((1 + dInterestRateConvertedToMonthly), months) - 1)) * (1 - (pOrdinaryDiscount / 100));
}

function calculateDebtWithInterestForAnonymousUser(outstadingBalance, dInterestRateConvertedToMonthly, months) {
	if (dInterestRateConvertedToMonthly == 0) {
		return outstadingBalance;
	}

	return (outstadingBalance * Math.pow((1 + dInterestRateConvertedToMonthly), months) * dInterestRateConvertedToMonthly
				/ (Math.pow((1 + dInterestRateConvertedToMonthly), months) - 1)) * months;
}

function log(message) {
    if (typeof console != 'undefined') {
       console.log(message);
    }
}

// Make sure deals stay within viewport, scroll page if necessary
function focusDeals() {
	$(window).scrollTo($('.dealSliderArea'), 500);
}

// Delimiter formatting (ex. British: 1,234,567.89 / Norway: 1.234.567,89)
function format(numStr) {
    numStr += '';
    x = numStr.split(seperatorDecimals);
    x1 = x[0];
    x2 = x.length > 1 ? seperatorDecimals + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + seperatorThousands + '$2');
    }
    return x1 + x2;
}

function moneyFormat(numStr) {
    return format(numStr) + " " + currencySymbol;
}

// Remove non-digits while typing
function removeNonDigits(fld) {
    fld.val(fld.val().replace(/[^0-9]/g, ''));
}

function removeComma(value) {
    return value.replace(',', '');
}

function giveValueInRange(value, min, max) {
    if (value < min)
        value = min;
    else if (value > max)
        value = max;
    return value;
}

function getRealDebtVal() {
	return $("#dept").val().replace(seperatorThousands, '');
}
