var search_box_selector = "#company_search";
var company_search_url = "";
var search_query = "";
ajax_request2 = null;
var not_found = true;

$(document).ready(function() {
	// focus on search box
	// setTimeout(function() {
	// 		$(search_box_selector).focus();
	// 	},50);
	$(search_box_selector)
		.keyup(search_modified)
		.blur(function() {
			setTimeout(function() {
				$('div.search_results_container').hide();
			},150);
		})
		.click(function() {
			if ($(this).val()=='search companies') {
				$(this).val('');
			};
		});
	company_search_url = $('#root_url').html()+'companies/ajaxSearch/';
	
	$('tr.result.company').live('click',function() {
		$.historyLoad($(this).find('td.url').html());
		return false;
	});
});

function search_modified() {
	var new_query = $(search_box_selector).val();
	if (new_query!=search_query) {
		not_found = false;
		search_query = new_query;
		$('tr#no_match').hide();
		get_results();
	};
}

function get_results() {
	$('div.black_spinner').show();
	
	if (ajax_request2) { // checks for an existing ajax request
		ajax_request2.abort(); // aborts request
	};
	var url = company_search_url+search_query+'.json';
	
	ajax_request2 = $.ajax({
		url : url,
		dataType : 'json',
		success : function(data) {
			$('table.search_results tr.result.company').remove();
			if (data!=null) {
				$.each(data.item,function() {
					var new_row = $('table.search_results tr.result:first').clone();
					var query_index = this.name.toLowerCase().indexOf(search_query.toLowerCase());
					var item_name = this.name.substring(0,query_index)+"<strong>"+this.name.substring(query_index,query_index+search_query.length)+"</strong>"+this.name.substring(query_index+search_query.length,this.name.length);
					new_row.find('td.name').html(item_name);
					new_row.find('td.url').html(this.url);
					if (this.id) {
						new_row.find('td.id').html(this.id);
					};
					new_row.addClass('company');
					new_row.insertAfter('table.search_results tr:last');
				});
				$('table.search_results tr.company').show();
			} else {
				not_found = true;
				$('tr#no_match').show();
			};
			$('div.search_results_container').show();
			$('div.black_spinner').hide();
		}
	});
}
