function getElById(id)
{
  return document.getElementById(id);
}

function walkIds(ids, callback)
{
  var el;
  for (i in ids)
  {
    el = getElById(ids[i]);
    if (el) { callback(el); }
  }
}

function getSelectValue(select)
{
  try
  {
    return select.options[select.selectedIndex].value;
  }
  catch (e) {}
  return null;
}

function setSelectValue(select, value)
{
  for (var i = select.options.length - 1; i >= 0; i--)
  {
    if (select.options[i].value == value)
    {
      select.selectedIndex = i;
      return;
    }
  }
}

function indexOf(ar, val)
{
  for (var i in ar)
  {
    if (ar[i] == val) { return parseInt(i); }
  }  
  return -1;
}

function getKeys(obj)
{
  var keys = [];
  for (var k in obj) { keys.push(k); }
  return keys;
}

function multiAt(obj, indexes)
{
  var result = {}; var index;
  for (var i in indexes)
  {
    index = indexes[i];
    if (obj[index] != undefined)
    {
      result[index] = obj[index];
    }
  }
  return result;
}

function merge(obj1, obj2)
{
  var result = {};
  
  for (var i in obj1)
  {
    result[i] = obj1[i];
  }

  for (var i in obj2)
  {
    result[i] = obj2[i];        
  }

  return result;
}

function intersect(obj1, obj2)
{
  var tmp    = {};
  var result = [];

  for (var i in obj1)
  {
    tmp[obj1[i]] = true;
  }

  for (var i in obj2)
  {
    if (tmp[obj2[i]])
    {
      result.push(obj2[i]);
    }
  }

  return result;
}

function toggle(id)
{
  var el = getElById(id);
  el.style.display = (el.style.display == 'none') ? 'block' : 'none';
  return false;
}

var calc =
{
  loaded: false,
  T: {}, wmid_ps_id: -1, ps_ids_with_wmid: {}, type: null,
  curs: {}, curs_order: {}, curRates: {},
  ps: {}, ps_order: {}, dirs: {}, cur4dirs: {}, ecs: {}, ecsInOutLimit: {},
  tscs: {}, tsRates: {}, userPurses: {},
  countriesWithEuRate: [], transferRateOutsideEu: {},
  wrapPostfix: '_wrap',
  attrs:
  {
    ps_in:  'id="ps_in" name="calculator[payment_system_in_id]" onchange="calc.changed(\'ps_in\');"',
    c_in:   'id="c_in" name="calculator[currency_in_id]" class="currency" onchange="calc.changed(\'c_in\');"',
    ps_out: 'id="ps_out" name="calculator[payment_system_out_id]" onchange="calc.changed(\'ps_out\');"',
    c_out:  'id="c_out" name="calculator[currency_out_id]" class="currency" onchange="calc.changed(\'c_out\');"'
  },

  renderSelect: function(items, order, attrs)
  {
    if (!items) { return ''; }

    var id;
    var result = '<select ' + attrs + '>';    
    for (var i in order)
    {
      id = order[i];
      if (items[id])
      {
        result += ('<option value="' + id + '">' + items[id] + '</option>');
      }
    }
    return result + '</select>';
  },

  draw: function (name)
  {
    var el = getElById(name + this.wrapPostfix);
    if (!el) { return; }
    el.innerHTML = this.renderSelect(this.getItems(name), this.getOrder(name), this.attrs[name]);
  },

  toggleMtWtOutForm: function ()
  {    
    if (this.tscs[getSelectValue(getElById('ps_out'))]
      [getSelectValue(getElById('c_out'))].is_need_out_bank_info)
    {
      getElById('bank_info_wrap').style.display = 'block';
      getElById('operation_for_wt_wrap').style.display = 'block';
      getElById('operation_for_mt_wrap').style.display = 'none';
    }
    else
    {
      getElById('bank_info_wrap').style.display = 'none';
      getElById('operation_for_wt_wrap').style.display = 'none';
      getElById('operation_for_mt_wrap').style.display = 'block';        
    }
  },
  
  insertUserPurse: function(psId, elIds)
  {    
    var purse = this.userPurses[psId];
    if (!purse) { purse = ''; }

    walkIds(elIds, function (el) {
      if (calc.loaded || !el.value)
      {
        el.value = purse;
      }
    });
  },

  insertWmid: function(elIds)
  {
    var wmid = (this.wmid_ps_id == -1 ? '' : this.userPurses[this.wmid_ps_id]);
    if (!wmid) { wmid = ''; }

    walkIds(elIds, function (el) {
      if (calc.loaded || !el.value)
      {
        el.value = wmid;
      }
    });
  },

  changed: function (name)
  {
    var chain = ['ps_in', 'ps_out', 'c_in', 'c_out'];

    if (this['changed_' + name]())
    {
      for (var i = indexOf(chain, name) + 1; i < chain.length; i++)
      {
        this.draw(chain[i]);
        this['changed_' + chain[i]]();
      }
    }

    this.calc();
    if (this.formType == 'out')
    {
      this.toggleMtWtOutForm();
    }
  },

  changed_ps_in: function()
  {
    var ps_in = getSelectValue(getElById('ps_in'));

    walkIds(['label_ps_in', 'label_ps_in_mt', 'label_ps_in_wt'], function (el) {
      el.innerHTML = calc.ps[ps_in];
    });

    this.insertUserPurse(ps_in,
      ['operation_user_account_out', 'operation_for_mt_user_account_out', 'operation_for_wt_user_account_out']
    );
    this.insertWmid(
      ['operation_user_wmid_out', 'operation_for_wt_user_wmid_out', 'operation_for_mt_user_wmid_out']
    );

    if (this.formType == 'all')
    {      
      getElById('c_in_wrap').style.display = this.tscs[ps_in] ? 'inline' : 'none'; 
    }

    //wmid
    var trEl;
    var wmidTrNames = ['tr_operation_user_wmid_out',
      'tr_operation_for_wt_user_wmid_out', 'tr_operation_for_mt_user_wmid_out'
    ];
    for (var i in wmidTrNames)
    {
      trEl = getElById(wmidTrNames[i]);
      if (!trEl) { continue; }

      trEl.className = this.ps_ids_with_wmid[ps_in] ? 'tr_vis' : 'tr_hid'; 
    }

    return true;
  },

  changed_c_in: function ()
  {
    return false;
  },

  changed_ps_out: function ()
  {
    var ps_out = getSelectValue(getElById('ps_out'));

    walkIds(['label_ps_out', 'label_ps_out_confirm'], function (el) {
      el.innerHTML = calc.ps[ps_out]; 
    });

    this.insertUserPurse(ps_out, ['operation_user_account_in', 'operation_user_account_in_confirm']);
    
    if (this.formType == 'all')
    {         
      getElById('c_out_wrap').style.display = this.tscs[ps_out] ? 'inline' : 'none'; 
    }

    // credit card
    var trEl;
    var ccTrNames = ['tr_operation_for_mt_user_credit_card', 'tr_operation_for_mt_user_credit_card_confirm'];
    for (var i in ccTrNames)
    {
      trEl = getElById(ccTrNames[i]);
      if (!trEl) { continue; }
      
      if (this.ps[ps_out] && this.ps[ps_out] == 'Credit/Debit Card')
      {
        trEl.className = 'tr_vis';
      }
      else
      {
        trEl.className = 'tr_hid';
      }
    }

    return true;
  },
  
  changed_c_out: function ()
  {
    return false;
  },

  getOrderType: function ()
  {
    if (this.formType != 'all') { return this.formType; }

    var tsIn  = this.tscs[getSelectValue(getElById('ps_in'))];
    var tsOut = this.tscs[getSelectValue(getElById('ps_out'))];

    if (tsIn && !tsOut)
    {
      return 'in';
    }
    else if (!tsIn && tsOut)
    {
      return 'out';
    }
    else if (!tsIn && !tsOut)
    {
      return 'exchange';
    }

    return null;
  },

  getCurIds: function ()
  {
    var orderType = this.getOrderType();
    if (orderType == 'in')
    {
      return [
        getSelectValue(getElById('c_in')),
        this.ecs[getSelectValue(getElById('ps_out'))].cur_id
      ];
    }
    else if (orderType == 'out')
    {
      return [
        this.ecs[getSelectValue(getElById('ps_in'))].cur_id,
        getSelectValue(getElById('c_out'))
      ];
    }
    else if (orderType == 'exchange')
    {
      return [
        this.ecs[getSelectValue(getElById('ps_in'))].cur_id,
        this.ecs[getSelectValue(getElById('ps_out'))].cur_id
      ];
    }

    return [];
  },

  getRate: function (curId1, curId2)
  {
    if (curId1 == curId2) { return 1.0; }
    var rate = this.curRates[curId1][curId2];
    return rate ? rate : 0.0;
  },
  
  compareMoney: function (arg1, arg2)
  {
    arg1 = Math.round(arg1 * 100.0) / 100.0;
    arg2 = Math.round(arg2 * 100.0) / 100.0;

    if (Math.abs(arg1 - arg2) < 0.01) { return 0; }
    if (arg1 < arg2) { return -1; }
    return +1;
  },

  smartPercent: function (obj, amount, refRate)
  {
    var result = 0.0;
    if (amount < 0) { amount = 0.0; }

    var floors = getKeys(obj.rates).reverse();
    var rate; var floor; var amountForPercent;
    for (var i in floors)
    {
      floor = floors[i];
      rate = obj.rates[floor];

      if (refRate != undefined)
      {
        refRate.rate = rate;
        refRate.min_amount = obj.min_amount;
        refRate.max_amount = obj.max_amount;
        if (obj.min_for_percent) { refRate.min_for_percent = obj.min_for_percent; }
        if (obj.max_for_percent) { refRate.max_for_percent = obj.max_for_percent; }
      }

      if (this.compareMoney(amount, floor) > 0)
      {
        amountForPercent = amount * (rate[1] / 100.0);
        if (obj.min_for_percent && this.compareMoney(amountForPercent, obj.min_for_percent) < 0)
        {
          amountForPercent = obj.min_for_percent;
        }
        if (obj.max_for_percent && this.compareMoney(amountForPercent, obj.max_for_percent) > 0)
        {          
          amountForPercent = obj.max_for_percent;
        }

        result = rate[0] + amountForPercent;
        break;
      }
    }

    var min = obj.min_amount;
    if (min && this.compareMoney(result, min) < 0)
    {
      result = min;
    }

    var max = obj.max_amount;
    if (max && this.compareMoney(result, max) > 0)
    {
      result = max;
    }

    return result;
  },  

  smartPercentRev: function (ratesObj, amount, sign)
  {
    if (typeof(sign) == 'undefined') { sign = +1; }
    if (amount < 0) { amount = 0.0; }
    
    var rates = ratesObj.rates;
    var floors = getKeys(rates).reverse();
    var floor;    
    for (var i in floors)
    {
      floor = floors[i];
      if (calc.compareMoney(amount, floor - sign * calc.smartPercent(ratesObj, floor)) > 0)
      {
        break;
      }
    }
    var base = rates[floor][0];
    var percent = rates[floor][1] / 100.0;
    var result = null;

    var minForPercent = ratesObj.min_for_percent;
    if (minForPercent)
    {
      var x4minPercent = minForPercent / percent;
      //out = x4min_percent - sign * (base + min4percent)
      if (calc.compareMoney(amount, x4minPercent - sign * (base + minForPercent)) <= 0)
      {
        result = base + minForPercent;// = percent
      }
    }

    var maxForPercent = ratesObj.max_for_percent;
    if (maxForPercent)
    {
      var x4maxPercent = maxForPercent / percent;
      //out = x4max_percent  - sign * (base + max4percent)
      if (calc.compareMoney(amount, x4maxPercent - sign * (base + maxForPercent)) >= 0)
      {        
        result = base + maxForPercent;// = percent
      }
    }

    //out = in  - sign * (base + in * percent)
    //in = (out + sign * base) / (1 - sign * percent)
    if (result == null)
    {
      result = Math.abs(amount - (amount + sign * base) / (1.0 - sign * percent));// = percent = out - in
    }

    var min = ratesObj.min_amount;
    if (min && calc.compareMoney(result, min) < 0)
    {
      result = min;
    }

    var max = ratesObj.max_amount;
    if (max && calc.compareMoney(result, max) > 0)
    {
      result = max;
    }

    return result;
  },

  getTsRate: function(psId, cId)
  {
    var ts = this.tscs[psId][cId];
    if (ts)
    {
      return this.tsRates[ts.id];
    }
    
    return null;
  },

  getTrForOut: function(country, psId, cId)
  {
    var psOutName  = this.ps[psId].toLowerCase();
    var curOutName = this.curs[cId].toLowerCase();

    if (country && psOutName === 'international wire transfer' && curOutName === 'eur')
    {
      var iwtForOut = null;
      if (indexOf(this.countriesWithEuRate, country.toLowerCase()) == -1)
      {
        iwtForOut = this.transferRateOutsideEu;
      }
      if (iwtForOut) { return iwtForOut; }    
    }

    return this.getTsRate(psId, cId);
  },

  calc: function (only_limit_and_rate)
  {
    var amountInEl = getElById('amount_in');
    var amountToUserEl = getElById('amount_to_user');
    var limitAndRateEl = getElById('limit_and_rate');

    var c = {
      amount_in: (Math.round(parseFloat(amountInEl.value) * 100.0) / 100.0),
      fee: 0.0,
      transfer_out_loss: 0.0,
      amount_to_user: 0.0
    };

    if (isNaN(c.amount_in))
    {
      c.amount_in = 0.0;
    }

    var ps_in = getSelectValue(getElById('ps_in'));
    var ps_out = getSelectValue(getElById('ps_out'));

    var dir = this.dirs[ps_in][ps_out];
    var orderType = this.getOrderType();
    var curIds = this.getCurIds();
    var in2outScale = this.getRate(curIds[0], curIds[1]);

    var amountOut = c.amount_in * in2outScale;

    var feeRate = {};
    c.fee = this.smartPercent(dir, amountOut, feeRate);

    if (orderType === 'out')
    {      
      var tsRate = this.getTrForOut(getSelectValue(getElById('out_user_bank_info_bank_country')),
        ps_out, getSelectValue(getElById('c_out'))
      );
      if (tsRate && !tsRate.alter_url)
      {
        c.transfer_out_loss = this.smartPercentRev(tsRate, amountOut - c.fee, -1);
      }
    }
    c.amount_to_user = amountOut - c.fee - c.transfer_out_loss;

    c.amount_to_user    = Math.round(c.amount_to_user * 100) / 100;
    c.transfer_out_loss = Math.round(c.transfer_out_loss * 100) / 100;

    if (!only_limit_and_rate)
    {
      amountToUserEl.value = isNaN(parseFloat(amountInEl.value)) ? '' : c.amount_to_user;
    }

    var limitAndRate = this.T['Fee:'] + ' ' + feeRate.rate[1] + '%';
    if (feeRate.min_for_percent)
    {
      limitAndRate += (' (' + this.T['min'] + ' ' + feeRate.min_for_percent + ' ' + this.curs[curIds[1]] + ')');
    }
    if (feeRate.rate[0])
    {
      limitAndRate += (' + ' + feeRate.rate[0] + ' ' + this.curs[curIds[1]]);
    }
    if (feeRate.min_amount)
    {
      limitAndRate += (' (' + this.T['min fee'] + ' ' + feeRate.min_amount + ' ' + this.curs[curIds[1]] + ')');
    }

    if (orderType === 'out')
    {
      var tscs = this.tscs[ps_out][curIds[1]];
      if (tscs.out_rate_label)
      {
        var tsRate = this.getTrForOut(getSelectValue(getElById('out_user_bank_info_bank_country')),
          ps_out, getSelectValue(getElById('c_out'))
        );
        if (tsRate && tsRate.alter_url)
        {
          limitAndRate += (' + <a href="' + tsRate.alter_url + '" target="_blank">' + tscs.out_rate_label + '</a>');
        }
        else
        {
          limitAndRate += (' + ' + tscs.out_rate_label);
          if (c.transfer_out_loss) { limitAndRate += (' ' + c.transfer_out_loss + ' ' + this.curs[curIds[1]]); }
        }
      }
    }

    limitAndRateEl.innerHTML = limitAndRate;
    this.checkOrder();
  },

  getEc: function(ps_id)
  {
    return this.ecs[ps_id];
  },

  getTs: function(ps_id, c_id)
  {
    return this.tscs[ps_id][c_id];
  },

  getEcLimit: function(ec, ts)
  {    
    if (this.ecsInOutLimit[ec.id] && this.ecsInOutLimit[ec.id][ts.id])
    {
      return this.ecsInOutLimit[ec.id][ts.id];
    }
    return null;
  },

  error: function(msg, vars)
  {
    var t = this.T[msg] ? this.T[msg] : msg;
    for (var i in vars)
    {
      t = t.replace('%' + i + '%', vars[i], 'g');
    }
    return '<ul class="error_list"><li>' + t + '</li></ul>';
  },

  checkOrder: function()
  {
    if (!this.loaded) { return; }

    var errors = {'amount_in' : '', 'amount_to_user': ''};
    var ps_in = getSelectValue(getElById('ps_in'));
    var ps_out = getSelectValue(getElById('ps_out'));
    var cur_ids = calc.getCurIds();

    var orderType = this.getOrderType();
    var dir = this.dirs[ps_in][ps_out];
    if (!dir) { return; }

    var amount_in = parseFloat(getElById('amount_in').value);
    var amount_to_user = parseFloat(getElById('amount_to_user').value);     
    if (isNaN(amount_in) || isNaN(amount_to_user))
    {
      getElById('amount_in_error_wrap').innerHTML = '';
      getElById('amount_in_error_wrap').style.display = 'none';
      getElById('amount_to_user_error_wrap').innerHTML = '';
      getElById('amount_to_user_error_wrap').style.display = 'none';
      return;
    }

    var tsIn, tsOut, ecIn, ecOut, ecLimit;
    if (orderType == 'in')
    {
      tsIn  = this.getTs(ps_in, cur_ids[0]);
      ecOut = this.getEc(ps_out);
      ecLimit = this.getEcLimit(ecOut, tsIn);
    }
    else if (orderType == 'out')
    {
      ecIn  = this.getEc(ps_in);
      tsOut = this.getTs(ps_out, cur_ids[1]);
      ecLimit = this.getEcLimit(ecIn, tsOut);
    }
    else if (orderType == 'exchange')
    {
      ecIn  = this.getEc(ps_in);
      ecOut = this.getEc(ps_out);
    }
    else { return; }

    var amount_in_min = null, amount_in_max = null;
    var amount_to_user_min = null, amount_to_user_max = null;

    if (dir.min_out && this.compareMoney(amount_to_user, dir.min_out) < 0)
    {
      amount_to_user_min = dir.min_out;
      errors['amount_to_user'] = this.error('amount_to_user_min_error', {'min': amount_to_user_min});
    }
    else if (orderType == 'in')
    {
      var _amount_in_min = ecLimit ? ecLimit.min_in : tsIn.min_in;      
      if (this.compareMoney(amount_in, _amount_in_min) < 0)
      {
        amount_in_min = _amount_in_min;
        errors['amount_in'] = this.error('amount_in_min_error', {'min': amount_in_min});
      }
    }
    else if (orderType == 'out')
    {
      var _amount_to_user_min = ecLimit ? ecLimit.min_out : tsOut.min_out;
      if (this.compareMoney(amount_to_user, _amount_to_user_min) < 0)
      {
        amount_to_user_min = _amount_to_user_min;
        errors['amount_to_user'] = this.error('amount_to_user_min_error', {'min': amount_to_user_min});
      }
    }
    else if (orderType == 'exchange')
    {
      if (this.compareMoney(amount_in, ecIn.exchange_min_in) < 0)
      {
        amount_in_min = ecIn.exchange_min_in;
        errors['amount_in'] = this.error('amount_in_min_error', {'min': amount_in_min});
      }
    }

    if (dir.max_in && this.compareMoney(amount_in, dir.max_in) > 0)
    {
      amount_in_max = dir.max_in;
      errors['amount_in'] = this.error('amount_in_max_error', {'max': amount_in_max});
    }
    else if (orderType == 'in')
    {
      var _amount_in_max = ecLimit ? ecLimit.max_in: tsIn.max_in;
      if (this.compareMoney(amount_in, _amount_in_max) > 0)
      {
        amount_in_max = _amount_in_max;
        errors['amount_in'] = this.error('amount_in_max_error', {'max': amount_in_max});
      }
    }
    else if (orderType == 'out')
    {
      var _amount_to_user_max = ecLimit ? ecLimit.max_out : tsOut.max_out;
      if (this.compareMoney(amount_to_user, _amount_to_user_max) > 0)
      {
        amount_to_user_max = _amount_to_user_max;
        errors['amount_to_user'] = this.error('amount_to_user_max_error', {'max': amount_to_user_max});
      }
    }

    if (this.compareMoney(amount_to_user, 0.0) <= 0)
    {
      amount_to_user_min = 0.0;
      errors['amount_to_user'] = this.error('amount_to_user_less_then_0');
    }
    else if (orderType == 'in' || orderType == 'exchange')
    {
      var _amount_to_user_max = (ecOut.balance > 0 ? ecOut.balance : 0);      
      if (this.compareMoney(amount_to_user, _amount_to_user_max) > 0)
      {
        amount_to_user_max = _amount_to_user_max;
        errors['amount_to_user'] = this.error('amount_to_user_great_then_ec_balance', {'max': amount_to_user_max});
      }
    }
    else if (orderType == 'out')
    {
      var _amount_to_user_max = tsOut.balance > 0 ? tsOut.balance : 0;
      if (this.compareMoney(amount_to_user, _amount_to_user_max) > 0)
      {
        amount_to_user_max = _amount_to_user_max;
        errors['amount_to_user'] = this.error('amount_to_user_great_then_mts_balance', {'max': amount_to_user_max});
      }
    }

    if (errors)
    {     
      var in_to_out_scale = this.getRate(cur_ids[0], cur_ids[1]);
      if (errors['amount_in'] && errors['amount_to_user'])
      {
        if (amount_in_max != null && amount_to_user_max != null)
        {
          if (this.compareMoney(amount_in_max * in_to_out_scale, amount_to_user_max) > 0)
          {
            errors['amount_in'] = '';
          }
          else
          {
            errors['amount_to_user'] = '';
          }
        }
        else if (amount_in_min != null && amount_to_user_min != null)
        {
          if (this.compareMoney(amount_in_min * in_to_out_scale, amount_to_user_min) < 0)
          {
            errors['amount_in'] = '';
          }
          else
          {
            errors['amount_to_user'] = '';
          }
        }
      }

      var el;
      for (var i in errors)
      {
        el = getElById(i + '_error_wrap');
        el.innerHTML = errors[i];
        el.style.display = errors[i] ? 'block' : 'none';
      }
    }
  },

  recalc: function ()
  {
    var amountInEl = getElById('amount_in');
    var amountToUserEl = getElById('amount_to_user');

    var c = {
      amount_in: 0.0,
      fee: 0.0,
      transfer_out_loss: 0.0,
      amount_to_user: (Math.round(parseFloat(amountToUserEl.value) * 100.0) / 100.0)
    };

    if (isNaN(c.amount_to_user))
    {
      amountInEl.value = '';
      this.checkOrder();
      return;
    }

    var ps_in = getSelectValue(getElById('ps_in'));
    var ps_out = getSelectValue(getElById('ps_out'));

    var dir = this.dirs[ps_in][ps_out];
    var orderType = this.getOrderType();
    var curIds = this.getCurIds();
    var in2outScale = this.getRate(curIds[0], curIds[1]);

    if (orderType === 'out')
    {
      var tsRate = this.getTrForOut(getSelectValue(getElById('out_user_bank_info_bank_country')),
        ps_out, getSelectValue(getElById('c_out'))
      );
      if (tsRate && !tsRate.alter_url)
      {
        c.transfer_out_loss = this.smartPercent(tsRate, c.amount_to_user);
      }
    }

    c.fee = c.fee + this.smartPercentRev(dir, c.amount_to_user + c.transfer_out_loss + c.fee);

    c.amount_in = (c.amount_to_user + c.fee + c.transfer_out_loss) / in2outScale;
    c.amount_in = Math.round(c.amount_in * 100) / 100;

    amountInEl.value = c.amount_in;
    this.calc(true);
  },
  
  getOrder: function (name)
  {
    if (name == 'ps_in' || name == 'ps_out')
    {
      return this.ps_order;
    }
    else if (name == 'c_in' || name == 'c_out')
    {
      return this.curs_order;
    }

    return [];  
  },

  getItems: function (name)
  {
    return this['get_' + name + '_items']();
  },  
  
  get_ps_in_items: function ()
  {
    return multiAt(this.ps, getKeys(this.dirs));
  },

  get_c_in_items: function ()
  {    
    try
    {
      var ps_in  = getSelectValue(getElById('ps_in'));
      var ps_out = getSelectValue(getElById('ps_out'));
      var dirId  = this.dirs[ps_in][ps_out].id;

      return multiAt(this.curs,
        intersect(getKeys(this.tscs[ps_in]), getKeys(this.cur4dirs[dirId]))
      );
    }
    catch (e) {}
    return {};
  },

  get_ps_out_items: function ()
  {
    var ps_in = getSelectValue(getElById('ps_in'));
    return multiAt(this.ps, getKeys(this.dirs[ps_in]));
  },

  get_c_out_items: function ()
  {
    try
    {
      var ps_in  = getSelectValue(getElById('ps_in'));
      var ps_out = getSelectValue(getElById('ps_out'));
      var dirId  = this.dirs[ps_in][ps_out].id;

      return multiAt(this.curs,
        intersect(getKeys(this.tscs[ps_out]), getKeys(this.cur4dirs[dirId]))
      );
    }
    catch (e) {}
    return {};
  }
};





function HideAllContentWithIDContaining(d)
{
  if(d.length < 1) { return; }  
  var divs = document.getElementsByTagName('div');  
  for (var j=0; j < divs.length; j++)
  {  
    if(divs[j].id.indexOf(d) != -1)
    {
      divs[j].style.display = "none";
    }
  }
}

function HideContent(d)
{
  if(d.length < 1) { return; }
  document.getElementById(d).style.display = "none";
}

function ShowContent(d) 
{
  if(document.getElementById(d)!=null)
  {
    //start by hiding all DIVS
    HideAllContentWithIDContaining("RB");
    //and unselect current tab selection
    //UnselectTabImages();
    
    //now show the requested DIV   
    if(d.length < 1) { return; }
    document.getElementById(d).style.display = "block";
  }
}

function ReverseContentDisplay(d) 
{
  if(d.length < 1) { return; }
  if(document.getElementById(d).style.display == "none") { document.getElementById(d).style.display = "block"; }
  else { document.getElementById(d).style.display = "none"; }
}