Ext.onReady(function(){

Ext.namespace("Ext.ux.DefaultingComboBox");

Ext.ux.DefaultingComboBox = function(config) {
    Ext.ux.DefaultingComboBox.superclass.constructor.call(this, config);
};

Ext.extend(Ext.ux.DefaultingComboBox, Ext.form.ComboBox, {
setValue: function(v) {
  // If the ComboBox hasn't been loaded yet, load it asynchronously
  // before setting the value.
  if (v && !this.disabled && this.store.getCount() == 0) {
      this.store.on("load", function () {
         Ext.ux.DefaultingComboBox.superclass.setValue.call(this, v);
      }, this, {single: true});
      this.doQuery(this.allQuery, true);
  } else {
      Ext.ux.DefaultingComboBox.superclass.setValue.call(this, v);
  }
},
initComponent: function(){
  Ext.form.ComboBox.superclass.initComponent.call(this);
  this.addEvents(
      'expand',
      'collapse',
      'beforeselect',
      'select',
      'beforequery'
  );
  if(this.transform){
      this.allowDomMove = false;
      var s = Ext.getDom(this.transform);
      if(!this.hiddenName){
          this.hiddenName = s.name;
      }
      if(!this.store){
          this.mode = 'local';
          var d = [], opts = s.options;
          for(var i = 0, len = opts.length;i < len; i++){
              var o = opts[i];
              var value = (Ext.isIE ? o.getAttributeNode('value').specified : o.hasAttribute('value')) ? o.value : o.text;
              if(o.selected) {
                  this.value = value;
              }
              d.push([value, o.text]);
          }
          this.store = new Ext.data.SimpleStore({
              'id': 0,
              fields: ['value', 'text'],
              data : d
          });
          this.valueField = 'value';
          this.displayField = 'text';
      }
      s.name = Ext.id(); // wipe out the name in case somewhere else they have a reference
      if(s.value) // DefaultingComboBox (FIX)
        this.value = s.value; // setting default value, now for input type='text'
      if(!this.lazyRender){
          this.target = true;
          this.el = Ext.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate);
          Ext.removeNode(s); // remove it
          this.render(this.el.parentNode);
      }else{
          Ext.removeNode(s); // remove it
      }
  }
  this.selectedIndex = -1;
  if(this.mode == 'local'){
      if(this.initialConfig.queryDelay === undefined){
          this.queryDelay = 10;
      }
      if(this.initialConfig.minChars === undefined){
          this.minChars = 0;
      }
  }
}
});

var dataRecord = new Ext.data.Record.create([
   { name: 'v', type: 'int' },
   { name: 'n', type: 'string' }
]);

var countryJReader = new Ext.data.JsonReader({
                     totalProperty: 'countryCount',
                     root: 'data'}, dataRecord);

var cityJReader = new Ext.data.JsonReader({
                     totalProperty: 'cityCount',
                     root: 'data'}, dataRecord);

var countryStore = new Ext.data.Store({
  proxy: new Ext.data.HttpProxy({url: '/utils/json_countries_options', disableCaching:false, method: 'GET'}),
  reader: countryJReader,
  autoLoad: true
});

var cityStore = new Ext.data.Store({
  proxy: new Ext.data.HttpProxy({url: '/utils/json_cities_options', disableCaching:false, method: 'GET'}),
  reader: cityJReader
});

var country_combo = new Ext.ux.DefaultingComboBox ({
   fieldLabel:'Country',
   emptyText:'Select Country...',
   displayField:'n',
   valueField:'v',
   editable: true, //false,
   id:'country_id',
   transform:'country_id',
   //renderTo:'country_id',
   store: countryStore,
   triggerAction:'all',
   mode:'local',
   listeners:{
     select:{fn:function(combo, value) {
        var cityCmp = Ext.getCmp('city_id');
        cityCmp.setValue('');
        cityCmp.setDisabled(false);
        cityCmp.store.baseParams = { id: combo.getValue(), cid: '' };
        cityCmp.store.reload();
     }}
   }
});

var city_combo = new Ext.ux.DefaultingComboBox ({
  fieldLabel:'City',
  emptyText:'Select City...',
  autocomplete: 'on',
  minChars: 1,
  displayField:'n',
  valueField:'v',
  id:'city_id',
  transform:'city_id',
  //renderTo:'city_id',
  store: cityStore,
  triggerAction:'all',
  autoHeight: true,
  listeners:{
    beforerender:{fn:function(e) {
      var countryCmp = Ext.getCmp('country_id');
      var country_value = countryCmp.getValue();
      if(country_value)
        e.setDisabled(false);
      else
        e.setDisabled(true);
    }},
    beforequery:{fn:function(e) {
      var countryCmp = Ext.getCmp('country_id');
      if(!e.combo.defaultValueLoaded && e.combo.getValue())
      {
        var extraParams = { id: countryCmp.getValue(), cid: e.combo.getValue() };
        e.combo.defaultValueLoaded = true;
      }
      else
      {
        var extraParams = { id: countryCmp.getValue(), cid: '' };
      }

      e.combo.store.baseParams = extraParams;
      return 1;
    }}
  }
});

});

function getVarValueFromURL(url, varName) {
	var query = url.substring(url.indexOf('?') + 1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		if (pair[0] == varName) {
			return pair[1];
		}
	}
	return 'ru';
}

function selectCounrtyLocale(locale)
{
	var arr = new Array();

    arr['ru'] = 'Выберете страну';
    arr['en'] = 'Select Country';
    arr['de'] = 'Wählen Sie Land';
    arr['fr'] = 'Choisissez votre pays';

    return arr[ locale ];
}

function selectCityLocale(locale)
{
	var arr = new Array();

    arr['ru'] = 'Выберете город';
    arr['en'] = 'Select City';
    arr['de'] = 'Wählen Sie Stadt';
    arr['fr'] = 'Choisissez votre ville';

    return arr[ locale ];
}
