function CreateXmlHttpRequest()
{
  try
  {
    return new XMLHttpRequest();
  }
  catch(e)
  {
    try
    {
      return new ActiveXObject('Msxml2.XMLHTTP');
    }
    catch(e)
    {
      try
      {
        return new ActiveXObject('Microsoft.XMLHTTP');
      }
      catch(e)
      {
        return null;
      }
    }
  }
}

function LoadData(from, callback)
{
  var xhr = CreateXmlHttpRequest();
  if(!xhr)
  {
    // error
    return;
  }
  xhr.open('GET', from, true);
  xhr.onreadystatechange = function()
  {
    if(xhr.readyState != 4)
    {
      return;
    }
    if(xhr.status == 200)
    {
      var json = xhr.responseText.replace(/\r/g, '');
      json = json.replace(/\n/g, '');
      callback(eval('(' + json + ')'));
      return;
    }
    // error
  }
  xhr.send(null);
}

function ById(id)
{
  return document.getElementById(id);
}

function DisableCalc(idx, reset)
{
  var ids = new Array('cbOrgs', 'cbCountries', 'cbTypes', 'cbCurrs', 'iAmount', 'bCalc');
  for(var i=idx; i<ids.length; i++)
  {
    if(reset && i > 0)
    {
      var obj = ById(ids[i]);
      obj.disabled = true;
      if(obj.tagName.toUpperCase() == 'SELECT')
      {
        obj.selectedIndex = 0;
      }
    }
    else
    {
      ById(ids[i]).disabled = true; 
    }
  }
}

function EnableCalc(idx)
{
  var ids = new Array('cbOrgs', 'cbCountries', 'cbTypes', 'cbCurrs', 'iAmount', 'bCalc');
  for(var i=0; i<idx; i++)
  {
    if(i == 5)
    {
      AmountKeyUp(null)
    }
    else
    {
      ById(ids[i]).disabled = false;
    }
  }
}

function OrgChanged(cbOrgs)
{
  DisableCalc(0, true);
  var langId = ById('iLangId').value;
  var orgId = cbOrgs.options[cbOrgs.selectedIndex].id;
  ById('sCountries').style.display = 'block';
  LoadData('/pub/dust/getCountries.jsp?lang=' + langId + '&orgId=' + orgId, CountriesLoaded);
}

function CountriesLoaded(countries)
{
  var cbCountries = ById('cbCountries');
  cbCountries.length = countries.arr.length;
  for(i=0; i<countries.arr.length; i++)
  {
    cbCountries.options[i].text = countries.arr[i].name;
    cbCountries.options[i].id = countries.arr[i].id;
  }
  EnableCalc(2);
  ById('sCountries').style.display = 'none';
}

function CountryChanged(cbCountries)
{
  if(cbCountries.options[cbCountries.selectedIndex].id < 0)
  {
    DisableCalc(2, true);
    return;
  }
  DisableCalc(0);
  var cbOrgs = ById('cbOrgs');
  var orgId = cbOrgs.options[cbOrgs.selectedIndex].id;
  var langId = ById('iLangId').value;
  var countryId = cbCountries.options[cbCountries.selectedIndex].id;
  ById('sTypes').style.display = 'block';
  LoadData('/pub/dust/getTTypes.jsp?org=' + orgId + '&lang=' + langId + '&country=' + countryId, TransferTypesLoaded);
}

function TransferTypesLoaded(ttypes)
{
  var cbTypes = ById('cbTypes');
  cbTypes.length = ttypes.arr.length;
  for(i=0; i<ttypes.arr.length; i++)
  {
    cbTypes.options[i].text = ttypes.arr[i].name;
    cbTypes.options[i].id = ttypes.arr[i].id;
  }
  EnableCalc(3);
  ById('sTypes').style.display = 'none';
}

function TransferTypeChanged(cbTypes)
{
  if(cbTypes.options[cbTypes.selectedIndex].id < 0)
  {
    DisableCalc(3, true);
    return;
  }
  DisableCalc(0);
  var ttId = cbTypes.options[cbTypes.selectedIndex].id;
  var cbCountries = ById('cbCountries');
  var countryId = cbCountries.options[cbCountries.selectedIndex].id;
  var cbOrgs = ById('cbOrgs');
  var orgId = cbOrgs.options[cbOrgs.selectedIndex].id;
  var langId = ById('iLangId').value;
  ById('sCurrs').style.display = 'block';
  LoadData('/pub/dust/getCurrs.jsp?org=' + orgId + '&lang=' + langId + '&country=' + countryId + '&tt=' + ttId, CurrsLoaded);
}

function CurrsLoaded(currs)
{
  var cbCurrs = ById('cbCurrs');
  cbCurrs.length = currs.arr.length;
  for(i=0; i<currs.arr.length; i++)
  {
    cbCurrs.options[i].text = currs.arr[i].name;
    cbCurrs.options[i].id = currs.arr[i].id;
  }
  EnableCalc(4);
  ById('sCurrs').style.display = 'none';
}

function CurrChanged(cbCurrs)
{
  if(cbCurrs.options[cbCurrs.selectedIndex].id < 0)
  {
    DisableCalc(4, true);
    return;
  }
  EnableCalc(6);
}

function Calculate()
{
  DisableCalc(0);
  var cbOrgs = ById('cbOrgs');
  var orgId = cbOrgs.options[cbOrgs.selectedIndex].id;
  var cbCountries = ById('cbCountries');
  var countryId = cbCountries.options[cbCountries.selectedIndex].id;
  var cbTypes = ById('cbTypes');
  var ttId = cbTypes.options[cbTypes.selectedIndex].id;
  var cbCurrs = ById('cbCurrs');
  var currId = cbCurrs.options[cbCurrs.selectedIndex].id;
  ById('sAmount').style.display = 'block';
  LoadData('/pub/dust/getFormula.jsp?org=' + orgId + '&country=' + countryId + '&tt=' + ttId + '&curr=' + currId, FormulaLoaded);
}

function FormulaLoaded(rate)
{
  var formula = rate.formula.replace(/:I:/g, ById('iAmount').value);
  formula = formula.replace(/:R:/g, rate.rate);
  ById('sAmount').style.display = 'none';
  try
  {
    var res = eval(formula);
    ById('iResult').value = res.toFixed(2);
  }
  catch(e)
  {
    alert(ById('errorMsg').value);
  }
  EnableCalc(6);
}

function Trim(s)
{
  return s.replace(/^\s+|\s+$/g, '');
}

function AmountKeyUp(e)
{
  var txt = Trim(ById('iAmount').value);
  if(txt.length == 0)
  {
    ById('bCalc').disabled = true;
    return;
  }
  if(isNaN(txt))
  {
    ById('sErrAmount').style.display = 'block';
    ById('bCalc').disabled = true;
  }
  else
  {
    ById('sErrAmount').style.display = 'none';
    if(e)
    {
      var code = window.event ? e.keyCode : e.which;
      if(code == 13)
      {
        Calculate();
        return;
      }
    }
    ById('bCalc').disabled = false;
  }
}

function UpdateRate(button)
{
  var id = button.id.substring(button.id.indexOf('.') + 1);
  var rate = ById('val.' + id).value;
  if(isNaN(rate))
  {
    alert(ById('calc.errmsg').value);
    return;
  }
  button.disabled = true;
  
  var load = ById('load.' + id);
  var err = ById('err.' + id);
  var info = ById('info.' + id);
  
  err.style.display = 'none';
  info.style.display = 'none';
  load.style.display = 'block';
  
  var xhr = CreateXmlHttpRequest();
  if(!xhr)
  {
    err.onclick = function(){ alert(ById('editor.noxhr').value); }
    load.style.display = 'none';
    err.style.display = 'block';
    button.disabled = false;
    return;
  }
  xhr.open('GET', '/pub/dust/updateRate.jsp?uid=' + id + '&rate=' + rate, true);  
  xhr.onreadystatechange = function()
  {
    if(xhr.readyState != 4)
    {
      return;
    }
    if(xhr.status == 200)
    {
      load.style.display = 'none';
      info.style.display = 'block';
      button.disabled = false;
      return;
    }
    var msg = ById('editor.reterr').value;
    msg += '\n\nTechnical info:';
    msg += '\n - Status: ' + xhr.status;
    msg += '\n - Message: ' + xhr.statusText;
    err.onclick = function(){ alert(msg); }
    load.style.display = 'none';
    err.style.display = 'block';
    button.disabled = false;
  }
  xhr.send(null);  
}

