var activeDropDown = null;
function CustomDropDown(selectId, textInputId, valueInputId, options)
{
  this.options = options.Options;

  this.textInputId = textInputId;
  this.valueInputId = valueInputId;
  this.selectId = selectId;
  this.selectedIdx = -1;
  this.activated = false;
  this.normalClass = "";
  this.selectedClass = "";
  this.lock = false;
}

CustomDropDown.prototype.Activate = function(normalClass, selectedClass)
{
  if (!this.activated)
  {
    this.normalClass = normalClass;
    this.selectedClass = selectedClass;
    $(this.textInputId).onkeydown = this.HandleKey;

    this.activated = true;
    activeDropDown = this;
  }
  this.Show();
}

CustomDropDown.prototype.DeActivate = function()
{
  if (!this.lock)
  {
    this.activated = false;
    activeDropDown = null;
    this.Hide();
  }
}

CustomDropDown.prototype.Select = function()
{
  var idx = this.selectedIdx;;
  if (idx < 0 || idx >= this.options.length)
    return;

  var opt = this.options[idx];
  $(this.textInputId).value = opt.Text;
  $(this.valueInputId).value = opt.Value;
  $(this.selectId).style.display = "none";
}

CustomDropDown.prototype.Show = function()
{
  $(this.selectId).style.display  = "";
}

CustomDropDown.prototype.Hide = function()
{
 $(this.selectId).style.display = "none";
}

CustomDropDown.prototype.ActivateOption = function(activeIdx)
{
 var node = $(this.selectId).childNodes[0];
 for (var idx = 0; idx < this.options.length; ++idx)
  {
      if (!node)
        break;

      while (node.nodeType != 1)//jump over text
      {
        node = node.nextSibling
      }
      if (idx == activeIdx)
          node.className = this.selectedClass;
      else
          node.className = this.normalClass;

      node = node.nextSibling;
  }
  this.selectedIdx = activeIdx
}

CustomDropDown.prototype.HandleKey = function(evt)
{
  var key = KeyCode(evt);

  if (key == 40 && activeDropDown.selectedIdx < activeDropDown.options.length -1)
  {
    activeDropDown.ActivateOption(activeDropDown.selectedIdx + 1);
  }
  else if (key == 38 && activeDropDown.selectedIdx > 0)
  {
    activeDropDown.ActivateOption(activeDropDown.selectedIdx - 1);
  }
  else if (key == 13)
  {
    activeDropDown.Select();
  }
  return false;
}

CustomDropDown.prototype.Lock = function ()
{
  this.lock = true;
}


CustomDropDown.prototype.UnLock = function ()
{
  this.lock = false;
}