(function() {
  var calc, i;
  calc = {
    capacityVars: {
      min: 100 * 1000,
      max: 800 * 1000
    },
    mortgageInterestRates: {
      PLN: (function() {
        var _i, _len, _ref, _results;
        _ref = [0.5, 3.0];
        _results = [];
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          i = _ref[_i];
          _results.push(i + 4.99);
        }
        return _results;
      })(),
      EUR: (function() {
        var _i, _len, _ref, _results;
        _ref = [1.6, 5.0];
        _results = [];
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          i = _ref[_i];
          _results.push(i + 1.23);
        }
        return _results;
      })(),
      CHF: (function() {
        var _i, _len, _ref, _results;
        _ref = [3.0, 5.0];
        _results = [];
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          i = _ref[_i];
          _results.push(i + 0.05);
        }
        return _results;
      })(),
      USD: (function() {
        var _i, _len, _ref, _results;
        _ref = [3.0, 5.0];
        _results = [];
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          i = _ref[_i];
          _results.push(i + 0.58);
        }
        return _results;
      })()
    },
    capacity: function(earnings, obligations, people, currency, years, percent) {
      var amount_factor, credit_cards_limit, currency_risk, excess_green, excess_yellow, expenses_factor, expenses_green, expenses_yellow, fi_green, fi_yellow, green, o_installments, yellow;
      credit_cards_limit = 0;
      expenses_factor = earnings <= 1000 ? 0.75 : earnings <= 1500 ? 0.65 : earnings <= 2000 ? 0.6 : earnings <= 5000 ? 0.5 : earnings <= 7500 ? 0.4 : 0.3;
      currency_risk = 0.00;
      if (currency === 'CHF') {
        currency_risk = 0.40;
      }
      if (currency === 'EUR') {
        currency_risk = 0.15;
      }
      if (currency === 'USD') {
        currency_risk = 0.20;
      }
      if (currency === 'CHF' && earnings < 15000) {
        green = yellow = 0;
      } else {
        expenses_green = _.max([earnings * expenses_factor * 1.00, people * 700]);
        expenses_yellow = _.max([earnings * expenses_factor * 0.80, people * 500]);
        excess_green = _.min([earnings - expenses_green, earnings * (0.50 - currency_risk)]);
        excess_yellow = _.min([earnings - expenses_yellow, earnings * (0.70 - currency_risk)]);
        o_installments = obligations + credit_cards_limit * 0.05;
        fi_green = excess_green - o_installments;
        fi_yellow = excess_yellow - o_installments;
        amount_factor = 1 / (((1 / (_.min([years, 25]) * 12)) + (percent / 100 / 12)) * 0.9);
        green = _.max([fi_green, 0]) * amount_factor;
        yellow = _.max([fi_yellow, 0]) * amount_factor;
      }
      return {
        "green": Math.round(green),
        "yellow": Math.round(yellow)
      };
    },
    simulation: function(amount, years, installment_type, percent) {
      var adjusted_percent, asset, d_amount, ins, installments, interest, num, num_of_installments, sum;
      num_of_installments = years * 12;
      adjusted_percent = percent / 100 / 12;
      installments = (function() {
        var _results, _results2;
        if (installment_type === 'constant') {
          d_amount = amount;
          _results = [];
          for (num = 1; 1 <= num_of_installments ? num <= num_of_installments : num >= num_of_installments; 1 <= num_of_installments ? num++ : num--) {
            ins = amount * adjusted_percent * Math.pow(adjusted_percent + 1, num_of_installments) / ((Math.pow(adjusted_percent + 1, num_of_installments)) - 1);
            interest = d_amount * adjusted_percent;
            asset = ins - interest;
            d_amount -= asset;
            _results.push({
              installment: ins,
              interest: interest,
              asset: asset
            });
          }
          return _results;
        } else {
          _results2 = [];
          for (num = 1; 1 <= num_of_installments ? num <= num_of_installments : num >= num_of_installments; 1 <= num_of_installments ? num++ : num--) {
            asset = amount / num_of_installments;
            interest = amount * (num_of_installments - num + 1) * adjusted_percent / num_of_installments;
            ins = asset + interest;
            _results2.push({
              installment: ins,
              interest: interest,
              asset: asset
            });
          }
          return _results2;
        }
      })();
      sum = _.inject(installments, (function(memo, ins) {
        return memo + ins.installment;
      }), 0);
      return {
        amount: amount,
        installment_type: installment_type,
        installments: installments,
        sum: sum
      };
    },
    capacityVarsFromForm: function() {
      var currency, earnings, id, obligations, people, val, _ref;
      _ref = (function() {
        var _i, _len, _ref, _results;
        _ref = ['earnings', 'obligations', 'people'];
        _results = [];
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          id = _ref[_i];
          val = parseInt($('#' + id).val());
          _results.push((val != null) && !isNaN(val) ? val : 0);
        }
        return _results;
      })(), earnings = _ref[0], obligations = _ref[1], people = _ref[2];
      currency = $('#currency').val();
      return [earnings, obligations, people, currency];
    },
    capacityFromForm: function() {
      var amount, currency, earnings, installment_type, obligations, people, percent, result, years, _ref, _ref2;
      _ref = calc.capacityVarsFromForm(), earnings = _ref[0], obligations = _ref[1], people = _ref[2], currency = _ref[3];
      _ref2 = calc.simulationVarsFromForm(), amount = _ref2[0], years = _ref2[1], installment_type = _ref2[2], percent = _ref2[3];
      result = calc.capacity(earnings, obligations, people, currency, years, percent);
      $('#earnings_slider').slider('value', earnings);
      $('#obligations_slider').slider('value', obligations);
      return result;
    },
    simulationVarsFromForm: function() {
      var amount, id, installment_type, percent, years, _ref;
      _ref = (function() {
        var _i, _len, _ref, _results;
        _ref = ['credit_amount', 'years', 'percent'];
        _results = [];
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          id = _ref[_i];
          _results.push($('#' + id).val());
        }
        return _results;
      })(), amount = _ref[0], years = _ref[1], percent = _ref[2];
      installment_type = $('input[name=installment_type]:checked').val();
      amount = parseInt(amount);
      years = parseInt(years);
      percent = parseFloat(percent);
      percent = (percent != null) && !isNaN(percent) ? percent : 0.0;
      if (percent <= 0.0) {
        percent = 0.001;
      }
      return [amount, years, installment_type, percent];
    },
    simulationFromForm: function() {
      var amount, installment_type, percent, years, _ref;
      _ref = calc.simulationVarsFromForm(), amount = _ref[0], years = _ref[1], installment_type = _ref[2], percent = _ref[3];
      return calc.simulation(amount, years, installment_type, percent);
    },
    showCreditAmountLegend: function() {
      $('#credit_amount_row .legend_list div').qtip('hide');
      if ($('input#credit_amount').val() > $('.capacity_result .yellow').text()) {
        $('#credit_amount_row .legend_red').qtip('show');
        setTimeout("$('#credit_amount_row .legend_red').qtip('hide')", 1500);
      }
      if ($('input#credit_amount').val() < $('.capacity_result .green').text()) {
        $('#credit_amount_row .legend_green').qtip('show');
        setTimeout("$('#credit_amount_row .legend_green').qtip('hide')", 1500);
      }
      if (($('input#credit_amount').val() < $('.capacity_result .yellow').text()) && ($('input#credit_amount').val() > $('.capacity_result .green').text())) {
        $('#credit_amount_row .legend_yellow').qtip('show');
        return setTimeout("$('#credit_amount_row .legend_yellow').qtip('hide')", 1500);
      }
    },
    updateCapacity: function() {
      var $slider, cap, green_width, yellow_width;
      cap = window.calc.capacityFromForm();
      $slider = $('#credit_amount_slider');
      $('.capacity_result .green').text(Math.round(cap.green / 1000));
      $('.capacity_result .yellow').text(Math.round(cap.yellow / 1000));
      green_width = $slider.width() * (cap.green - calc.capacityVars.min) / (calc.capacityVars.max - calc.capacityVars.min);
      green_width = _.max([_.min([green_width, $slider.width()]), 0]);
      yellow_width = $slider.width() * (cap.yellow - calc.capacityVars.min) / (calc.capacityVars.max - calc.capacityVars.min) - green_width;
      yellow_width = _.max([_.min([yellow_width, $slider.width() - green_width]), 0]);
      $('.green', $slider).width(green_width);
      return $('.yellow', $slider).width(yellow_width);
    },
    updatePercentInterval: function(switch_slider) {
      var interval_max, interval_min, left_position, percent_max, percent_min, rates, right_position, slider_width;
      if (switch_slider == null) {
        switch_slider = false;
      }
      rates = calc.mortgageInterestRates[$('#currency').val()];
      if (rates) {
        interval_min = rates[0], interval_max = rates[1];
        slider_width = $('#percent_slider').width();
        percent_min = $('#percent_slider').slider('option', 'min');
        percent_max = $('#percent_slider').slider('option', 'max');
        left_position = Math.round(((interval_min - percent_min) / (percent_max - percent_min)) * slider_width);
        right_position = Math.round(((interval_max - percent_min) / (percent_max - percent_min)) * slider_width);
        $('#percent_slider .percent_interval').css('margin-left', left_position + 'px');
        $('#percent_slider .percent_interval').width(right_position - left_position + 'px');
        if (switch_slider) {
          return $('#percent_slider').slider("value", Math.round((interval_min + (interval_max - interval_min) * 0.33) * 10) / 10);
        }
      } else {
        return $('#percent_slider .percent_interval').width('0px');
      }
    },
    updateResult: function() {
      var first_installment, sim, _ref;
      sim = calc.simulationFromForm();
      first_installment = (_ref = sim.installments[0]) != null ? _ref.installment : void 0;
      if ((first_installment != null) && !isNaN(first_installment)) {
        $('.result #first_installment').text(note.roundInstallment(first_installment));
        return calc.drawChart(sim);
      }
    },
    drawChart: function(sim) {
      if (!document.createElement("canvas").getContext) {
        return;
      }
      return $.plot($("#result_chart"), [
        {
          color: '#DB7302',
          label: 'Suma',
          data: sim.amount
        }, {
          color: '#CB0101',
          label: 'Odsetki',
          data: sim.sum - sim.amount
        }
      ], {
        series: {
          pie: {
            show: true,
            radius: 1,
            label: {
              show: true,
              radius: 1 / 2,
              formatter: function(label, series) {
                return '<div class="chart_label">' + label + '<br/>' + Math.round(series.percent) + '% <br/> <span>(' + Math.round(series.percent * sim.sum / 100000) + ' tys.)</span></div>';
              },
              background: {
                opacity: 0.0
              }
            },
            stroke: {
              color: '#840101'
            }
          }
        },
        legend: {
          show: false
        }
      });
    },
    planPopup: function() {
      var sim;
      $('#loader').show();
      sim = calc.simulationFromForm();
      $('.plan_table tbody tr:not(.blank)').remove();
      $('#plan_popup').dialog({
        modal: true,
        width: 'auto'
      });
      calc.updatePopup(sim.installments, 0, 12, sim.amount);
      return $('#loader').hide();
    },
    updatePopup: function(installments, offset, size, amount) {
      var $plan_row, installment, _i, _len, _ref;
      if (offset >= installments.length) {
        return;
      }
      i = offset + 1;
      _ref = installments.slice(offset, (offset + size - 1 + 1) || 9e9);
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        installment = _ref[_i];
        $plan_row = $('.plan_table tr.blank').clone();
        $plan_row.removeClass('blank');
        $('.num', $plan_row).text("" + i + ".");
        $('.year', $plan_row).text("" + (Math.ceil(i / 12)));
        $('.asset', $plan_row).text(note.roundInstallment(installment.asset));
        $('.interest', $plan_row).text(note.roundInstallment(installment.interest));
        $('.left', $plan_row).text(note.roundInstallment(amount));
        $('.installment', $plan_row).text(note.roundInstallment(installment.installment));
        $('.plan_table tbody').append($plan_row);
        amount -= installment.asset;
        i++;
      }
      calc.updatePopupIEHackVariables = [installments, offset + size, size, amount];
      return setTimeout('calc.updatePopupIEHack()', 50);
    },
    updatePopupIEHackVariables: [],
    updatePopupIEHack: function() {
      return calc.updatePopup(calc.updatePopupIEHackVariables[0], calc.updatePopupIEHackVariables[1], calc.updatePopupIEHackVariables[2], calc.updatePopupIEHackVariables[3]);
    }
  };
  window.calc = calc;
}).call(this);

