﻿MSDImages.AutoCompleteComboBox = Ext.extend(Ext.form.ComboBox, {

    triggerMode: 'search',

    initComponent: function() {
        Ext.apply(this, {
            mode: 'remote',
            displayField: 'name',
            valueField: 'name',
            emptyText: "Start typing and select from list",
            forceSelection: false,
            minChars: 1,
            maxLength: 100,
            triggerClass: 'x-form-' + this.triggerMode + '-trigger',
            editable: true,
            maxHeight: 200,
            queryDelay: 1000,
            listWidth: 320,
            width:200,
            	allowBlank: false,
            tpl: new Ext.XTemplate('<tpl for="."><div class="x-combo-list-item">{[this.high(values.name)]} {[this.high(values.count)]}</div></tpl>', {
                ownerId: this.id,
                high: function(str) {
                    return str.replace(new RegExp('(' + Ext.fly(this.ownerId).getValue() + ')', 'i'), '<em>$1</em>');
                }
            })
        });

        this.store = new Ext.data.Store({
            proxy: new Ext.data.HttpProxy(
					new Ext.data.Connection({
					    url: this.url,
					    disableCaching: false,
					    method: 'GET'
					})),
            queryParam: 'query',
            reader: new Ext.data.JsonReader({
                fields: [
				    { name: 'name' },
				    { name: 'count' }
				    ]
            })
        });
        MSDImages.AutoCompleteComboBox.superclass.initComponent.apply(this, arguments);

    },

    /* return querystring value for lib-search*/
    getQSValue: function() {
        var val = Images.Search.AutoCompleteComboBox.superclass.getValue.call(this);
        var raw = this.getRawValue();
        if (raw === '') {
            return '';
        }
        else {
            return String.format(this.qsFormat, (val === raw) ? 'val' : 'phr', encodeURIComponent(raw));
        }
    },

    initEvents: function() {
        Ext.form.ComboBox.superclass.initEvents.call(this);

        this.keyNav = new Ext.KeyNav(this.el, {
            "up": function(e) {
                this.inKeyMode = true;
                this.selectPrev();
            },

            "down": function(e) {
                if (!this.isExpanded()) {
                    this.onTriggerClick();
                } else {
                    this.inKeyMode = true;
                    this.selectNext();
                }
            },

            "enter": function(e) {
                if (this.inKeyMode) {
                    this.onViewClick();
                    this.delayedCheck = true;
                    this.unsetDelayCheck.defer(10, this);
                }
                else {
                    this.collapse();
                }
                Ext.getCmp('btnSearch').handler();

            },

            "esc": function(e) {
                this.collapse();
            },

            "tab": function(e) {
                this.onViewClick(false);
                return true;
            },
            scope: this,
            doRelay: function(foo, bar, hname) {
                if (hname == 'down' || this.scope.isExpanded()) {
                    return Ext.KeyNav.prototype.doRelay.apply(this, arguments);
                }
                return true;
            },
            forceKeyDown: true
        });

        this.queryDelay = 100;
        this.dqTask = new Ext.util.DelayedTask(this.initQuery, this);
        if (this.typeAhead) {
            this.taTask = new Ext.util.DelayedTask(this.onTypeAhead, this);
        }
        if (this.editable !== false) {
            this.el.on("keyup", this.onKeyUp, this);
        }
        if (this.forceSelection) {
            this.on('blur', this.doForce, this);
        }
    },

    onTriggerClick: function() {
    if (this.triggerClass == 'x-form-search-trigger') {
            MSDImages.Utils.OpenWindow('/Tag/Index', 'Full disease listing', 300, 300, this);
        }
        else {
            this.onTriggerClick();
        }
    },

    select: function(index, scrollIntoView) {
        this.selectedIndex = index;
        this.view.select(index);

        var newVal = this.store.getAt(index).data[this.displayField];
        this.setValue(newVal);

        if (scrollIntoView !== false) {
            var el = this.view.getNode(index);
            if (el) {
                this.innerList.scrollChildIntoView(el, false);
            }
        }
    },

    onLoad: function() {
        if (!this.hasFocus) {
            return;
        }
        if (this.store.getCount() > 0) {
            this.expand();
            this.restrictHeight();
            if (this.lastQuery == this.allQuery) {
                if (this.editable) {
                    this.el.dom.select();
                }
                if (!this.selectByValue(this.value, true)) {
                    //this.select(0, true);
                }
            } else {
                //this.selectNext();
                if (this.typeAhead && this.lastKey != Ext.EventObject.BACKSPACE && this.lastKey != Ext.EventObject.DELETE) {
                    this.taTask.delay(this.typeAheadDelay);
                }
            }
        } else {
            this.onEmptyResults();
        }
        //this.el.focus();
    }

});
