/**
  * @class Ext.ux.LocationCombo
  * @extends Ext.form.ComboBox
  * @author Dan Cosser
  * 12th May 2009
  * @constructor
  */

Ext.ux.LocationCombo = Ext.extend(Ext.form.ComboBox,  {
	tpl: new Ext.XTemplate(
			'<tpl for="."><div class="search-item">',
				'<span>{displayTerm}</span>',
			'</div></tpl>'
		),

	store: new Ext.data.Store({
		proxy: new Ext.data.JsonRpcProxy(IcmRpcClient().locationLookup.checkLocation),
		reader: new Ext.data.JsonReader({},[{name: 'displayTerm'}, {name: 'valueTerm'}])
	}),

	typeAhead: false,
	forceSelection: false,
	hideTrigger: true, 
	cls: 'location-combo',
	triggerClass: 'location-trigger',
	loadingText: 'Searching...',
	itemSelector: 'div.search-item',
	displayField: 'displayTerm',
	valueField: 'valueTerm',
	minChars: 3,
	queryDelay: 100,
	enableKeyEvents: true,
	listeners: {
		"blur": function(){
			//if user has blanked input then blank the ext stored value
			if(this.getRawValue()==null || this.getRawValue()==''){
				this.setValue('');
			}
			//check for postcode outcode in input as ajax will not be triggered if < 3 characters (e.g. W1)
			else if(this.getRawValue().toUpperCase().search(/^[A-PR-UWYZ](([0-9][A-HJKS-UW0-9]?)|([A-HK-Y][0-9][ABEHMNPRVWXY0-9]?))$/) > -1){
				this.setValue(this.getRawValue());
			}
			else if (this.getRawValue().length > 0) {
				this.setValue(this.getRawValue());
			}
		},
		"keypress": function(){
			// Make sure the value actually gets set (an annoyance with Ext combo boxes)
			this.setValue(this.getRawValue());
		}
	}
});

/**
 * @class Ext.ux.PostcodeCombo
 * @extends Ext.form.ComboBox
 * @author Dan Cosser
 * 12th May 2009
 * @constructor
 * @param {Object} config Configuration options
 */

Ext.ux.PostcodeCombo = Ext.extend(Ext.form.ComboBox,  {
	tpl: new Ext.XTemplate(
			'<tpl for="."><div class="search-item">',
				'<span>{unit}</span>',
			'</div></tpl>'
		),

	store: new Ext.data.Store({
		proxy: new Ext.data.JsonRpcProxy(IcmRpcClient().locationLookup.checkPostCode),
		reader: new Ext.data.JsonReader({},[{name:'unit'}])
	}),

	typeAhead: true,
	forceSelection: true,
	hideTrigger: true, 
	loadingText: 'Searching...',
	itemSelector: 'div.search-item',
	displayField: 'unit',
	valueField: 'unit',
	minChars: 3,
	queryDelay: 100,
	listeners: {"blur": function(){
			if(this.getRawValue()==null || this.getRawValue()==''){
				this.setValue('');
			}
		}
	}
});

//fix to stop whole combobox field disappearing in ie due to hideTrigger: true
Ext.form.TriggerField.override({
    afterRender : function(){
        Ext.form.TriggerField.superclass.afterRender.call(this);
        var y;
        if(Ext.isIE && !this.hideTrigger && this.el.getY() != (y = this.trigger.getY())){
            this.el.position();
            this.el.setY(y);
        }
    }
});

Ext.reg('locationcombo', Ext.ux.LocationCombo);
Ext.reg('postcodecombo', Ext.ux.PostcodeCombo);