Ext.namespace('Ext.ux');


Ext.ux.ClearableSearchField = function(config) {
    Ext.applyIf(config, {
		validationEvent:false,
	    emptyText: 'Suchbegriff',
	    validateOnBlur:false,
	    trigger1Class:'x-form-clear-trigger',
	    trigger2Class:'x-form-search-trigger',
		trigger1Qtip: "Suchbegriff zurücksetzen",
		loadingText: '',
	    hideTrigger1:true,
		hideTrigger2: false,
	    width:180,
	    hasSearch : false,
	    paramName : 'suche',
		displayField: 'value',
		queryDelay: 250,
		searchCallback: Ext.emptyFn,
		scope: this,
		mode: 'local',
		store: new Ext.data.JsonStore({
			url: '/cms/json/',
			baseParams: {
				key: 'searchstrings'
			},
			fields: ['value'],
			root: 'matches'
		})
	});	
	
    Ext.ux.ClearableSearchField.superclass.constructor.call(this, config);
	this.triggerConfig = {
       tag:'span', cls:'x-form-twin-triggers', style:'padding-right:2px',  // padding needed to prevent IE from clipping 2nd trigger button
       cn:[{tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + config.trigger1Class, style:config.hideTrigger1?"display:none":"", "ext:qtip": (this.trigger1Qtip?this.trigger1Qtip:"")},
           {tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + config.trigger2Class, style: config.hideTrigger2?"display:none":""}
    ]};
};

Ext.extend(Ext.ux.ClearableSearchField, Ext.form.ComboBox, {
	setValue: function(val) {
		Ext.ux.ClearableSearchField.superclass.setValue.call(this, val);
		if (this.triggers) {
			this.triggers[0].show();
		}
	},
	initTrigger : function(){
        var ts = this.trigger.select('.x-form-trigger', true);
        this.wrap.setStyle('overflow', 'hidden');
        var triggerField = this;
        ts.each(function(t, all, index){
            t.hide = function(){
                var w = triggerField.wrap.getWidth();
                this.dom.style.display = 'none';
                triggerField.el.setWidth(w-triggerField.trigger.getWidth());
            };
            t.show = function(){
                var w = triggerField.wrap.getWidth();
                this.dom.style.display = '';
                triggerField.el.setWidth(w-triggerField.trigger.getWidth());
            };
            var triggerIndex = 'Trigger'+(index+1);

            if(this['hide'+triggerIndex]){
                t.dom.style.display = 'none';
            }
            t.on("click", this['on'+triggerIndex+'Click'], this, {preventDefault:true});
            t.addClassOnOver('x-form-trigger-over');
            t.addClassOnClick('x-form-trigger-click');
        }, this);
        this.triggers = ts.elements;
    },
    initComponent : function(){
        Ext.ux.ClearableSearchField.superclass.initComponent.call(this);
        this.on('specialkey', function(f, e){
            if(e.getKey() == e.ENTER){
                this.onTrigger2Click();
            }
        }, this);
		
		/*this.on('focus', function(f, e) {
			this.showHistory();
		}, this);*/
		
		this.historyRecords = [];
		this.dqTask = new Ext.util.DelayedTask(this.initQuery, this);
    },
	showHistory: function() {
		if (this.getRawValue() == '' && this.list) {
			this.expand();
		}
	},
    onTrigger1Click : function(){
        this.clearValue();
        this.triggers[0].hide();
        this.hasSearch = false;
    },

    onTrigger2Click : function(){
        var v = this.getRawValue();
        if(v.length < 2){
            this.onTrigger1Click();
			this.searchCallback.call(this.scope, this, this.getRawValue());
            return;
        }
		if (this.store && this.store.findExact('value', v) == -1) {
			this.store.insert(0, [new Ext.data.Record({
				value: v
			})]);
			this.historyRecords.push(new Ext.data.Record({
				value: v
			}));
		}
		this.searchCallback.call(this.scope, this, this.getRawValue());
     
        this.hasSearch = true;
        this.triggers[0].show();
    },
	doQuery : function(q, forceAll){
		if (this.store) {
	        q = Ext.isEmpty(q) ? '' : q;
	        var qe = {
	            query: q,
	            forceAll: forceAll,
	            combo: this,
	            cancel:false
	        };
	        if(this.fireEvent('beforequery', qe)===false || qe.cancel){
	            return false;
	        }
	        q = qe.query;
	        forceAll = qe.forceAll;
	        if(forceAll === true || (q.length >= this.minChars)){
	            if(this.lastQuery !== q){
	                this.lastQuery = q;
	                
	                this.store.baseParams[this.queryParam] = q;
	                this.store.load({
	                    params: this.getParams(q),
						scope: this,
						callback: function() {
							if (this.historyRecords.length) {
								this.store.add(this.historyRecords);
							}
							this.store.filter(this.displayField, this.createValueMatcher(q), true);
						}
	                });
	                //this.expand();
	            }else{
	                this.selectedIndex = -1;
	                this.onLoad();
	            }
	        }
		}
    },
	
	anyMatch: true,
	caseSensitive: false,
	createValueMatcher: function(value) {
		if(Ext.isEmpty(value, false)){
			return new RegExp('^');
		}
		value = Ext.escapeRe(String(value));
		return new RegExp((this.anyMatch === true ? '' : '^') + '(' + value + ')', this.caseSensitive ? '' : 'i');
	},
	prepareData : function(data) {
		var result = Ext.apply({}, data);
		result[this.displayField] = data[this.displayField].replace(this.createValueMatcher(this.getRawValue()), function(a, b){
			if (typeof b != 'string') {
				return '';
			}
			return '<span class="mark-combo-match">' + b + '</span>'
		});
		return result;
	},
	initList : function(){
		Ext.ux.ClearableSearchField.superclass.initList.apply(this, arguments);
		this.view.prepareData = this.prepareData.createDelegate(this);
	}
});

