function CharCode(chr)
{
  return chr.charCodeAt(0);
}

function SelectedOptionValue(select)
{
  select = FindElement(select);
  return select.options[select.selectedIndex].value;
}

function FormatMoneyForDisplay(amount, decimalPlaces)
{
  amount = amount.toString().replace(/\s+/g, '');
  if(amount == '') return '';
  if(typeof(decimalPlaces) != 'undefined'){
    amount = Math.round((0.0 + eval(amount))*Math.pow(10, decimalPlaces)).toString();
    amount = amount.replace(/\..*/, '');
    if(decimalPlaces != 0){
      while(amount.replace('-', '').length <= decimalPlaces){
        amount = amount.replace(/(\d+)/, '0$1');
      }
      amount = amount.replace(new RegExp('(.{' + decimalPlaces + '})$'), '.$1');
    }
  }

  // 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;
}

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, ''));
}



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 KeyPressFloat(evt, elem) {
  // Firefox wchodzi tu tak¬e po naciniąciu backspace, delete, czy strza-ek,
  // ale nie pozwala -atwo tego obs-u¬y
  var keycode = evt.keyCode || evt.charCode;

  if(keycode==CharCode(','))
        {
    keycode = CharCode('.');
    try{
      evt.keyCode = keycode;
      evt.charCode = keycode;
    }catch(e){
      return false; // nie umiemy zmieni przecinka na kropką (np. Opera)
    }
        }
  if(keycode == CharCode('.')){
    // tylko jedna kropka
    return (elem.value.indexOf('.') < 0);
  }else{
    return ((keycode > 47 && keycode < 58) || keycode==46 || keycode==8);
  }
}

function Trim( tekst ) {
    return tekst.replace( /^\s+|\s+$/g, "" );
}

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;
}




function CalculateExtra()
{
  var form = document.forms['FormCalculatorExtra'];
  //form.elements['MortgageCooperative'].disabled = !IsCooperativeChecked(form);
  var PriceEntered = RepairFloatField('TPrice', true);
  if(PriceEntered == ''){
    ClearCalculatedFields(form);
    return;
  }

  //var TPrice = PriceEntered * parseFloat(SelectedOptionValue('CurrencyRate'));
  var TPrice = PriceEntered * 1

  var GovernmentLegalTax = TPrice * 0.02;
  form.elements['GovernmentLegalTax'].value = CalcFormatMoney(GovernmentLegalTax,2);

  var NotarialFee = CalculateNotarialFee(TPrice, IsCooperativeChecked(form),IsMortgageCooperativeChecked(form) );
  form.elements['NotarialFee'].value = CalcFormatMoney(NotarialFee,2);
  
  

  var NotarialFeeVat = Math.round(NotarialFee * 22)/100;
  form.elements['NotarialFeeVat'].value = CalcFormatMoney(NotarialFeeVat,2);

  var CommissionPercent = RepairFloatField('CommissionPercent');
  var Commission = Math.round(TPrice * CommissionPercent)/100;
  form.elements['Commission'].value = CalcFormatMoney(Commission,2);
  var CommissionVAT = Math.round(Commission * 22)/100;
  form.elements['CommissionVAT'].value = CalcFormatMoney(CommissionVAT,2);
  var KWFee;

  if (IsCooperativeChecked(form)) //&& !form.MortgageCooperative.checked)
  {
    KWFee = 0;
    CourtFee = 0;
    form.elements['CourtFee'].value = "nie ma";  //transl
    form.elements['KWFee'].value = CalcFormatMoney(KWFee,2);
  }
  else if (IsMortgageCooperativeChecked(form))
  {
    KWFee = 40;
    form.elements['KWFee'].value = CalcFormatMoney(KWFee,2);
    CourtFee = CalculateCourtFee(TPrice);
    form.elements['CourtFee'].value = CalcFormatMoney(CourtFee,2);

  }
  else
  {
    KWFee = 0;
    CourtFee = CalculateCourtFee(TPrice);
    form.elements['CourtFee'].value = CalcFormatMoney(CourtFee,2);
    form.elements['KWFee'].value = CalcFormatMoney(KWFee,2);
  }
  


  var CopiesFee = RepairFloatField('CopiesFee');


  //var ExtraCosts = GovernmentLegalTax + NotarialFee + NotarialFeeVat + CourtFee +
                   Commission + CommissionVAT + CopiesFee;
  var ExtraCosts = GovernmentLegalTax + NotarialFee + NotarialFeeVat + CourtFee +
                   Commission + CommissionVAT + KWFee;
  form.elements['ExtraCosts'].value = CalcFormatMoney(ExtraCosts,2);

  var TotalCosts = TPrice + ExtraCosts;
  form.elements['TotalCosts'].value = CalcFormatMoney(TotalCosts,2);
} // CalculateExtra

function IsCooperativeChecked(form)
{
  return CheckedRadioButtonValue(form.elements['PropertyType']) == 'cooperative';
}

function IsMortgageCooperativeChecked(form)
{
 return CheckedRadioButtonValue(form.elements['PropertyType']) == 'mort';
}

// Taksa notarialna
function CalculateNotarialFee(TPrice, IsCooperative, IsMortgage)
{
  if(TPrice<=0)
    fee = 0;
  else if(TPrice<=3000)
    fee = 100;
  else if(TPrice<=10000)
    fee = 100  + (TPrice-3000)*0.03;
  else if(TPrice<=30000)
    fee = 310  + (TPrice-10000)*0.02;
  else if(TPrice<=60000)
    fee = 710  + (TPrice-30000)*0.01;
  else if(TPrice<=1000000)
    fee = 1010 + (TPrice-60000)*0.005;
  else
    fee = 5710+(TPrice-1000000)*0.0025;

  if(IsCooperative) {fee = fee/2;}
  if(IsMortgage) {fee = fee/2;}

  return Math.round(fee*100)/100;
}

// Op³ata s¹dowa
function CalculateCourtFee(TPrice)
{
  var fee;
  fee = 200;
  //if (TPrice <= 10000)        fee = TPrice * 0.08;
  //else if (TPrice <= 50000)   fee = 800 + ((TPrice - 10000) * 0.07);
  //else if (TPrice <=100000)   fee = 3600 + ((TPrice - 50000) * 0.06);
  //else                        fee = 6600 + ((TPrice - 100000) * 0.05);

  //fee = fee * 0.2;

  //if (fee < 15) fee = 15;
  //if (fee > 100000) fee = 100000;
  //if (TPrice <= 0) fee =0;
  return fee;
}

function ClearCalculatedFields(form)
{
   form.elements['CourtFee'].value = '';
   form.elements['GovernmentLegalTax'].value = '';
   form.elements['NotarialFee'].value = '';
   form.elements['NotarialFeeVat'].value = '';
   form.elements['ExtraCosts'].value = '';
   form.elements['Commission'].value = '';
   form.elements['TotalCosts'].value = '';
}

function CalcFormatMoney(amount, decimalPlaces)
{
  return FormatMoneyForDisplay(amount, decimalPlaces);
}

// Walidacja wciniźtego klawisza w polu z liczb¹ float.
function CalcKeyPress(evt, elem) {
  return KeyPressFloat(evt, elem);
}

function CalcSetFocus()
{
  document.FormCalculatorExtra.TPrice.focus();
}

