//Ext.BLANK_IMAGE_URL = 'resources/s.gif';
Ext.override(Ext.grid.GridView, {
    onRowOver : function(e, t){
        var row;
        if((row = this.findRowIndex(t)) !== false){
            this.addRowClass(row, "x-grid3-row-over");
            this.grid.fireEvent('rowmouseover', this.grid, row, e);
        }
    }/*,
    onRowOut : function(e, t){
        var row;
        if((row = this.findRowIndex(t)) !== false && !e.within(this.getRow(row), true)){
            this.removeRowClass(row, "x-grid3-row-over");
            this.grid.fireEvent('rowmouseout', this.grid, row, e);
        }
    }*/
});

Docs = {};
// Record current search term so that we don't record repeated search term in short period of time
currentSearch = '';

ApiPanel = function() {
    ApiPanel.superclass.constructor.call(this, {
        id:'api-tree',
		region: 'north',
		border: false,
        /*region:'North',
        split:true,
        width: 175,
        minSize: 120,
        maxSize: 280,*/
        collapsible: false,
        margins:'0 0 5 5',
        cmargins:'0 0 0 0',
        rootVisible:false,
        lines:false,
        autoScroll:true,
        animCollapse:false,
        animate: false,
        collapseMode:'mini',
        loader: new Ext.tree.TreeLoader({
            preloadChildren: true,
            clearOnLoad: false
        }),
        root: new Ext.tree.AsyncTreeNode({
            text:'Ext JS',
            id:'root',
            expanded:true,
            children:[Docs.classData]
         }),
        collapseFirst:false
    });
    // no longer needed!
    //new Ext.tree.TreeSorter(this, {folderSort:true,leafAttr:'isClass'});

    this.getSelectionModel().on('beforeselect', function(sm, node){
        return node.isLeaf();
    });
};

Ext.extend(ApiPanel, Ext.tree.TreePanel, {
    selectClass : function(cls){
        if(cls){
            var parts = cls.split('.');
            var last = parts.length-1;
            var res = [];
            var pkg = [];
            for(var i = 0; i < last; i++){ // things get nasty - static classes can have .
                var p = parts[i];
                var fc = p.charAt(0);
                var staticCls = fc.toUpperCase() == fc;
                if(p == 'Ext' || !staticCls){
                    pkg.push(p);
                    res[i] = 'pkg-'+pkg.join('.');
                }else if(staticCls){
                    --last;
                    res.splice(i, 1);
                }
            }
            res[last] = cls;
            this.selectPath('/root/TPB/'+res.join('/'));
        }
    }
});

DocPanel = Ext.extend(Ext.Panel, {
    closable: true,
    autoScroll:true,

    initComponent : function(){
        //var ps = this.cclass.split('.');
        //this.title = ps[ps.length-1];

		this.dataStore = new Ext.data.JsonStore({
            url: this.dataStoreUrl,
			remoteSort: true,
			totalProperty: 'totalCount',
	        idProperty: 'tpb_id',
			root: this.storeReaderRoot,
            //id: this.dataStoreId,
            //reader: this.storeReader
			fields: this.storeReaderFields
        });
		
		
        DocPanel.superclass.initComponent.call(this);
		
		/*this.storeReader = new Ext.data.JsonReader({
			root: this.storeReaderRoot,
			id: this.storeReaderId,
			fields: this.storeReaderFields			
		});*/
		
		this.gridCM = new Ext.grid.ColumnModel(this.gridCMColumns);
		this.gridView = new Ext.grid.GridView({
            getRowClass: function(row, index)
            {
                /*if (row.data.amount > 80)
                {
                    return 'order_detail_shipped';
                }*/
                return '';
            }
        });
		this.gridFilters =  new Ext.ux.grid.GridFilters({
			// encode and local configuration options defined previously for easier reuse
			encode: true, // json encode the filter query
			local: true,   // defaults to false (remote filtering)
			filters: this.dataGridFilters
		});
		this.cellActions = new Ext.ux.grid.CellActions({
			listeners:{
				action:function(grid, record, action, value) {
					window.open(record.data.tlink);
				}
			},
			align:'right'
		});
		// init the grid
		this.grid = this.add(new Ext.grid.GridPanel({
			store: this.dataStore,
			cm: this.gridCM,
			view: this.gridView,
			loadMask: true, 
			stripeRows: true,
			viewConfig: { forceFit: true },
			autoHeight: true, 
			frame: false,
			border: false,
			collapsible: false, 
			animCollapse: false, 
			trackMouseOver: true,
			autoExpandColumn: 'name',
			plugins: [this.gridFilters, this.cellActions],
			// paging bar on the bottom
	        bbar: new Ext.PagingToolbar({
	            pageSize: 30,
	            store: this.dataStore,
	            displayInfo: true,
	            displayMsg: 'Displaying {0} - {1} of {2}',
	            emptyMsg: "Nothing found.",
				plugins: new Ext.ux.ProgressBarPager()
	        })
		}));
		this.grid.on('rowmouseover', function(grid, row, e){this.showTorrentDetail(grid,row,e);}, this);
		this.grid.on('rowclick', function(grid, row, e){
			var d = grid.getStore().getAt(row).data;
			window.open('/torrent/' + d.tpb_id + '?t=' + d.tlink + '&n=' + d.name);
		}, this);
		//this.grid.on('mouseout', this.hideTorrentDetail, this);
		// build a tooltip for this grid
		this.currentRow = null;
		this.contentId = this.grid.id + '_content';
		this.torrentWindow = new Ext.Window({
                layout:'fit',
                width:600,
                height:300,
                closeAction:'hide',
				autoScroll: true,
                plain: true,
                html: '<div id="' + this.contentId + '" class="windowContent"></div>',
				constrain: true,
				border: true,
				buttons: [
					new Ext.Button({text: 'Download This Torrent', iconCls:'icon-download', handler: function(){
						window.open(this.grid.getStore().getAt(this.currentRow).data.tlink);
					}.createDelegate(this)}),
					new Ext.Button({text: 'Preview In A Separate Page', iconCls:'icon-jumb-link', handler: function(){
						var d = this.grid.getStore().getAt(this.currentRow).data;
						window.open('/torrent/' + d.tpb_id + '?t=' + d.tlink + '&n=' + d.name);
					}.createDelegate(this)})],
				buttonAlign: 'center'
        });
		this.previousTimeoutId = null;
		this.previousHideTimeoutId = null;
    },
	showTorrentDetail: function(grid, row,e)
	{
		//console.log(grid);
		//console.log(row);
		//console.log(e);
		//console.log(this);
		if(row == this.currentRow) {
			return false;
		} else {
			//console.log('show');
			//console.log('start to show detail for ' + grid.id + ' ' + row);
			this.torrentWindow.hide();
			this.currentRow = row;
			var x = e.xy[0];
			var y = e.xy[1];
			//this.torrentWindow.show();
			this.torrentWindow.setTitle(grid.getStore().getAt(row).data.type + ': ' + grid.getStore().getAt(row).data.name);
			if(this.previousTimeoutId) {
				window.clearTimeout(this.previousTimeoutId);
			}
			this.previousTimeoutId = window.setTimeout(function(){
				if(x > e.xy[0] - 50 && x < e.xy[0] + 50 && y > e.xy[1] - 50 && y < e.xy[1] + 50) {
					//console.log('set position: ' + x + ',' + y);
					this.torrentWindow.setPosition(x, y);
					this.torrentWindow.show();
					if(Ext.getDom(this.contentId) && Ext.getDom(this.contentId).innerHTML) {
						Ext.getDom(this.contentId).innerHTML = 'Loading preview info, please wait...';
					}
					//console.log(this.contentId);
					var position = this.torrentWindow.getPosition();
					//console.log(position);
					var newX = position[0];
					var newY = position[1];
					var rePositionX = false;
					var rePositionY = false;
					var rePosition = false;
					if(position[0] != x) {
						newX = x - this.torrentWindow.getWidth();
						rePositionX = true;
					}
					if(position[1] != y) {
						newY = y - this.torrentWindow.getHeight();
						rePositionY = true;
					}
					if(!rePositionY && y < e.xy[1]) {
						newY = e.xy[1] + 7;
					}
					if(rePositionY && y > e.xy[1]) {
						newY = newY - 15;
					}
					this.torrentWindow.setPosition(newX, newY);
					var data = grid.getStore().getAt(row).data;
					if(data.preview) {
						Ext.getDom(this.contentId).innerHTML = data.preview;
					} else {
						var contentId = this.contentId;
						// Ajax call
						Ext.Ajax.request({
						   url: '/tpb/torrent/id/' + data.tpb_id,
						   success: function(r){data.preview = r.responseText; Ext.getDom(contentId).innerHTML = data.preview;}
						});
					}
					
					//this.torrentWindow.load({url:'/tpb/torrent/id/' + grid.getStore().getAt(row).data.tpb_id, nocache: false});
					//Ext.getDom(this.contentId).innerHTML = grid.getStore().getAt(row).data.tpb_id;
					/*var data = grid.getStore().getAt(row).data;
					if(data.preview) {
						console.log(this.torrentWindow.items);
					} else {
						var panel = 
						console.log(panel.getEl().dom.innerHTML);
					}*/
				}}.createDelegate(this), 800);
			//alert(grid.id + ' ' + row);
			//console.log(this.torrentTooltip);
		}
	},
	hideTorrentDetail: function()
	{
		console.log('hide');
		if(this.previousHideTimeoutId) {
			window.clearTimeout(this.previousHideTimeoutId);
		}
		this.previousHideTimeoutId = window.setTimeout(function(){this.torrentWindow.hide();}.createDelegate(this), 2000);
		//console.log('hide');
		//this.torrentWindow.hide();
	},
    scrollToMember : function(member){
        var el = Ext.fly(this.cclass + '-' + member);
        if(el){
            var top = (el.getOffsetsTo(this.body)[1]) + this.body.dom.scrollTop;
            this.body.scrollTo('top', top-25, {duration:.75, callback: this.hlMember.createDelegate(this, [member])});
        }
    },

    scrollToSection : function(id){
        var el = Ext.getDom(id);
        if(el){
            var top = (Ext.fly(el).getOffsetsTo(this.body)[1]) + this.body.dom.scrollTop;
            this.body.scrollTo('top', top-25, {duration:.5, callback: function(){
                Ext.fly(el).next('h2').pause(.2).highlight('#8DB2E3', {attr:'color'});
            }});
        }
    },

    hlMember : function(member){
        var el = Ext.fly(this.cclass + '-' + member);
        if(el){
            el.up('tr').highlight('#cadaf9');
        }
    }
});

SearchPanel = Ext.extend(DocPanel, {
	initComponent : function(){
		SearchPanel.superclass.initComponent.call(this);
		this.dataStore = this.dataStorePassIn;
	}
});

MainPanel = function(){
    /*this.searchStore = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            //url: '/tpb/search'
			url: '/tpb/browse/category/104'
        }),
        reader: new Ext.data.JsonReader({
                root: 'data'
            },
            ['cls', 'member', 'type', 'doc']
        ),
        baseParams: {},
        listeners: {
            'beforeload' : function(){
                this.baseParams.qt = Ext.getCmp('search-type').getValue();
            }
        }
    });*/
	// Add a search result grid
	this.searchGridPanel = new DocPanel({
		id: 'search-result-panel',
		//title: 'Search Results',
		//applyTo: 'searchResultPanelDiv',
		frame: false,
		border: false,
		storeReaderRoot: 'lists',
		storeReaderId: 'searchReadId',
		storeReaderFields: [
			{name: 'tpb_id', type: 'int'},
			{name: 'type', type: 'string'},
			{name: 'name', type: 'string'},
			{name: 'uploaded', type: 'string'},
			{name: 'size', type: 'string'},
			{name: 'seeders', type: 'int'},
			{name: 'leechers', type: 'int'},
			{name: 'tlink', type: 'string'}
		],
		dataStoreUrl: '/tpb/search',
		dataStoreId: 'searchStore',
		gridCMColumns: [
			{id: 'tpb_id', header: 'ID', dataIndex: 'tpb_id', width: 100, hidden: true},
			{id: 'type', header: 'Type', dataIndex: 'type', width: 100, sortable: true},
			{id: 'name', header: 'Name', dataIndex: 'name', width: 240, sortable: true, cellActions:[{iconCls:'icon-download',qtip:'Download This Torrent'}]},
			{id: 'uploaded', header: 'Uploaded', dataIndex: 'uploaded', width: 100, sortable: true},
			{id: 'size', header: 'Size', dataIndex: 'size', width: 100, sortable: true},
			{id: 'seeders', header: 'SE', dataIndex: 'seeders', width: 80, sortable: true},
			{id: 'leechers', header: 'LE', dataIndex: 'leechers', width: 80, sortable: true}
		],
		dataGridFilters:[
			{ type: 'string', dataIndex: 'type'},
			{ type: 'string', dataIndex: 'name'},
			{ type: 'numeric', dataIndex: 'seeders'},
			{ type: 'numeric', dataIndex: 'leechers'}
		]
	});
	
    MainPanel.superclass.constructor.call(this, {
        id:'doc-body',
        region:'center',
        margins:'0 5 5 0',
        resizeTabs: true,
        minTabWidth: 135,
        tabWidth: 135,
        plugins: new Ext.ux.TabCloseMenu(),
        enableTabScroll: true,
        activeTab: 0,

        items: {
            id:'search-panel',
            title: 'HOME',
            autoLoad: {url: '/tpb/welcome', callback: this.initSearch, scope: this},
			//html: 'Welcome To TPB Portal',
            iconCls:'icon-docs',
            autoScroll: true,
            tbar: [
                'Search: ', ' ',
                new Ext.ux.SelectBox({
                    listClass:'x-combo-list-small',
                    width:90,
                    value:'All',
                    id:'search-type',
                    store: new Ext.data.SimpleStore({
                        fields: ['text'],
                        expandData: true,
                        data : ['All', 'Audio', 'Video', 'Applications', 'Games', 'Porn', 'Other']
                    }),
                    displayField: 'text'
                }), ' ',
                new Ext.app.SearchField({
                    width:240,
                    store: this.searchGridPanel.dataStore,
                    paramName: 'q'
                })
            ]
        }
    });
};

Ext.extend(MainPanel, Ext.TabPanel, {

    initEvents : function(){
        MainPanel.superclass.initEvents.call(this);
        this.body.on('click', this.onClick, this);
        this.body.on({
            mouseover: this.onMarginEnter,
            mouseout: this.onMarginLeave,
            scope: this,
            delegate: 'td.micon'
        });
        new Ext.ToolTip({
            renderTo: document.body,
            target: this.body,
            delegate: 'td.micon',
            showDelay: 100,
            dismissDelay: 1000,
            listeners: {
//              Don't show if you *can't* expand it.
                beforeshow: function(t) {
                    var tr = Ext.get(t.triggerElement.parentNode);
                    var result = tr.hasClass("expandable");
                    if (result) {
                        t.body.dom.innerHTML = (tr.hasClass("expanded")) ? "Click to collapse" : "Click to expand";
                    }
                    return result;
                }
            }
        });
    },

    onMarginEnter: function(e) {
        var t = e.getTarget('td.micon', 2, true);
        if (t && Ext.fly(t.dom.parentNode).hasClass("expandable")) {
            t.addClass('over');
        }
    },

    onMarginLeave: function(e) {
        var t = e.getTarget('td.micon', 2, true), toTd = Ext.get(e.getRelatedTarget());
        if (toTd) toTd = toTd.up('td.micon', 2);
        if (!toTd || (toTd !== t)) {
               t.removeClass('over');
        }
    },

    onClick: function(e, target){
        if(target = e.getTarget('a:not(.exi)', 3)){
            var cls = Ext.fly(target).getAttributeNS('ext', 'cls');
            e.stopEvent();
			// Hide all windows
			Ext.WindowMgr.hideAll();
            if(cls){
                var member = Ext.fly(target).getAttributeNS('ext', 'member');
                this.loadClass(target.href, cls, member);
            }else if(target.className == 'inner-link'){
                this.getActiveTab().scrollToSection(target.href.split('#')[1]);
            }else{
                window.open(target.href);
            }
        }else if(target = e.getTarget('.micon', 2)){
            e.stopEvent();
            var tr = Ext.fly(target.parentNode);
            if(tr.hasClass('expandable')){
                tr.toggleClass('expanded');
            }
        }
    },

    loadClass : function(href, cls, title, member){
		// Hide all windows
		// Ext.WindowMgr.hideAll();
        var id = 'docs-' + cls;
        var tab = this.getComponent(id);
        if(tab){
            this.setActiveTab(tab);
            if(member){
                tab.scrollToMember(member);
            }
        }else{
            var autoLoad = {url: href};
            if(member){
                autoLoad.callback = function(){
                    Ext.getCmp(id).scrollToMember(member);
                }
            }
            var p = this.add(new DocPanel({
                id: id,
				hidden: true,
                cclass : cls,
                title: title,
                iconCls: Docs.icons[cls],
				storeReaderRoot: 'lists',
				storeReaderId: 'readId' + tab,
				storeReaderFields: [
					{name: 'tpb_id', type: 'int'},
					{name: 'type', type: 'string'},
					{name: 'name', type: 'string'},
					{name: 'uploaded', type: 'string'},
					{name: 'size', type: 'string'},
					{name: 'seeders', type: 'int'},
					{name: 'leechers', type: 'int'},
					{name: 'tlink', type: 'string'}
				],
				dataStoreUrl: href,
				dataStoreId: 'storeId' + tab,
				gridCMColumns: [
					{id: 'tpb_id', header: 'ID', dataIndex: 'tpb_id', width: 100, hidden: true},
					{id: 'type', header: 'Type', dataIndex: 'type', width: 100, sortable: true},
					{id: 'name', header: 'Name', dataIndex: 'name', width: 240, sortable: true, cellActions:[{iconCls:'icon-download',qtip:'Download This Torrent'}]},
					{id: 'uploaded', header: 'Uploaded', dataIndex: 'uploaded', width: 100, sortable: true},
					{id: 'size', header: 'Size', dataIndex: 'size', width: 100, sortable: true},
					{id: 'seeders', header: 'SE', dataIndex: 'seeders', width: 80, sortable: true},
					{id: 'leechers', header: 'LE', dataIndex: 'leechers', width: 80, sortable: true}
				],
				dataGridFilters:[
					{ type: 'string', dataIndex: 'type'},
					{ type: 'string', dataIndex: 'name'},
					{ type: 'numeric', dataIndex: 'seeders'},
					{ type: 'numeric', dataIndex: 'leechers'}
				],
				tbar:
				[
					'Search: ', ' ',
					new Ext.app.SearchField({
						width:240,
						id: 'searchfield_' + tab,
						paramName: 'q'
					})
				]
            }));
			p.dataStore.load({params:{start:0, limit:30}});
			//console.log(Ext.getCmp('search_field_' + tab));
            this.setActiveTab(p);
			Ext.getCmp('searchfield_' + tab).setStore(p.dataStore);
        }
    },

    initSearch : function(){
		this.searchGridPanel.hide();
		this.searchGridPanel.render('searchResultPanelDiv');
		this.searchGridPanel.dataStore.on('beforeload', function(){this.show();}, this.searchGridPanel);
		//console.log(this.searchGridPanel.dataStore);
	
        // Custom rendering Template for the View
        /*var resultTpl = new Ext.XTemplate(
            '<tpl for=".">',
            '<div class="search-item">',
                '<a class="member" ext:cls="{cls}" ext:member="{member}" href="output/{cls}.html">',
                '<img src="resources/images/default/s.gif" class="item-icon icon-{type}"/>{member}',
                '</a> ',
                '<a class="cls" ext:cls="{cls}" href="output/{cls}.html">{cls}</a>',
                '<p>{doc}</p>',
            '</div></tpl>'
        );

        var p = new Ext.DataView({
            applyTo: 'search',
            tpl: resultTpl,
            loadingText:'Searching...',
            store: this.searchStore,
            itemSelector: 'div.search-item',
            emptyText: '<h3>Use the search field above to search the Ext API for classes, properties, config options, methods and events.</h3>'
        });*/
    },

    doSearch : function(e){
		this.searchGridPanel.show();
        var k = e.getKey();
        if(!e.isSpecialKey()){
            var text = e.target.value;
            if(!text){
                this.searchStore.baseParams.q = '';
                this.searchStore.removeAll();
            }else{
                this.searchStore.baseParams.q = text;
                this.searchStore.reload();
            }
        }
    }
});


Ext.onReady(function(){

    Ext.QuickTips.init();

    var api = new ApiPanel();
    var mainPanel = new MainPanel();

    api.on('click', function(node, e){
         if(node.isLeaf()){
            e.stopEvent();
            mainPanel.loadClass(node.attributes.href, node.id, node.id);
         }
    });
	
    mainPanel.on('tabchange', function(tp, tab){
        api.selectClass(tab.cclass);
    });
	
	var etologyAdHtml = '<p style="text-align: center"><b><a href="http://www.youplayoff.com" title="YouPlayoff.com" target="_blank" style="text-decoration:underline;">YouPlayoff</a></b></p><p style="text-align: center">Create and Share Playoffs with Friends.</p><!--div style="text-align:center;"><iframe allowtransparency="true" src="http://pages.etology.com/imp2/88289.php" width="120" height="260" style="border:0px;margin:0px;overflow:hidden" frameborder="0" scrolling="no"></iframe></div-->';
	//etologyAdHtml = 'test';
	var westBottom = new Ext.Panel({
		border: false,
		regoin: 'south',
		html: etologyAdHtml,
		padding: 3		
	});
	var west = new Ext.Panel({
		id:'west-panel',
		items: [api, westBottom],
		region:'west',
        split:true,
        width: 175,
        minSize: 120,
        maxSize: 280,
        margins:'0 0 5 5',
        cmargins:'0 0 0 0',
		collapsible: true,
		autoScroll:true
	});
    var hd = new Ext.Panel({
        border: false,
        layout:'anchor',
        region:'north',
        cls: 'docs-header',
        height:60,
        items: [{
            xtype:'box',
            el:'header',
            border:false,
            anchor: 'none -25'
        },
        new Ext.Toolbar({
            cls:'top-toolbar',
            items:[ ' ',
            new Ext.form.TextField({
                width: 200,
                emptyText:'Find a Category',
                listeners:{
                    render: function(f){
                        f.el.on('keydown', filterTree, f, {buffer: 350});
                    }
                }
            }), ' ', ' ',
            {
                iconCls: 'icon-expand-all',
                tooltip: 'Expand All',
                handler: function(){ api.root.expand(true); }
            }, '-', {
                iconCls: 'icon-collapse-all',
                tooltip: 'Collapse All',
                handler: function(){ api.root.collapse(true); }
            }/*, '->', {
                tooltip:'Hide Inherited Members',
                iconCls: 'icon-hide-inherited',
                enableToggle: true,
                toggleHandler : function(b, pressed){
                     mainPanel[pressed ? 'addClass' : 'removeClass']('hide-inherited');
                }
            }, '-', {
                tooltip:'Expand All Members',
                iconCls: 'icon-expand-members',
                enableToggle: true,
                toggleHandler : function(b, pressed){
					// Notice the following method usage...
                    mainPanel[pressed ? 'addClass' : 'removeClass']('full-details');
                }
            }*/]
        })]
    })

    var viewport = new Ext.Viewport({
        layout:'border',
        items:[ hd, west, mainPanel ]
    });

    // allow for link in
    /*var page = window.location.href.split('?')[1];
    if(page){
        var ps = Ext.urlDecode(page);
        var cls = ps['class'];
        mainPanel.loadClass('output/' + cls + '.html', cls, ps.member);
    }*/

    viewport.doLayout();

    setTimeout(function(){
        Ext.get('loading').remove();
        Ext.get('loading-mask').fadeOut({remove:true});
    }, 250);

    var filter = new Ext.tree.TreeFilter(api, {
        clearBlank: true,
        autoClear: true
    });
    var hiddenPkgs = [];
    function filterTree(e){
        var text = e.target.value;
        Ext.each(hiddenPkgs, function(n){
            n.ui.show();
        });
        if(!text){
            filter.clear();
            return;
        }
        api.expandAll();

        var re = new RegExp('^' + Ext.escapeRe(text), 'i');
        filter.filterBy(function(n){
            return !n.attributes.isClass || re.test(n.text);
        });

        // hide empty packages that weren't filtered
        hiddenPkgs = [];
        api.root.cascade(function(n){
            if(!n.attributes.isClass && n.ui.ctNode.offsetHeight < 3){
                n.ui.hide();
                hiddenPkgs.push(n);
            }
        });
    }

});


Ext.app.SearchField = Ext.extend(Ext.form.TwinTriggerField, {
    initComponent : function(){
		if(this.store) {
			if(!this.store.baseParams){
				this.store.baseParams = {};
			}
			// Add store empty load event
			this.attacheStoreLoad();
		}
		
        Ext.app.SearchField.superclass.initComponent.call(this);
        this.on('specialkey', function(f, e){
            if(e.getKey() == e.ENTER){
                this.onTrigger2Click();
            }
        }, this);
    },

    validationEvent:false,
    validateOnBlur:false,
    trigger1Class:'x-form-clear-trigger',
    trigger2Class:'x-form-search-trigger',
    hideTrigger1:true,
    width:180,
    hasSearch : false,
    paramName : 'query',

    onTrigger1Click : function(){
        if(this.hasSearch){
            this.store.baseParams[this.paramName] = '';
            this.store.removeAll();
            this.el.dom.value = '';
            this.triggers[0].hide();
            this.hasSearch = false;
            this.focus();
			var o = {start: 0};
			this.store.reload({params:o});
        }
    },

    onTrigger2Click : function(){
        var v = this.getRawValue();
        if(v.length < 1){
            this.onTrigger1Click();
            return;
        }
        /*if(v.length < 2){
            Ext.Msg.alert('Invalid Search', 'You must enter a minimum of 2 characters to search the API');
            return;
        }*/
        this.store.baseParams[this.paramName] = v;
		// Save this search term to database only different from local search term cache
		if(v != currentSearch) {
			// Update the latest search term on top
			var newSearchTerm = {
				tag: 'a',
				cls: 'search-term',
				target: '_blank',
				href: '/search/' + escape(v),
				html: v
			};
			Ext.DomHelper.insertAfter('searchStartB', newSearchTerm);
			currentSearch = v;
			Ext.Ajax.request({
			   url: '/tpb/record-search-term',
			   params: { t: v}
			});
		}
		this.store.baseParams.qt = Ext.getCmp('search-type').getValue();
        var o = {start: 0};
        this.store.reload({params:o});
        this.hasSearch = true;
        this.triggers[0].show();
        this.focus();
    },
	attacheStoreLoad: function(){
		if(this.store) {
			// Add store empty load event
			this.store.on('load', function(s, r, o){
				if(!r || r.length == 0) {
					Ext.Msg.alert('Nothing Found', 'Sorry, but we found nothing. <br><br>The reason may be one of the followings:<br><br>(1) Nothing really exists. Please change your search terms!<br>(2) The pirate bay search engine is overloaded. Please try again in 30 seconds!');
				}
			});
		}
	},
	setStore: function(store){
		this.store = store;
		this.attacheStoreLoad();		
	}
});


/**
 * Makes a ComboBox more closely mimic an HTML SELECT.  Supports clicking and dragging
 * through the list, with item selection occurring when the mouse button is released.
 * When used will automatically set {@link #editable} to false and call {@link Ext.Element#unselectable}
 * on inner elements.  Re-enabling editable after calling this will NOT work.
 *
 * @author Corey Gilmore
 * http://extjs.com/forum/showthread.php?t=6392
 *
 * @history 2007-07-08 jvs
 * Slight mods for Ext 2.0
 */
Ext.ux.SelectBox = function(config){
    this.searchResetDelay = 1000;
    config = config || {};
    config = Ext.apply(config || {}, {
        editable: false,
        forceSelection: true,
        rowHeight: false,
        lastSearchTerm: false,
        triggerAction: 'all',
        mode: 'local'
    });

    Ext.ux.SelectBox.superclass.constructor.apply(this, arguments);

    this.lastSelectedIndex = this.selectedIndex || 0;
};

Ext.extend(Ext.ux.SelectBox, Ext.form.ComboBox, {
    lazyInit: false,
    initEvents : function(){
        Ext.ux.SelectBox.superclass.initEvents.apply(this, arguments);
        // you need to use keypress to capture upper/lower case and shift+key, but it doesn't work in IE
        this.el.on('keydown', this.keySearch, this, true);
        this.cshTask = new Ext.util.DelayedTask(this.clearSearchHistory, this);
    },

    keySearch : function(e, target, options) {
        var raw = e.getKey();
        var key = String.fromCharCode(raw);
        var startIndex = 0;

        if( !this.store.getCount() ) {
            return;
        }

        switch(raw) {
            case Ext.EventObject.HOME:
                e.stopEvent();
                this.selectFirst();
                return;

            case Ext.EventObject.END:
                e.stopEvent();
                this.selectLast();
                return;

            case Ext.EventObject.PAGEDOWN:
                this.selectNextPage();
                e.stopEvent();
                return;

            case Ext.EventObject.PAGEUP:
                this.selectPrevPage();
                e.stopEvent();
                return;
        }

        // skip special keys other than the shift key
        if( (e.hasModifier() && !e.shiftKey) || e.isNavKeyPress() || e.isSpecialKey() ) {
            return;
        }
        if( this.lastSearchTerm == key ) {
            startIndex = this.lastSelectedIndex;
        }
        this.search(this.displayField, key, startIndex);
        this.cshTask.delay(this.searchResetDelay);
    },

    onRender : function(ct, position) {
        this.store.on('load', this.calcRowsPerPage, this);
        Ext.ux.SelectBox.superclass.onRender.apply(this, arguments);
        if( this.mode == 'local' ) {
            this.calcRowsPerPage();
        }
    },

    onSelect : function(record, index, skipCollapse){
        if(this.fireEvent('beforeselect', this, record, index) !== false){
            this.setValue(record.data[this.valueField || this.displayField]);
            if( !skipCollapse ) {
                this.collapse();
            }
            this.lastSelectedIndex = index + 1;
            this.fireEvent('select', this, record, index);
        }
    },

    render : function(ct) {
        Ext.ux.SelectBox.superclass.render.apply(this, arguments);
        if( Ext.isSafari ) {
            this.el.swallowEvent('mousedown', true);
        }
        this.el.unselectable();
        this.innerList.unselectable();
        this.trigger.unselectable();
        this.innerList.on('mouseup', function(e, target, options) {
            if( target.id && target.id == this.innerList.id ) {
                return;
            }
            this.onViewClick();
        }, this);

        this.innerList.on('mouseover', function(e, target, options) {
            if( target.id && target.id == this.innerList.id ) {
                return;
            }
            this.lastSelectedIndex = this.view.getSelectedIndexes()[0] + 1;
            this.cshTask.delay(this.searchResetDelay);
        }, this);

        this.trigger.un('click', this.onTriggerClick, this);
        this.trigger.on('mousedown', function(e, target, options) {
            e.preventDefault();
            this.onTriggerClick();
        }, this);

        this.on('collapse', function(e, target, options) {
            Ext.getDoc().un('mouseup', this.collapseIf, this);
        }, this, true);

        this.on('expand', function(e, target, options) {
            Ext.getDoc().on('mouseup', this.collapseIf, this);
        }, this, true);
    },

    clearSearchHistory : function() {
        this.lastSelectedIndex = 0;
        this.lastSearchTerm = false;
    },

    selectFirst : function() {
        this.focusAndSelect(this.store.data.first());
    },

    selectLast : function() {
        this.focusAndSelect(this.store.data.last());
    },

    selectPrevPage : function() {
        if( !this.rowHeight ) {
            return;
        }
        var index = Math.max(this.selectedIndex-this.rowsPerPage, 0);
        this.focusAndSelect(this.store.getAt(index));
    },

    selectNextPage : function() {
        if( !this.rowHeight ) {
            return;
        }
        var index = Math.min(this.selectedIndex+this.rowsPerPage, this.store.getCount() - 1);
        this.focusAndSelect(this.store.getAt(index));
    },

    search : function(field, value, startIndex) {
        field = field || this.displayField;
        this.lastSearchTerm = value;
        var index = this.store.find.apply(this.store, arguments);
        if( index !== -1 ) {
            this.focusAndSelect(index);
        }
    },

    focusAndSelect : function(record) {
        var index = typeof record === 'number' ? record : this.store.indexOf(record);
        this.select(index, this.isExpanded());
        this.onSelect(this.store.getAt(record), index, this.isExpanded());
    },

    calcRowsPerPage : function() {
        if( this.store.getCount() ) {
            this.rowHeight = Ext.fly(this.view.getNode(0)).getHeight();
            this.rowsPerPage = this.maxHeight / this.rowHeight;
        } else {
            this.rowHeight = false;
        }
    }

});

// Tracking?
/*Ext.Ajax.on('requestcomplete', function(ajax, xhr, o){
    if(typeof urchinTracker == 'function' && o && o.url){
        urchinTracker(o.url);
    }
});*/
