function triggerFilter(){
	var filter = $("#filter .morefilters");
	if (filter.hasClass('opened')) {
		filter.slideUp('fast').removeClass('opened');
		$("#filter_switch").removeClass("opened");
		if((typeof(chText) != "undefined") && chText){
			$("#filter_switch").html(TEXT_MORE_FILTERS)
		}
	} else {
		filter.slideDown('fast').addClass('opened');
		$("#filter_switch").addClass("opened");
		if((typeof(chText) != "undefined") && chText){
			$("#filter_switch").html(TEXT_LESS_FILTERS)
		}
	}
	this.blur();
	return false;
}

/**
 * selects all categpories if "<All>" option was chosen,
 * selects "<All>" option if all categories were chosen
 * unselects "<All>" option if not all categories are chosen
 * unselects all categories if "<All>" option is unchosen
 */
function updateCategoriesChoice() {
	select = $(this).parent().get(0);
	if (this.value == 0) {
		// It's a <All> option
		$("option", select).attr("selected", this.selected);
	} else {
		// It's a certain category
		all_options_are_chosen = true;
		$("option", select).each(function(){
			if (this.value == 0) {
				// Except <All> option
				return;
			}
			if (!this.selected) {
				all_options_are_chosen = false;
			}
		});
		$("option[value=0]", select).attr("selected", all_options_are_chosen);
	}
	// Trick to avoid scrolling of <select> after triggering selecting/unselecting of all options.
	// If double change "selected" on currently cliked <option> nothing will change, except it will be scrolled to it again.
	$(this).attr("selected", !this.selected).attr("selected", !this.selected);
}

function checkCategoriesBeforeSubmit() {
	var select = $("select#category");
	var i = "";
	if($("option[value=0]", select).attr("selected")){
		$("option", select).each(function(j){
			if($(this).attr("value") != "0")
				$(this).removeAttr("selected");
		});
	}
	return true;
}

$().ready(function(){
	$("#filter_form").submit(checkCategoriesBeforeSubmit);
	$("#filter_switch").click(triggerFilter);
	$("select#category option").click(updateCategoriesChoice);

});
