﻿// Format a value as currency.
function formatCurrency(num) 
{
  num = num.toString().replace(/\$|\,/g,'');
  if(isNaN(num))
     num = "0";
  sign = (num == (num = Math.abs(num)));
  num = Math.floor(num*100+0.50000000001);
  cents = num%100;
  num = Math.floor(num/100).toString();
  if(cents<10)
      cents = "0" + cents;
  for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
      num = num.substring(0,num.length-(4*i+3)) + ',' + num.substring(num.length-(4*i+3));
  return (((sign)?'':'-') + '$' + num + '.' + cents);
}

function CalculateAll(inputItem)
{
  with (inputItem.form) 
  {
    val = 0;
    VG = 0;
    CV = 0;
    DR = 0;
    
    for (i=0; i < document.selectionForm.elements.length; i++) 
    {
      if (document.selectionForm.elements[i].type == 'checkbox') 
      {
        if (document.selectionForm.elements[i].checked)
        {
           val += eval(document.selectionForm.elements[i].value); 
           if (document.selectionForm.elements[i].name == "VideoGet") VG = 1;
           if (document.selectionForm.elements[i].name == "ConvertVid") CV = 1;
           if (document.selectionForm.elements[i].name == "DiscRipper") DR = 1;
        }
      }
    }
    
    whole=val;
    
    if (VG && CV && DR)
    {
      val *= 0.75
    } 
    else if ((VG && DR) || (DR && CV))
    {
      val *= 0.85
    } 
    else if (VG && CV)
    {
      val *= 0.9
    } 
    
    percent = Math.round((whole-val)/whole*100);
    if(isNaN(percent))
    { 
      percent = 0;
    }
    
    payment_fee = pmethod[1].checked ? 4 : 0;
    stand.value = formatCurrency(whole);
    saved.value = '-' + formatCurrency(whole-val) + ' (' + percent + '% економии)';
    fees.value = formatCurrency(payment_fee);
    total.value = formatCurrency(val + payment_fee);
  }
  
  return;
}

function InitForm(id) 
{
  for (i=0; i < document.selectionForm.elements.length; i++) 
  {
    if (document.selectionForm.elements[i].type == 'checkbox') 
    {
      if(id == '' || document.selectionForm.elements[i].name == id)
        document.selectionForm.elements[i].checked = true;
        
      inputItem = document.selectionForm.elements[i];
    }
  }
  CalculateAll(inputItem);
}
