fcf.module({
  name: "fcfControls:templates/select+menu.wrapper.js",
  dependencies: ["fcf:NClient/Wrapper.js"],
  module: function(Wrapper){
    return class WrapperEx extends Wrapper{

      constructor(a_initializeOptions){
        super(a_initializeOptions);
        this._cbClose = undefined;
      }

      attach(){
        var self = this;
        if (this.getArg("display") != "none")
          document.addEventListener("click", ()=>{self.close();}, {once: true});
        return super.attach();
      }

      close(){ 
        document.removeEventListener("click", this.close);
        this.setArg("display", "none");
      }

      onArgDisplay(a_value){
        if (a_value === "none")
          this.emit("close");
        this.update();
      }

      onItem(a_event){
        var value = a_event.target.getAttribute("value");
        this.emit("change", {value: value});
        this.close();
      }


      onKeyDown(a_event){
        // a_event.preventDefault();
        // a_event.stopPropagation();
        // if (a_event.keyCode == 40)
        //   this.onDown();
        // else if (a_event.keyCode == 38) 
        //   this.onUp();
      }

      onUp(){
        var activeElements = this.select("[name=item].active");
        fcf.each(activeElements, function(k, el){
          el.classList.remove("active");
        });

        var el = fcf.first(activeElements).previousElementSibling;
        if (el)
          this._setActiveElement(el);
        else
          this._setActiveElement(fcf.first(this.select("[name=item]")));
      }

      onDown(){
        var activeElements = this.select("[name=item].active");
        fcf.each(activeElements, function(k, el){
          el.classList.remove("active");
        });

        if (fcf.empty(activeElements)){
          var el = fcf.first(this.select("[name=item]"));
          if (el)
            el.classList.add("active");
        } else {
          var el = fcf.first(activeElements).nextElementSibling;
          if (el)
            this._setActiveElement(el);
          else
            this._setActiveElement(fcf.first(activeElements));
        }
      }

      _setActiveElement(a_element){
        if (!a_element)
          return;
        a_element.classList.add("active");
        var offset = a_element.getBoundingClientRect().top - this.getActionDomElement().getBoundingClientRect().top;
        this.getActionDomElement().scrollTo(0, offset);
      }
    }
  }
});
