var archiveSearch = function (channel_id) {
	var form = $$('.sidesearch form'),
		main = $$('.main'),
		timer, searching = false;

	// preload ajax loader
	new Image().src = "/img/ajax-loader-big.gif";

	// attach handlers
	form = form ? form[0] : null;
	main = main ? main[0] : null;
	if (form && main) {
		form.reset();
		form.observe('submit', search);
		form.select('ul')[0].observe('click', checkFilters);
		main.observe('click', resetSearch);
	}

	function search(e) {
		// disable searching and collect inputs
		searching = true;
		var params = form.serialize();
		form.disable();

		if (e) e.stop();

		// delete current articles
		$$('.article').invoke('remove');

		// fetch articles from server
		new Ajax.Request('/snippets/archives/' + channel_id + '/?' + params, {
			method: 'get',
			onLoading: function () { main.addClassName('loading'); },
			onSuccess: function (data) {
				main.insert({ bottom: data.responseText });
			},
			onComplete: function () {
				main.removeClassName('loading');
				form.enable();
				searching = false;
			}
		});
	}

	// on category click, wait a moment for further input, then initiate search
	function checkFilters(e) {
		var input_type = e.target.tagName.toLowerCase();

		if (!searching && (input_type == "input" || input_type == "label")) {
			if (timer) clearTimeout(timer);
			timer = setTimeout( function () {
				search();
			}, 750);
		}
	}

	// watch for "all articles" link on failed searches
	function resetSearch(e) {
		if (e.target.getAttribute('rel') == "all") {
			form.reset();
			search(e);
		}
	}
};
