// © 2004-2007, Applied Geographics, Inc.  All rights reserved.

function DropDownList(id) {
  this.element = document.getElementById(id);
  this.text = "";
  this.onchange = null;
  this.index = -1;
  this.handle = null;
  
  this.attachEvent = function(eventName, handler) {
    if (this.element.attachEvent) {
      this.element.attachEvent("on" + eventName, handler);
    }
    else {
      this.element.addEventListener(eventName , handler, false);
    }
  };

  this.handleKeyPress = function(e) {
    var keyCode = document.all ? e.keyCode : e.which;
    
    if (keyCode == 13 && this.element.onchange) {
      this.element.onchange();
      return true;
    }
    
    if (keyCode >= 32) {
      if (this.element.onchange) {
        this.onchange = this.element.onchange;
        this.element.onchange = null;
      }
      
      if (97 <= keyCode && keyCode <= 122) {
        keyCode -= 32;
      }
      
      this.text += String.fromCharCode(keyCode);
      var len = this.text.length;

      for (var i = 0; i < this.element.options.length; ++i) {
        var optionText = this.element.options[i].text.toUpperCase().substr(0, len);
        
        if (optionText == this.text) {
          this.index = i;
          break;
        }
      }
    }

    var target = this;
    setTimeout(function () { target.setIndex(); }, 1);
    return false;
  };

  this.reset = function() {
    this.text = "";
    this.index = -1;
    this.handle = null;
  };
  
  this.setIndex = function() {
    if (this.handle != null) {
      clearTimeout(this.handle);
      this.handle = null;
    }

    if (this.index > -1) {
      this.element.selectedIndex = this.index;
    }
    
    if (this.onchange) {
      this.element.onchange = this.onchange;
      this.onchange = null;
    }

    if (this.index > -1) {
      var target = this;
      this.handle = setTimeout(function () { target.reset(); }, 1000);
    }
  };
  
  var controller = this;
  this.attachEvent("keypress", function (e) { controller.handleKeyPress(e); });
  
  this.element.controller = controller;
  return this.element;
}
