/*
 * jQuery UI Select box 1.0.1
 *
 * Created by Negru Nicolae Marian (marian.negru@gmail.com)
 * Modified by Edward Leigh (edward@visualconnections.com)
 *
 * Depends:
 *   ui.core.js
 */
(function($) {
    if ($.browser.mozilla) {
        $.fn.disableTextSelect = function() {
            return this.each(function() {
                $(this).css({
                    'MozUserSelect' : 'none'
                });
            });
        };
    } else if ($.browser.msie) {
        $.fn.disableTextSelect = function() {
            return this.each(function() {
                $(this).bind('selectstart', function() {
                    return false;
                });
            });
        };
    } else {
        $.fn.disableTextSelect = function() {
            return this.each(function() {
                $(this).mousedown(function() {
                    return false;
                });
            });
        };
    }
$.SelectManager = {};
$.SelectManagerIndex = 0;
$.widget("ui.select", {

  version: "1.0.1",
  options: {
    scope: ''
  },
  
  _create: function() {
    var self = this;
    this.inFocus = false;
    this.element.hide();

    this.index = $.SelectManagerIndex++;
    $.SelectManager[this.index] = this.element;
    var width = this.options.width || this.element.outerWidth();

    this.input = $('<input />')
      .attr("type", "text")
      .addClass("ui-select")
      .attr("autocomplete", "off")
      .attr("readonly", "readonly")
      .attr("tabindex", this.element.attr("tabindex"))
      .insertBefore(this.element)
      .focus()
      .width(width)
      .click(function(e){
        if(!self.inFocus) {
          self._toggle();
        }
        else {
          self.inFocus = false;
        }
        e.stopPropagation();
        return false;
      })
      .focus(function(e){
        self.inFocus = true;
        self._show();
        e.stopPropagation();
      })
      .keydown(function(event) {     
        switch(event.keyCode) {
          case 38: // up
            event.preventDefault();
            self._show();
            self._select(-1);
            break;
          case 40: // down
            event.preventDefault();
            self._show();
            self._select(1);
            break;
          //case 9:  // tab 
          case 13: // return
            event.preventDefault(); // seems not working in mac !
            self._setOption('value', jQuery('.ui-select-selected', self.container).attr('id'));
            self._hide();
            break;
        }
        
      })
      .blur(function(e) {
        if (!(self.container.is(':visible') && self.hasfocus > 0 )) {
          if((jQuery.browser.msie || jQuery.browser.safari || jQuery.browser.opera)) {
            //if($(document.activeElement).hasClass('ui-select-wrapper')) {
            if(self.isHover == 1) {
              self.input.focus();
              return;
            }
          }
          self._hide();  
        }
      });

    //this.input.disableTextSelect();
    this.hideHandle = function(){self._hide();};
    $('body').click(this.hideHandle);
    this.element.bind('hideEvent', this.hideHandle);
    var scope = this.options.scope ? ' class="' + this.options.scope + '" ' : "";
    var span = this.input.wrap('<span' + scope + ' style="cursor:pointer;display:inline-block;"></span>').parent();

    this.input.wrap('<div class="ui-select-left"><div class="ui-select-right"><div class="ui-select-middle" style="position:relative;"></div></div></div>');
    if(jQuery.browser.opera) {
    this.input.parent().parent().click(function(e){
        if(!self.inFocus) {
          self._toggle();
        }
        else {
          self.inFocus = false;
        }
        e.stopPropagation();
        return false;
      });
    }
    this.input.parent().height(this.input.outerHeight());
    
    this.container = $('<div class="ui-select-wrapper" style="position:absolute"></div>').insertAfter(this.input).hide().
      hover(function() {self.isHover = 1;}, function() {self.isHover = -1;});
    
    var list = $('<ul></ul>').appendTo(this.container);
    
    this.element.children('option').each(function(index) {
      var opt = $(this);
      var li = $('<li></li>').appendTo(list).html(opt.html())
        .attr("id", opt.val() || "v_"+index)
        .hover(
          function() {
            self.hasfocus = 1;
            $(this).addClass('ui-select-hover');
          },
          function() {
            self.hasfocus = -1;
            $(this).removeClass('ui-select-hover');
          }
        ) 
        .click(function(event) {
          $("li", self.container).removeClass("ui-select-selected"); // remove selected
          $(this).addClass("ui-select-selected");
          self._setOption('value', $(this).attr('id'));
          self._hide();
          return false;
        });
        
      if (opt.is(':selected')) {
        li.addClass("ui-select-selected");
        self.active = index;
        self._setOption('value', opt.val() || "v_"+index);
      }
    });
    
    this.container.width(width);
    
    this._refreshValue(); 
  },
  _num : function (value) {
    return parseInt(value, 10) || 0;
  },  
  _select : function(step) {
    var lis = $("li", this.container);
    if (!lis) return;

    this.active += step;

    if (this.active < 0) {
      this.active = 0;
    } else if (this.active >= lis.size()) {
      this.active = lis.size() - 1;
    }

    lis.removeClass("ui-select-selected");

    $(lis[this.active]).addClass("ui-select-selected");
  },
  _selectCurrent : function() {
    var self = this;
    var value = this._value();
    $("li", this.container).removeClass("ui-select-selected")
    .each(function(index){
      var li = $(this);
      if (li.attr('id') == value) {
        li.addClass("ui-select-selected");
        self.active = index;
      }
    });
  },
  _hide : function() {
    this.hasfocus = 0;
    this.isHover = 0;
    this.container.toggle();
    this.container.hide(); 
    
    this._selectCurrent();
  },
  
  _show : function() {
    for(var sel in $.SelectManager) {
      if($.SelectManager[sel] != null && $.SelectManager[sel] != this.element) {
        $.SelectManager[sel].trigger('hideEvent');
      }
    }
    this.container.show();
  },
  
  _toggle : function() {
    if (this.container.is(':visible')) {
      this._hide();
    }
    else {
      this._show();
    }
  },
  
  destroy: function() {

    $.SelectManager[this.index] = null;
    delete $.SelectManager[this.index];
    this.element.unbind('hideEvent', this.hideHandle);
    
    this.container.remove();
    this.input.remove();

    $.Widget.prototype.destroy.apply(this, arguments);

  },

  value: function(newValue) {
    if (newValue === undefined) {
      return this._value();
    }
    
    this._setOption('value', newValue);
    return this;
  },

  _setOption: function(key, value) {

    switch (key) {
      case 'value':
        this.options.value = value;
        this._refreshValue();
        this._trigger('change', null, {});
        break;
    }

    $.Widget.prototype._setOption.apply(this, arguments);
  },

  _value: function() {
    return this.options.value;
  },

  _refreshValue: function() {
    var value = this.value();
    this.element.val(value);
    this.input.val($('#' + value, this.container).html());
  }
});


})(jQuery);

