// encoding: utf-8
(function(){
  var $ = function(id){ return document.getElementById( id.replace(/^#/,'') ) || {}; },
      cnst = {
          resultText: 'Húsaleigubætur yrðu %{benefits} kr. á mánuði.',

          base: 13500,
          children: [0, 14000, 22500, 28000],

          rentFactor: .15,
          rentMin:   20000,
          rentMax:   50000,

          wagesFactor: .01,
          wagesMin:    2000000,

          propFactor: .25,
          propMin:    5918453,
          
          maxBenefitPrct: .5
        };

  $('#hlb_calc').onclick = function () {
      var propField = $('#hlb_properties'),
          rentField = $('#hlb_rent'),
          childrenField = $('#hlb_children'),
          wagesField = $('#hlb_wages');

      propField.value = propField.value.replace(/\D/g, '');
      rentField.value = rentField.value.replace(/\D/g, '');
      wagesField.value = wagesField.value.replace(/\D/g, '');

      var prop = parseInt(propField.value, 10) || 0,
          rent = parseInt(rentField.value, 10) || 0,
          children = parseInt(childrenField.options[childrenField.selectedIndex].value, 10) || 0,
          wages = parseInt(wagesField.value, 10) || 0;

      if (rent)
      {
        var benefits = cnst.base
                     + cnst.children[ Math.min(children, cnst.children.length) ]
                     + (cnst.rentFactor * Math.max(0, Math.min(rent, cnst.rentMax) - cnst.rentMin) )
                     - (cnst.wagesFactor * ( Math.max(0, wages + (cnst.propFactor * Math.max(0, prop - cnst.propMin)) - cnst.wagesMin ) ) );

        benefits = Math.max(0, Math.min( benefits, rent * cnst.maxBenefitPrct));
        
        $('hlb_benefits').innerHTML = cnst.resultText.replace(/%\{benefits\}/g, (Math.round(benefits)+'').replace(/(\d)(\d\d\d)$/, '$1.$2') );
        $('hlb_benefits').style.visibility = '';
        
      }
    
      return false;
    };

})();
