var linkMenuButton;
var linkMenu;
var linkMenuShow = true;

Ext.onReady(function(){
    if (!getObj('searchForm')){
        return;
    }
    var ds = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: 'index.php?act=company&hdl=quick_search',
            method : 'GET'
        }),
        reader: new Ext.data.JsonReader({
            root: 'rows',
            totalProperty: 'total',
            id: 'comp_id'
        }, [
            {name: 'exchange', mapping: 'exchange'},
            {name: 'sexchange', mapping: 'sexchange'},
            {name: 'ticker', mapping: 'ticker'},
            {name: 'user_id', mapping: 'user_id'},
            {name: 'type_', mapping: 'type_'},
            {name: 'conf_status', mapping: 'conf_status'},
            {name: 'company_name', mapping: 'company_name'},
            {name: 'company_url_name', mapping: 'company_url_name'},
            {name: 'query', mapping: 'query'}
        ])
    });

    // Custom rendering Template
    var resultTpl;

    var search = new Ext.form.ComboBox({
        store: ds,
        minChars : 1,
        displayField:'title',
        typeAhead: false,
        loadingText: 'Searching...',
        listWidth : 340,
        listAlign : 'tr-br',
        queryDelay: 100,
        pageSize:0,
        hideTrigger:true,
        tpl: resultTpl,
        applyTo: 'searchForm',
        itemSelector: 'tr.search-item',
        onRender : function(ct, position){
            Ext.form.Field.superclass.onRender.call(this, ct, position);
            if(!this.el){
                var cfg = this.getAutoCreate();
                if(!cfg.name){
                    cfg.name = this.name || this.id;
                }
                if(this.inputType){
                    cfg.type = this.inputType;
                }
                this.el = ct.createChild(cfg, position);
            }
            if(this.readOnly){
                this.el.dom.readOnly = true;
            }
            if(this.tabIndex !== undefined){
                this.el.dom.setAttribute('tabIndex', this.tabIndex);
            }

            this.wrap = this.el.wrap({cls: "x-form-field-wrap"});
            this.trigger = this.wrap.createChild(this.triggerConfig ||
                    {tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.triggerClass});
            if(this.hideTrigger){
                this.trigger.setDisplayed(false);
            }
            this.initTrigger();
            if(this.hiddenName){
                this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName,
                        id: (this.hiddenId||this.hiddenName)}, 'before', true);

                // prevent input submission
                this.el.dom.removeAttribute('name');
            }
            if(Ext.isGecko){
                this.el.dom.setAttribute('autocomplete', 'off');
            }

            if(!this.lazyInit){
                this.initList();
            }else{
                this.on('focus', this.initList, this, {single: true});
            }

            if(!this.editable){
                this.editable = true;
                this.setEditable(false);
            }
        },
        restrictHeight : function(){
            this.innerList.dom.style.height = '';
            var inner = this.innerList.dom;
            var pad = this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight;
            var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
            var ha = this.getPosition()[1]-Ext.getBody().getScroll().top;
            var hb = Ext.lib.Dom.getViewHeight()-ha-this.getSize().height;
            var space = Math.max(ha, hb, this.minHeight || 0)-this.list.shadowOffset-pad-5;
            h = Math.min(h, space, this.maxHeight);

            this.innerList.setHeight(h);
            this.list.beginUpdate();
            this.list.setHeight(h+pad);
            var alignX = 18;
            var alignY = 3;
            if (Ext.isIE8){
                alignY = 6;
            }else if (Ext.isIE){
                alignY = 1;
            }else if (Ext.isChrome){
                alignX = 35;
            }
            this.list.alignTo(this.wrap, this.listAlign, [alignX, alignY]);
            this.list.endUpdate();
        },
        expand : function(){
            if(this.isExpanded() || !this.hasFocus){
                return;
            }
            var alignX = 18;
            var alignY = 3;
            if (Ext.isIE8){
                alignY = 6;
            }else if (Ext.isIE){
                alignY = 1;
            }else if (Ext.isChrome){
                alignX = 35;
            }
            this.list.alignTo(this.wrap, this.listAlign, [alignX, alignY]);
            this.list.show();
            this.innerList.setOverflow('auto'); // necessary for FF 2.0/Mac
            Ext.getDoc().on('mousewheel', this.collapseIf, this);
            Ext.getDoc().on('mousedown', this.collapseIf, this);
            this.fireEvent('expand', this);
        },
        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();
        },
        onViewClick : function(doFocus){
            var index = this.view.getSelectedIndexes()[0];
            var r = this.store.getAt(index);
            if(r){
                this.onSelect(r, index);
            }else if (this.store.getCount() == 1)
                this.onSelect(this.store.getAt(0), 0);
            else
                document.getElementById('searchAreaForm').submit();
            if(doFocus !== false){
                this.el.focus();
            }
        },
        onSelect: function(record){ // override default onSelect to do redirect
            window.location = gDefURL + record.data.company_url_name;
        }
    });
    search.on('beforequery', function(event){
        resultTpl = new Ext.XTemplate(
            '<table>',
            '<tpl for="."><tr class="search-item">',
                '<td style="width:12px;padding-right:0px;overflow:visible"><tpl if="this.isImage(type_, conf_status)">\n\
                    <img src="img/stat{[this.getStatusId(values.type_, values.conf_status)]}.gif">\n\
                </tpl></td>',
                '<td style="width:34px;padding-right:0px;">{[this.highlight(values.ticker, values.query)]}</td>',
                '<td style="width:168px;"><div style="white-space:nowrap;width:168px;overflow:hidden">{[this.companyName(values.company_name, values.query)]}</div></td>',
                '<td style="width:80px;padding-right:8px;text-align:right;font-size:10px;overflow:hidden;white-space:nowrap;"><div style="width:72px;overflow:hidden;white-space:nowrap;"><tpl if="this.notEmptyStr(exchange)">{exchange}<tpl if="this.notEmptyStr(sexchange)">, {sexchange}</tpl></tpl>',
                '<tpl if="this.notEmptyStr(exchange) == false"><tpl if="this.notEmptyStr(sexchange)">{sexchange}</tpl></tpl></div></td>',
            '</tr></tpl>',
            '</table>',
            '<div class="my-links-link" style="border:0px;"><a href="javascript:document.getElementById(\'searchAreaForm\').submit()">Show all results for "'+event.query+'"</a></div>',
            '<div class="my-links-link" style="margin:0px;">',
            'Tip: Use comma (,) to separate multiple quotes. </div>',
            {
                notEmptyStr : function (str){
                    return str > '';
                },
                companyName : function (str, query){
                    if (str.length > 35)
                        str = str.substr(0, 35) + '...';
                    return str.replace(new RegExp('('+query+')',"gi"), '<b>$1</b>');
                },
                isImage : function (type_, conf_status){
                    return ((type_ == 'C') || (conf_status == 'Y'));
                },
                getStatusId : function (type_, conf_status){
                    if ('C' == type_) {
                        if ('Y' == conf_status) return 3;
                        else return 2;
                    } else {
                        if ('Y' == conf_status) return 1;
                    }
                    return 0;
                },
                highlight : function(str, query) {
                    return str.replace(new RegExp('^('+query+')',"gi"), '<b>$1</b>');
                }
            }
        );
        this.tpl = resultTpl;
        this.view.tpl = resultTpl;
        this.list.addClass('my-links');
        this.list.setStyle('z-index', '200000');
    });
    /*
    var html = '<div id=\'quickLinksDiv\'></div>';
    var baseItem = new Ext.menu.TextItem({text : html});
    linkMenu = new Ext.menu.FieldMenu({
        minWidth : 142,
        allowOtherMenus : true,
        ignoreParentClicks : true,
        defaultAlign : 'tr-br',
        shadow : 'drop',
        firstTimeShow : true,
        menuOffset : [4, 1],
        items: [ baseItem ]
    });
    linkMenu.on('show', function(menu){
        Ext.get('quickLinksButton').removeClass('my_links');
        Ext.get('quickLinksButton').addClass('my_links_open');
        menu.getEl().addClass('my-links');
        linkMenuShow = false;
        if (!menu.firstTimeShow){
            menu.firstTimeShow =  true;
            return;
        }
        var mask = new Ext.DevxLoadMask(menu.getEl(), {
            msgCls : 'loading-indicator'
        });
        mask.show();
        var url='index.php?act=company&hdl=quick_links&user_id='+user_id;
        loader.data['onerror'] = function(){};
        loader.processGET(url, function(http){
            var res = JSON.parse(http.responseText);
            var html = '<table>';
            var have_ticker = false;
            for (var k=0; k<res['total']; k++){
                var img = 0;
                if (res['rows'][k]['type_'] == 'C'){
                    if (res['rows'][k]['conf_status'] == 'Y') img = 3;
                    else if (res['rows'][k]['conf_status'] == 'N') img = 2;
                }else if (res['rows'][k]['conf_status'] == 'Y') img = 1;
                var exchange = res['rows'][k]['sexchange'];
                if (res['rows'][k]['exchange'])
                    exchange = res['rows'][k]['exchange'] + ((res['rows'][k]['sexchange'])? ', '+res['rows'][k]['sexchange']: '');
                if (res['rows'][k]['company_name'].length > 35)
                    res['rows'][k]['company_name'] = res['rows'][k]['company_name'].substr(0, 35) + '...';
                html += '<tr class="quik_link" id="quicklink'+k+'" \n\
                        onmouseover="Ext.get(\'quicklink'+k+'\').addClass(\'x-combo-selected\');"\n\
                        onmouseout="Ext.get(\'quicklink'+k+'\').removeClass(\'x-combo-selected\');"\n\
                        onclick="window.location.href=\'index.php?act=company&hdl=view&id='+res['rows'][k]['comp_id']+'\'">\n\
                    <td style="width:30px;">'+res['rows'][k]['ticker']+'</td>\n\
                    <td style="width:215px;">'+res['rows'][k]['company_name']
                    +((img > 0)?'<img src="img/stat'+img+'.gif">' : '')+'</td>\n\
                    <td style="width:72px;padding-right:8px;text-align:right;font-size:10px;overflow:hidden;white-space:nowrap;">'+exchange+'</td>\n\
                    </tr>';
                have_ticker = have_ticker || (res['rows'][k]['ticker'] != '');
            }
            if (!have_ticker){
                var re = /<td style="width:30px;"><\/td>/gi;
                html = html.replace(re, '');
            }
            html += '</table>';
            if (res['total'] == 0) html = '<div class="no-my-links">You have not selected Quick Links</div>';
            html += '<div class="my-links-link"><a href="index.php?act=qlink&hdl=edit">Manage list from My QuickLinks</a></div>';
            document.getElementById('quickLinksDiv').innerHTML = html;
            mask.hide();
            if (menu.firstTimeShow){
                menu.firstTimeShow = false;
                menu.getEl().setStyle('z-index', '200000');
                menu.show(Ext.get('quickLinksButton'), 'tl-bl');
            }
        }, false, false);
    });
    linkMenu.on('hide', function(menu){
        Ext.get('quickLinksButton').addClass('my_links');
        Ext.get('quickLinksButton').removeClass('my_links_open');
        (function() {
            linkMenuShow = true;
        }.defer(250, this));
    });
    */
});

function openQuickLinks(){
    if (!linkMenu.isVisible() && linkMenuShow)
        linkMenu.show(Ext.get('quickLinksButton'), 'tl-bl');
}
