var searchStatus = 'default';

function search_button() {
	var query = document.getElementById('query');
	query.value = query.value.replace(/^\s+|\s+$/g,"");
	
	if(searchStatus == 'default') {
		search_clear_and_focus(query);
		searchStatus = 'focused';
	} else if(searchStatus == 'focused') {
		search_go(query);
	}
	
	return false;
}

function search_query() {
	var query = document.getElementById('query');
	query.value = query.value.replace(/^\s+|\s+$/g,"");
	
	if(searchStatus == 'default') {
		search_clear_and_focus(query);
	} else if(searchStatus == 'focused' && query.value == '') {
		search_reset(query);
	} else if(searchStatus == 'focused' && query.value != '') {
		// do nothing
	}
	
	return false;
}

function search_clear_and_focus(query) {
	query.value = '';
	query.className = 'focused';
	
	query.focus();
	
	searchStatus = 'focused';
	return false;
}

function search_reset(query) {
	query.value = 'search';
	query.className = '';
	
	searchStatus = 'default';
	return false;
}

function search_go(query) {
	if(query.value != '') {
		var escaped = escapeQuery(query.value);
		window.location = '/search/' + escaped;
		//window.location = 'http://www.google.com/search?q=site%3Atagg.im+' + escaped;
	} else {
		search_clear_and_focus();
	}
	
	return false;
}

function highlightSearchResults() {
	var query = document.getElementById('query');
	
	var location = new String(document.location); 
	var locationComponents = location.split('/search/');
	
	if(locationComponents.length > 0) {
		//We have stuff to highlight
		var str = locationComponents[1];
		
		//Populate the search box
		query.value = unescapeQuery(str);
	}
}

function escapeQuery(str) {
	str = escape(str);
	str = str.replace(/\+/g, "%2B");
	str = str.replace(/\//g, "%2F");
	str = str.replace(/%20/g, "+");
	
	return str;
}

function unescapeQuery(str) {
	str = str.replace(/\+/g, "%20");
	str = str.replace(/%2F/g, "\/");
	str = str.replace(/%2B/g, "\+");
	str = unescape(str);
	
	return str;
}
