function mark($field, isError) {
    if (isError) {
        $field.addClass("field_error");
    } else {
        $field.removeClass("field_error");
    }
}
function formatInput($field, decimalDigit) {
    mark($field, false);
    var val = $field.val();
    if (typeof decimalDigit == "undefined") {
        decimalDigit = ",";
    }
    if (new RegExp("^\\d+(\\" + decimalDigit + "(\\d+)?)?$").test(val)) {
        val = val.replace(new RegExp(decimalDigit, "g"), ".");
        return parseFloat(val);
    }
    mark($field, true);
    return NaN;
}

function PMT(IR, NP, PV) {
    return (PV * IR) / (1 - Math.pow(1 + IR, -NP));
}

function resultFormatter(value) {
    if (isNaN(value)) {
        return "#VALUE!";
    }
    return Math.round(value);
}

function getSuffix(value) {
    var roundValue = Math.round(value);
    var last1 = roundValue % 10;
    var last2 = roundValue % 100;
    if (last2 >= 11 && last2 <= 14) {
        return "лей";
    }
    if (last1 == 1) {
        return "ль";
    }
    if (last1 >= 2 && last1 <= 4) {
        return "ля";
    }
    return "лей";
}

$(function() {
    var $form = $("#form");
    var $propertyCost = $("#propertyCost", $form);
    var $propertyCostH = $("#propertyCostH");
    var $creditPeriod = $("#creditPeriod");
    var $interestRate = $("#interestRate");
    var $creditAmount = $("#creditAmount");
    var $monthlyPayment = $("#monthlyPayment");
    var $interest = $("#interest");
    var $interestH = $("#interestH");
    var $result = $("#result");
    var $resultCurrencySuffix = $("#resultCurrencySuffix");

    function calc() {
        var propertyCost = formatInput($propertyCost);
        var creditPeriod = formatInput($creditPeriod);
        var interestRate = formatInput($interestRate) / 100.0;
        var creditAmount = formatInput($creditAmount);
        var propertyCostH, monthlyPayment, interest, interestH, result;

        propertyCostH = isNaN(propertyCost) ? NaN :
                        propertyCost > 2000000.0 ?
                        260000.0 : propertyCost * 0.13;
        monthlyPayment = isNaN(creditPeriod) || isNaN(interestRate) || isNaN(creditAmount) ? NaN :
                         PMT(interestRate / 12.0, creditPeriod - 2.0, creditAmount);
        interest = isNaN(monthlyPayment) || isNaN(creditPeriod) || isNaN(creditAmount) ? NaN :
                   monthlyPayment * creditPeriod - creditAmount;
        interestH = isNaN(interest) ? NaN :
                    interest * 0.13;
        result = isNaN(propertyCostH) || isNaN(interestH) ? NaN :
                 propertyCostH + interestH;

        $propertyCostH.val(resultFormatter(propertyCostH));
        $monthlyPayment.val(resultFormatter(monthlyPayment));
        $interest.val(resultFormatter(interest));
        $interestH.val(resultFormatter(interestH));
        var formattedResult = resultFormatter(result);
        $result.text(formattedResult);
        $resultCurrencySuffix.text(getSuffix(formattedResult));
    }

    var creditPeriodValidator = function() {
        var val = formatInput($creditPeriod);
        return !isNaN(val) && val > 2;
    };
    var creditAmountValidator = function() {
            var val = formatInput($creditAmount);
            var propertyCost = formatInput($propertyCost);
            return !isNaN(val) && !isNaN(propertyCost) && val < propertyCost;
        };
    $propertyCost.keyup(function() {
        fieldValidator($propertyCost, creditAmountValidator, "Cтоимость дома, квартиры не может быть меньше суммы кредита.");
        calc();
    });
    $creditPeriod.keyup(function() {
        fieldValidator($creditPeriod, creditPeriodValidator, "Срок кредита должен быть минимум 3 месяца.");
        calc();
    });
    $interestRate.keyup(function() {
        calc();
    });
    $creditAmount.keyup(function() {
        fieldValidator($creditAmount, creditAmountValidator, "Сумма кредита должна быть меньше стоимости дома, квартиры.");
        calc();
    });
    calc();
});

function fieldValidator($field, validatorFunc, message) {
    var errorLabel = $field.next(".error_message");
    if (!validatorFunc()) {
        $field.next(".error_message").text(message);
    } else if (errorLabel.text().length > 0) {
        errorLabel.text("");
    }
}
