var tags = null;
var search_tag = "";
var search_lock = false;
function handleSearchTag() {
	// If what's entered is not the same as the last search,
	// then perform search again.
	if ($('search_tag').value != search_tag && !search_lock) {
		search_tag = $('search_tag').value;
		
		// Get all the elements that are tags.
		if (tags == null) {
			tags = document.getElementsByClassName('tag');
		}
		
		// Conduct the search.
		var count = searchTags(slug(search_tag), tags);
		
		// If there are no results, alert the user...
		if (count == 0) {
			// ... by changing the color of the text field.
			$('search_tag').setStyle({ backgroundColor: '#f26c4f' });
		} else {
			$('search_tag').setStyle({ backgroundColor: 'white' });
		}
		
		if (search_tag == null || search_tag == "") {
			$('search_tag_clear').hide();
		} else {
			$('search_tag_clear').show();
		}
		
		// // Change the URL hash on the address bar.
		// if (search_tag == 0)
		// 	location.hash = "#";
		// else
		// 	location.hash = "#" + search_tag;
	}
}

function searchTags(search_tag, tags) {
	search_lock = true;
	
	var needle = new RegExp(search_tag);
	var count = 0;
	var tags_length = tags.length;
	var search_tag_length = search_tag.length;
	for (var i = 0; i < tags_length; i++) {
		tag = tags[i];
		if (search_tag_length == 0 || needle.test(tag.id)) {
			count++;
			tag.show();
		} else {
			tag.hide();
		}
	}
	
	search_lock = false;
	
	return count;
}

function slug(value) {
	return value.strip().replace(/[^A-Za-z0-9]+/, '_')
}

function initSearchTags() {
	// var hash = location.hash.replace('#', '');
	// if (hash.length > 0) {
	// 	$('search_tag').value = hash;
	// 	
	// 	// Conduct the search now!
	// 	handleSearchTag();
	// }
	
	$('search_tag').focus();
}

Event.observe(window, "load", initSearchTags);


