Ext.namespace('Ext.ux');

Ext.ux.SelectUpdater = Ext.extend(Object, {
  // default config
  config: {
    sourceElement: 'full_filters_ele_category_id',
    updateElement: 'full_filters_ele_subcategory_id',
    updateUrl: '/recepty/updatesubcategory',
    updateParamName: 'param',
    ajaxLoaderImg: '/images/spinner.gif',
    updateDefaultParams: {}
  },
  
  // constructor
  constructor: function (config) {
    Ext.apply(this.config, config);
    this.initialize();
  },
  
  initialize: function() {
    this.sourceElement = Ext.get(this.config.sourceElement);
    this.updateElement = Ext.get(this.config.updateElement);
    this.sourceElement.on('change', this.handleChange, this);
    this.ajaxLoader = Ext.DomHelper.insertAfter(this.updateElement, {tag: 'img', src: this.config.ajaxLoaderImg, style: 'position:absolute;margin-top:2px;display:none'}, true);
    this.connection = new Ext.data.Connection({
      url: this.config.updateUrl
    });
  },
  
  updateSelect: function(content) {
    // must remove the element and insert new select (IE does not allow to update content of select tag)
    this.updateElement = this.updateElement.replaceWith({
      tag: 'select',
      id: this.updateElement.id,
      name: this.updateElement.getAttribute('name'),
      cls: this.updateElement.getAttribute('class'),
      html: content
    });
  },
  
  handleChange: function () {
    // display loader img
    this.ajaxLoader.show();
    
    // params to send
    var param = this.config.updateDefaultParams;
    param[this.config.updateParamName] = this.sourceElement.getValue();
    
    // make request
    this.connection.request({
      params: param,
      success: this.handleSuccess.createDelegate(this),
      failure: this.handleError.createDelegate(this)
    });
    
  },
  
  handleSuccess: function (response) {
    this.updateSelect(response.responseText)
    this.ajaxLoader.hide();
  },
  
  handleError: function (response) {
    alert('Error');
  }
});
