var SearchGrid = {first: true};

function RefreshSearchGrid(store, query)
{
	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: 800,
		height: 400,
		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: 160,
			sortable: true
		},{
			header: "Company",
			dataIndex: 'name',
			width: 488,
			sortable: true
		},{
			header: "Type",
			dataIndex: 'set',
			width: 140,
			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;
}

function InitialiseExtSearchEngine(mainField)
{
	mainField = mainField != null ? mainField : document.getElementById('hidden_main_field').value;
	var queryField = document.getElementById('hidden_query');
	var query = queryField.value;
	
	// create the Data Store
	var store = new Ext.data.JsonStore({
		url: 'search-service.php?mode=query&query=' + encodeURIComponent(query) + '&direction=' + encodeURIComponent(mainField),
	    root: 'companies',
	    fields: ['name', 'ticker', 'set'],
	    totalProperty: 'totalCount',
        idProperty: 'id'
	});

    store.load({params:{start:0, limit:25}, callback: function(r, options, success){
		var container = Ext.get('search_container');
		if (container == null)
				return;
			
		if (r.length > 0 && success)
		{
			var html = ['<div class="radios">',
				'<div>',
					'<input type="radio" value="stocks" id="stocks_direction" name="direction" /><label for="stocks_direction">Show Stocks first</label>&nbsp;',
					'<input type="radio" value="funds" id="funds_direction" name="direction" /><label for="funds_direction">Show Mutual Funds first</label>&nbsp;',
					'<input type="radio" value="default" id="default_direction" name="direction" checked="checked" /><label for="default_direction">Show default order</label>',
				'</div>',
				'<!--Here are the companies and tickers that match your search for <strong>',query,'</strong>. Select your desired company from the list below.-->',
			'</div>',
			'<div id="search_results_div"></div>'].join("\n");

			container.update(html);
			RefreshSearchGrid(store, query);

			var elements  =['stocks_direction', 'funds_direction', 'default_direction'];

			for (var i = 0; i < elements.length; i++)
			{
				var el = Ext.get(elements[i]);
				if (el == null) continue;

				el.on('click', function(){
					var mField = this.dom.value;
					var cont = document.getElementById('search_results_div');

					if (cont != null)
					{
						cont.innerHTML = '';

						// create the Data Store
						var tmpStore = new Ext.data.JsonStore({
							//url: 'stock-lookup.cgi?mode=xml&query=' + encodeURIComponent(query) + '&direction=' + encodeURIComponent(mField),
							url: 'search-service.php?mode=query&query=' + encodeURIComponent(query) + '&direction=' + encodeURIComponent(mField),
							root: 'companies',
							fields: ['name', 'ticker', 'set'],
							totalProperty: 'totalCount',
							idProperty: 'id'
						});

						RefreshSearchGrid(tmpStore, query);
					}
				});
			}
		}
		else
		{
			var letter = (query.length > 0 ? query.substr(0,1) : '');
			
			var html = ["<div>We're sorry, but no match for <strong>" + query + "</strong> was found.</div><br />",
						'<!--<div><form method="GET" action="stock-lookup.php">Please try again: <input name="query" type="text" class="">&nbsp;&nbsp;<input type="submit" class="header-submit-search" value="" /></form></div><br />-->',
						'<div>Browse our company list by the <a href="/stock/stocklist' + letter.toLowerCase() + '.html">letter ' + letter.toUpperCase() + '</a></div><br />',
						'<div>or Check out today\'s most popular stocks:</div><div id="hot_stocks"></div><br />',
						'<div>or Browse our companies <a href="/industry_list.cgi">by Industry</a>.</div><br />',
						'<div><b>Search Tips:</b></div>',
						'<div style="padding-left: 25px;">',
							'<ul style="list-style: circle">',
								"<li>Use our search tool to your advantage. If you aren't sure exactly what you're looking for, try typing in the desired phrase letter by letter in the search box above, and use the suggested list of companies in the dropdown menu to help you figure out the company you want to find.</li>",
								'<li>Confirm that the words are spelled correctly.</li>',
								'<li>If your search had multiple words, try just one (or two) of the words.</li>',
								"<li>If you're searching for something that should be in our stock research section but you don't see it, let us know. Thanks for helping us to make InvestorGuide.com more useful!</li>",
							'</ul>',
						'</div>'].join("\n")

			container.update(html);

			Ext.Ajax.request({
				loadMask: false,
				url: 'search-service.php?mode=get_hot_stocks',
				success: function(resp) {
					var stocks = Ext.decode(resp.responseText);
					var html = '';

					for (var i = 0; i < stocks.length; i++)
					{
						html += '<a href="stock.php?ticker=' + encodeURIComponent(stocks[i].ticker) + '">' + Ext.util.Format.htmlEncode(stocks[i].name) + ' <strong>(' + Ext.util.Format.htmlEncode(stocks[i].ticker) + ')</strong></a><br />';
					}

					Ext.get('hot_stocks').update(html);
				}
			});
		}
	}
	});
}

Ext.onReady(InitialiseExtSearchEngine);
