(function ($) {
  $(function () {

    var fields = {
          form: $('#mortgage-calculator'),
          sum: $('#credit_amount'),
          initial: $('#initial_deposit'),
          period: $('#credit_period')
        },
        container = $('#mortgage-calculation-result td'),
        options = null;
  
    fields.form.each(function() {
      options = this.onclick instanceof Function ? this.onclick() : {};
      this.onclick = null;
      //this.removeAttribute('onclick');
    });


    function Calculator() {
      var that = this;
      
      this.getParams = function () {
        return {
          sum: fields.sum.val(),
          initial: fields.initial.val(),
          period: fields.period.val(),
        }
      }
      
      this.cleanResultContainer = function() {
        container.parent().addClass('hidden');
      }

      this.process = function() {
        container.html('<div class="processing">&nbsp;</div>');
      }

      this.template = function(data) {
        var template;

        //console.log(data);

        if (data.warning) {
          template = $('#mortgage-warning').html();
        } else {
          template = $('#mortgage-result').html();
        }
        
        container.parent().removeClass('hidden');
        container.html(
          _.template(template, data)
        );
      }

      this.getRate = function() {
        var matched = [],
            params = {},
            sum,
            initial,
            period,
            rate,
            result,
            settings = {
              precision : 0,
              thousand : " "
            };
       
        params = this.getParams();
        sum = accounting.unformat(params.sum);

        initial = parseInt(params.initial);
        period = parseInt(params.period);

        _.each(options.mortgage, function(rates) {
	  rates.rate = [].concat(rates.rate);
	  
          _.each(rates.rate, function(rate) {

            rate['min-period'].num = parseInt(rate['min-period'].num) || 0;
            rate['max-period'].num = parseInt(rate['max-period'].num) || Infinity;

            if ((rate['min-period'].num <= period) && (rate['max-period'].num >= period)) {

              rate['min-sum'] = parseInt(rate['min-sum']) || 0;
              rate['max-sum'] = parseInt(rate['max-sum']) || Infinity;

              if ( (rate['min-sum'] <= sum) && (sum <= rate['max-sum']) ) {

                rate['min-initial-instalment'] = parseInt(rate['min-initial-instalment']) || 0;
                rate['max-initial-instalment'] = parseInt(rate['max-initial-instalment']) || Infinity;


                if ( (rate['min-initial-instalment'] <= initial) && (initial <= rate['max-initial-instalment']) ) {
                  matched.push(rate);
                  //console.log(rate);
                }

              }
            }
          });
        });

        rate = matched.pop();
        result = {
          rate: 0,
          monthly_payment: 0
        };
    
        if (rate) {
          result.rate = parseFloat(rate['max-rate-value']);
          /*
          var summa = sum - ((initial * sum) / 100);
          var month = period * 12;
          var kof = (result.rate / 12) / 100;
          var k = (kof * (Math.pow((1 + kof), month))) / (Math.pow((1 + kof), month) - 1);
          
          result.monthly_payment = accounting.formatNumber((k * summa), settings);
          */

          var pp = (12 * period) - 1;
          var ps = result.rate * (1 / 1200);
          var monthly_payment = (sum * ps) / (1 - Math.pow( (1 + ps), (1 - pp) ));

          result.monthly_payment = accounting.formatNumber(monthly_payment, settings);
          
        } else {

          result.warning = '';
          if (options.min > sum) {
            result.warning += 'Минимальная сумма кредита - ' + accounting.formatNumber(options.min, settings) + 'руб.<br>';
          }

          if (options.max < sum) {
            result.warning += 'Максимальная сумма кредита - ' + accounting.formatNumber(options.max, settings) + 'руб.<br>';
          }

          if (!initial) {
            result.warning += 'Заполните поле "Первоначальный взнос"<br>';
          }

          if (!period) {
            result.warning += 'Заполните поле "Срок кредита"<br>';
          }

          if (!result.warning) {
            result.warning = ' ';
          }
        }
        return result;
      }
      
      this.calculate = function() {
        this.cleanResultContainer();
        this.template(
          this.getRate()
        );
      }

    }

    var calculator = new Calculator();
    fields.form.submit(function(e) {
      e.preventDefault();
      calculator.calculate();
    });
    
  });

})(jQuery);