function triggerFilter(){
	var filter = jQuery("#filter .morefilters");
	if (filter.hasClass('opened')) {
		filter.slideUp('fast').removeClass('opened');
		jQuery("#filter_switch").removeClass("opened");
		if((typeof(chText) != "undefined") && chText){
			jQuery("#filter_switch").html(TEXT_MORE_FILTERS)
		}
	} else {
		filter.slideDown('fast',
			// Workaround for a weird bug #4115 which appeared after jQuery 1.3.2 -> 1.4.1 switch:
			function(){
				jQuery(this).find("*").css("zoom", "0").css("zoom", "1");
			}
			).addClass('opened');
		jQuery("#filter_switch").addClass("opened");
		if((typeof(chText) != "undefined") && chText){
			jQuery("#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 = jQuery(this).parent().get(0);
	if (this.value == 0) {
		// It's a <All> option
		jQuery("option", select).attr("selected", this.selected);
	} else {
		// It's a certain category
		all_options_are_chosen = true;
		jQuery("option", select).each(function(){
			if (this.value == 0) {
				// Except <All> option
				return;
			}
			if (!this.selected) {
				all_options_are_chosen = false;
			}
		});
		jQuery("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.
	jQuery(this).attr("selected", !this.selected).attr("selected", !this.selected);
}

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

function fixSubcategoryLinkWidth(){
	var context = jQuery("ul.navigation"),
		categories = context.find('li.category');
	
	for(var i = 0, len = categories.length; i < len; i++) {
		var category = jQuery(categories[i]),
			link = category.find('a.top-cat-link'),
			subs = category.find('ol.sub-cat-holder'),
			linkWidth = link.width(),
			subsWidth = subs.width();
		
		if(linkWidth > subsWidth) {
			subs.find('a.sub-cat-link').width(linkWidth);
		}
	}
}

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

});

