window.addEvent('domready', function() {

	var visualFilter = new Element('div', { 'id': 'visualFilter' });
	$$('#info > div').grab(visualFilter, 'top');
	elems = $$('#info dl > dd[class]');

	allClasses = '';
	elems.each(function(item){
		allClasses += item.get('class') + ' ';
	});

	classes = [];
	classes.combine(allClasses.split(' ')).erase('');

	countryPrefix = 'country_';
	typePrefix = 'type_';

	countries = [];
	types = [];

	classes.each(function(item){
		if (item.contains(countryPrefix)) {
			countries.include(item.substr(countryPrefix.length));
		} else if (item.contains(typePrefix)) {
			types.include(item.substr(typePrefix.length));
		}
	});
	countries.sort();
	types.sort();

	var theCountries = new Hash();
	countries.each(function(item){
		theCountries.set(item.replace(/-/g, ' '), elems.filter('.'+countryPrefix+item).length);
	});

	var theTypes = new Hash();
	types.each(function(item){
		theTypes.set(item.replace(/-/g, ' '), elems.filter('.'+typePrefix+item).length);
	});


	if (countries.length > 0) {
		var visualFilterCountries = new Element('div');
		visualFilter.grab(visualFilterCountries);
		visualFilterCountries.grab(new Element('p', { 'class': 'active', 'html': '<span>All Countries</span> <em>'+elems.length+'</em>' }));
		theCountries.each(function(value, key){
			if (key.length < 4) { open_tag = '<span style="text-transform:uppercase">' } else { open_tag = '<span>' }
			visualFilterCountries.grab(new Element('p', { 'html': open_tag+key+'</span> <em>'+value+'</em>' }));
		});
	}
	if (types.length > 0) {
		var visualFilterTypes = new Element('div');
		visualFilter.grab(visualFilterTypes);
		visualFilterTypes.grab(new Element('p', { 'class': 'active', 'html': '<span>All Types</span> <em>'+elems.length+'</em>' }));
		theTypes.each(function(value, key){
			visualFilterTypes.grab(new Element('p', { 'html': '<span>'+key+'</span> <em>'+value+'</em>' }));
		});
	}


	filterControls = visualFilter.getElements('div p span');
	filterControls.addEvent('click', function(){
		txt = this.get('text');
		elParent = this.getParent();
		elGrandParent = elParent.getParent();
		if (!elParent.hasClass('active')) {
			visualFilter.getElements('p').removeClass('active');
			visualFilter.getElements('p:first-child').toggleClass('active');
			if (txt == 'All Countries' || txt == 'All Types') {
				elems.removeClass('off');
			} else {
				elGrandParent.getElements('p').removeClass('active');
				elParent.toggleClass('active');
				if (elGrandParent == visualFilterTypes) {
					prefix = typePrefix;
				} else if (elGrandParent == visualFilterCountries) {
					prefix = countryPrefix;
				}
				elems.each(function(item){
					if (item.hasClass(prefix+txt.replace(/ /g, '-'))) {
						item.removeClass('off');
					} else {
						item.addClass('off');
					}
				});
			}
		}
	});

});