$(function() {
    $.ECHO.producttree = {};
    
    $.ECHO.producttree.getCategory = function() {
        var url = document.location;
        var array = /\/products\/([\w|-]+)\/?/.exec(url);
        return array != undefined ? array[1] : null;
    };

    $.ECHO.producttree.toggle = function(el) {
        $(el).toggleClass('open');
        $(el).toggleClass('close');
        $(el).siblings('ul').toggle();
    };
    
    $.ECHO.producttree.init = function() {
        var div = $('div.statistics');
        var category = $.ECHO.producttree.getCategory();
        
        div.find('li.clickable').each(function(i, n) {
            $(this).removeClass('hidden');
            
            var siblings = $(this).siblings('ul');
            if (siblings.length == 0) {
                $(this).removeClass('open close');
                $(this).addClass('leaf');
                
                var a = $($(this).find('a'));
                a.attr('href', a.attr('location'));
                a.removeAttr('location');
            }
            
            siblings.hide();
            
            $(this).click(function() {
                if (!$(this).hasClass('leaf')) {
                    $.ECHO.producttree.toggle(this);
                }
            });
            
            if ($(this).find('a').attr('linkified').toLowerCase().indexOf(category) != -1) {
                var parent = $(this).parent();
                
                while (!parent.hasClass('statistics')) {
                    $.ECHO.producttree.toggle(parent.siblings('li'));
                    parent.show();
                    parent.siblings().show();
                    parent = parent.parent();
                }
            }
        });
    }();
    
});