function trim(s) {
	return s.replace(/^\s+|\s+$/,'');
}

function go(url) {
//	document.location.href = "go/?" + url;
	document.location.href = url;
}

function is_url(query) {
	len = query.length;
	if (query.substring(0,4) == "www." /*|| len > 3 && query.substring(len - 3, len) == ".ru" || len > 4 && (query.substring(len - 4, len) == ".com" || query.substring(len - 4, len) == ".org")*/)
		document.location.href = "http://" + query;
	else if (query.substring(0,7) == "http://")
		document.location.href = query;
	else
		return false;
	return true;
}

function google_url(query, area) {
	switch (area) {
		case 'krasu'  : return "http://www.google.ru/search?q=" + query + "+site:krasu.ru";
		case 'sfu'    : return "http://www.google.ru/search?q=" + query + "+site:sfu-kras.ru";
		case 'define' : return "http://www.google.ru/search?q=define%3A" + query;
		case 'images' : return "http://images.google.ru/images?q=" + query;
		case 'news'   : return "http://news.google.com/news?q=" + query;
		case 'blogs'  : return "http://blogsearch.google.com/blogsearch?q=" + query;
		default       : return "http://www.google.ru/search?q=" + query;
	}
}

function yandex_url(query, area) {
	switch (area) {
		case 'krasu'  : return "http://www.yandex.ru/yandsearch?ras=1&text=" + query + "&site=krasu.ru";
		case 'sfu'    : return "http://www.yandex.ru/yandsearch?ras=1&text=" + query + "&site=sfu-kras.ru";
		case 'define' : return "http://slovari.yandex.ru/search.xml?text=" + query;
		case 'images' : return "http://www.yandex.ru/yandsearch?text=" + query + "&rpt=image";
		case 'news'   : return "http://news.yandex.ru/yandsearch?text=" + query + "&rpt=nnews2";
		case 'blogs'  : return "http://blogs.yandex.ru/search.xml?text=" + query;
		default       : return "http://www.yandex.ru/yandsearch?text=" + query;
	}
}

function save_searcher(searcher) {
	var d = new Date();
	d.setYear(d.getYear() + 1);
	document.cookie = 'searcher=' + searcher + '; expires=' + d.toGMTString() + '; path=/';
}

function load_searcher(select) {
	if (document.cookie.length > 0) {
		start = document.cookie.indexOf("searcher=");
		if (start != -1) {
			start = start + "searcher=".length;
			end = document.cookie.indexOf(";", start);
			if (end == -1)
				end = document.cookie.length;
			searcher = document.cookie.substring(start, end);
			if (searcher != '')
				select.value = searcher;
		}
	}
}

function search() {
	query = trim(document.getElementById("search_query").value);
	if (query == '' || is_url(query)) return;
	query = encodeURIComponent(query);
	area = document.getElementById("search_area").value;
	searcher = document.getElementById("searcher").value;
	save_searcher(searcher);
	if (searcher == 'google')
		go(google_url(query,area));
	else
		go(yandex_url(query,area));
}
