/*!
 * Goodar
 * @author    Vyacheslav Voronchuk
 * @date      25.12.2009 
 * Copyright(c) 2009, by Vyacheslav Voronchuk
 */

Goodar.form.select = Ext.extend(Ext.util.Observable, {
  
  tag: 'div', 
  cls: 'sf',
  width: 180,
  style: 'display: none; position: relative; top: 2px; left: 10px; z-index: 1000;',
  html: '', 
  
  constructor: function(config)
  {
    for(value in config)
      this[value] = config[value];
    
    this.el = Ext.get(this.fieldId + '_label');
    if(Ext.fly(this.fieldId + '_trigger'))
      this.elTrigger = Ext.get(this.fieldId + '_trigger');
     
    if(!config.template)
      this.template = new Ext.Template('<li class="selector-' + this.id + '" id="select-' + this.id + '-item-{value}">{name}</li>');

    this.addEvents('select');
    
    Goodar.form.select.superclass.constructor.call(this);
    
    var aCoords = Ext.fly(this.fieldId).getXY();
    this.el.on('click', function(oItem) {
      this.toggle();
    }, this);   
    if(this.elTrigger)
    {
      this.elTrigger.on('click', function(oItem) {
        this.toggle();
      }, this); 
    }

    if(!config.contanier)
    {
      this.contanier = Ext.DomHelper.insertAfter(this.elTrigger ? this.elTrigger : this.el, 
      {
        tag: this.tag, 
        cls: this.cls,
        style: this.style + 'width: ' + this.width + 'px;',
        html: this.html, 
        
        children:
        [
          {tag: 'ul', id: 'select-' + this.id, html: ''},
          {tag: 'div', style: 'width: ' + this.width + 'px;', cls: 'bottom', html: '<div style="padding: 0" class="ll"></div><div style="padding: 0;' + 'width: ' + (this.width - 30) + 'px;height: 12px;" class="cc"></div><div class="rr">'}
        ]
      });  
    }
        
    Ext.each(this.data, function(item) {
      this.template.append('select-' + this.id, item);
    }, this);
    
    Ext.select('li.selector-' + this.id).on('click', function(oItem) {
      var value = oItem.target.id.split(/\-/)[3];
      document.getElementById(this.fieldId + '_label').value = oItem.target.innerHTML;
      document.getElementById(this.fieldId).value = value;
      this.hide();
      this.fireEvent('select', this, value);
    }, this); 
    
    Goodar.Manager.addCmp(this.id, this);
  },

  hide: function()
  {
    this.contanier.style.display = 'none';
  },
  
  show: function()
  {
    this.contanier.style.display = '';
  },
  
  toggle: function()
  {
    if(this.contanier.style.display === 'none')
      this.show();
    else
      this.hide();
  }
});