function ObliczKredyt(){
  var form = document.forms['CreditCalc'];
  
  var housePrice = RepairFloatField('housePrice', true);
  var ownAmount = RepairFloatField('ownAmount', true);
  var interestRate = RepairFloatField('interestRate', true);
  var period = RepairFloatField('period', true);
  var rateType = CheckedRadioButtonValue('rateType');
  
  if(ownAmount == ''){
    ownAmount = 0.0;
  }else{
    if(ownAmount >= housePrice){
      ownAmount = 0.0;
      form.elements['ownAmount'].value = '';
      document.getElementById("errorOwnAmount").setAttribute("style", "display: block;");
    }else{
      document.getElementById("errorOwnAmount").setAttribute("style", "display: none;");
    }
  }
  
  var creditAmount = (housePrice != '') ? housePrice - ownAmount : '';
  
  form.elements['creditAmount'].value = FormatMoneyForDisplay(creditAmount, 2);
  
  if(creditAmount == '' || interestRate == '' || period == '' || interestRate <= 0.0 || interestRate > 99.0 || period < 1 || period > 99){
    form.elements['firstRate'].value = '';
    form.elements['interestTotal'].value = '';
  }else{
    var firstRate, totalInterest;
    
    if(rateType == 'constant'){
      firstRate = CalculateConstantRate(creditAmount, period*12, interestRate);
      totalInterest = CalculateConstantRateTotalInterest(creditAmount, period*12, interestRate);
    }else{
      firstRate = CalculateDecreasingRate(creditAmount, period*12, interestRate);
      totalInterest = CalculateDecreasingRateTotalInterest(creditAmount, period*12, interestRate);
    }
    
    form.elements['firstRate'].value = FormatMoneyForDisplay(firstRate, 2);
    form.elements['interestTotal'].value = FormatMoneyForDisplay(totalInterest, 2);
  }
}

// Kod (unicode) pierwszego znaku w tekście.
function CharCode(chr){
  return chr.charCodeAt(0);
}

// Walidacja wciśniętego klawisza w polu z liczbą całkowitą (long).
function KeyPressInteger(event, element){
  var keycode = event.keyCode || event.charCode;
  
  return ((keycode > 47 && keycode < 58) || keycode==46 || keycode==8 || keycode==9 || keycode==37 || keycode==39 || keycode==36 || keycode==35);
}

// Walidacja wciśniętego klawisza w polu z liczbą float.
function KeyPressFloat(event, element){
  var keycode = event.keyCode || event.charCode;
  
  if(keycode == CharCode(',')){
    keycode = CharCode('.');
    
    try{
      event.keyCode = keycode;
      event.charCode = keycode;
    }catch(e){
      return false;
    }
  }
  
  if(keycode == CharCode('.')){
    return (element.value.indexOf('.') < 0);
  }else{
    return ((keycode > 47 && keycode < 58) || keycode==46 || keycode==8 || keycode==9 || keycode==37 || keycode==39 || keycode==36 || keycode==35);
  }
}

function FormatMoneyForDisplay(amount, decimalPlaces){
  amount = amount.toString().replace(/\s+/g, '');
  
  if(amount == ''){
    return '';
  }
  
  if(typeof(decimalPlaces) != 'undefined'){
    amount = (1.0 * amount);
    amount = amount.toFixed(decimalPlaces);
  }
  
  // grupy trzycyfrowe
  if(amount.indexOf('.') < 0)
    amount = amount.replace(/(\d)(?=(\d\d\d)+$)/g, '$1 ');
  else
    amount = amount.replace(/(\d)(?=(\d\d\d)+\.)/g, '$1 ');

  return amount;  
}

// Zwraca liczbę zapisaną w polu po ewentualnych poprawkach
// (usunięcie nadmiarowych kropek, zamiana przecinka na kropkę itp.)
function RepairFloatField(field, allowEmpty){
  field = FindElement(field);
  
  if(Trim(field.value) == ''){
    if(allowEmpty){
      return '';
    }
    
    field.value = '0';
  }
  
  var repaired = field.value.replace(/,/g, '.');
  
  while(repaired.indexOf('.') != repaired.lastIndexOf('.')){
    repaired = repaired.replace('.', '');
  }
  
  repaired = repaired.replace(/[^\.0-9\s]/g, '');
  
  if(repaired != field.value){
    field.value = repaired;
  }
  
  return parseFloat(field.value.replace(/ /g, ''));
}

// Znajduje elastycznie element DOM.
// Jeśli elem jest obiektem, to go zwraca i już.
// Jeśli elem jest nazwą, to szuka wg id i name. Dla przycisku typu "radio"
// zwraca listę wszystkich o tej samej nazwie z jednego formularza.
function FindElement(elem){
  if(typeof(elem) == 'string'){
    var found = document.getElementById(elem);  // chyba IE po nazwie też znajduje 
    
    if(found == null){
      found = document.getElementsByName(elem)[0];
    }
    
    // odszukanie całej grupy przycisków o tej samej nazwie
    elem = found;
    
    //ShowObjectProperties(elem);
    if(elem.type == 'radio'){
      elem = elem.form.elements[elem.name];
    }
  }
  
  return elem;
}

// zwraca tekst z usunietymi odstepami z lewa i prawa
function Trim(tekst){
  return tekst.replace( /^\s+|\s+$/g, "" );
}

// Zwraca wartość zaznaczonego przycisku
// z zestawu przycisków typu "radio".
// buttonSet - obiekt lub id lub name
// Przykład:  alert('Wybrałeś: ' + CheckedRadioButtonValue(form.Credit))
function CheckedRadioButtonValue(buttonSet){
  buttonSet = FindElement(buttonSet);
  
  var i;
  
  for(i = 0; i < buttonSet.length; i++){
    if(buttonSet[i].checked){
      return buttonSet[i].value;
    }
  }
  
  return undefined;
}

function CalculateConstantRate(amount, monthCount, interestRate){
  interestRate = interestRate/1200.0  // na miesiąc ułamek
  
  var r = Math.pow(1.0 + interestRate, monthCount);
  
  return (amount * r * (interestRate/(r - 1.0)));
}

function CalculateConstantRateTotalInterest(amount, monthCount, interestRate){
  interestRate = interestRate/1200.0  // na miesiąc ułamek
  
  var r = Math.pow(1.0 + interestRate, monthCount);
  
  return (amount * (r*monthCount*interestRate/(r-1.0) - 1.0));
}

function CalculateDecreasingRate(amount, monthCount, interestRate){
  interestRate = interestRate/1200.0  // na miesiąc ułamek
  
  return (amount*(interestRate + 1.0/monthCount));
}

function CalculateDecreasingRateTotalInterest(amount, monthCount, interestRate){
  interestRate = interestRate/1200.0  // na miesiąc ułamek
  
  return (amount*monthCount*interestRate/2.0);
}

$().ready(function(){
  $('#rateTable').click(function(){
    var housePrice = $('#housePrice').val();
    var ownAmount = $('#ownAmount').val();
    var interestRate = $('#interestRate').val();
    var period = $('#period').val();
    var rateType = $('input[name=rateType]:checked').val();
    
    var creditAmount = $('#creditAmount').val();
    var firstRate = $('#firstRate').val();
    var interestTotal = $('#interestTotal').val();
    
    if(creditAmount != '' && period != '' && interestRate != ''){
      var dataString = 'creditAmount='+ creditAmount + '&period='+ period + '&interestRate=' + interestRate +'&rateType=' + rateType;
      
      $.ajax({
        type: "GET",
        url: "http://www.kredyty.net/javascript/CalcCredit_ajax.php",
        data: dataString,
        success: function(msg){
          $('div#rateTableResult').html(msg);
        }
      });
    }
	});
});

