// Gaia Ajax Copyright (C) 2008 - 2009 Gaiaware AS. details at http://gaiaware.net/

/* 
 * Gaia Ajax - Ajax Control Library for ASP.NET
 * Copyright (C) 2008 - 2009 Gaiaware AS
 * All rights reserved.
 * This program is distributed under either GPL version 3 
 * as published by the Free Software Foundation or the
 * Gaia Commercial License version 1 as published by
 * Gaiaware AS
 * read the details at http://gaiaware.net
 */

/* ---------------------------------------------------------------------------
   Class basically wrapping the ListControl class
   --------------------------------------------------------------------------- */
Gaia.ListControl = function() {}

Gaia.ListControl.prototype = {

  clear: function() {
    this.element.options.length = 0;
    
    return this;
  },

  add: function(position, item) {
    return this._add(position, item);
  },
  
  remove : function(position) {
    this.element.remove(position);
    return this;
  },
  
  change : function(position, item) {
    return this._change(position, item);
  },
  
  setAutoPostBack: function(value) {
    
    if (value) {
        if (this._subscribedEvents == null) {
            this.observe('change');
        }
    } else {
        if( this._subscribedEvents ) {
          for( var idx = 0, length = this._subscribedEvents.length; idx < length ; ++idx ) {
            var evt = this._subscribedEvents[idx];
            Element.stopObserving(this.element, evt.name, evt.evt);
          }
          
          delete this._subscribedEvents;
        }
    }
    
    return this;
  },
  
  _add: function(position, item) {
    var options = this.element.options;
    var option = new Option(item.text, item.value, false, item.selected);
    if (position < options.length) {
        this.element.add(option, Prototype.Browser.IE ? position : options[position]);
    } else {
        options[position] = option;
    }
    return this;
  },
  
  _change: function(position, item) {
    var option = this.element.options[position];
    if (item.text != null)
        option.text = item.text;
    if (item.value != null)
        option.value = item.value;
    if (item.selected != null) {
        option.selected = item.selected;
        if (!item.selected && !this.element.multiple && Prototype.Browser.IE && this.element.selectedIndex === position)
          this.element.selectedIndex = -1;
    }
    return this;
  }
}

Gaia.ListControl.browserFinishedLoading = true;
