var SearchGrid = {first: true};

function InitialiseExtSearchEngine(mainField)
{
	var queryField = document.getElementById('hidden_query');
	
	if (typeof(Ext) == 'undefined' || queryField == null || typeof(Ext.data.JsonStore) == 'undefined' || typeof(Ext.PagingToolbar) == 'undefined' || typeof(Ext.grid.GridPanel) == 'undefined')
	{
		setTimeout(function() {InitialiseExtSearchEngine(); }, 1000);
		return;
	}
	
	mainField = mainField != null ? mainField : document.getElementById('hidden_main_field').value;
	
	var query = queryField.value;
    
	// create the Data Store
	var store = new Ext.data.JsonStore({
	    url: 'stock-lookup.cgi?mode=xml&query=' + escape(query) + '&direction=' + escape(mainField),
	    //url: 'stock-lookup.cgi?mode=xml&query=' + escape(query),
	    root: 'companies',
	    fields: ['name', 'ticker', 'set'],
	    totalProperty: 'totalCount',
        idProperty: 'id'
	});
    //store.setDefaultSort('posted', 'desc');
    
	var pagingBar = new Ext.PagingToolbar({
		pageSize: 25,
		store: store,
		displayInfo: true,
		displayMsg: 'Displaying search results {0} - {1} of {2}',
		emptyMsg: "No results to display"
	});
	
    var grid = new Ext.grid.GridPanel({
        el:'search_results_div',
        width: 620,
        height: 603,
        title:'Search results for \'' + query + '\'',
        store: store,
        trackMouseOver:false,
        disableSelection:true,
        loadMask: true,

        // grid columns
        columns:[{
            id: 'id', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: "Ticker",
            dataIndex: 'ticker',
            width: 100,
            sortable: true
        },{
            header: "Company",
            dataIndex: 'name',
            width: 432,
            sortable: true
        },{
            header: "Type",
            dataIndex: 'set',
            width: 70,
            sortable: true
        }],
		stripeRows: true,
        // paging bar on the bottom
        bbar: pagingBar
    });

    // render it
    grid.render();
    
    store.load({params:{start:0, limit:25}});
    
    SearchGrid.Grid = grid;
}

InitialiseExtSearchEngine();