$(document).ready(function(){
	$('ul.sitemap').sitemap();
});

jQuery.fn.sitemap = function() {
    return this.each(function(){
	
		//set variables
        var $map = $(this);
        var $roots = $map.find('li');
		
		//add classes
        $map.find('li:last-child').addClass('last');
        $map.addClass('sitemap');
		
		//hide all lists apart from the root list by default
        $map.find('ul').hide();
		
		//repeat trough all lists
        $roots.each(function(){
			//if list-item contains a child list
            if ($(this).children('ul').length > 0) {
				//add expand/contract control
                $(this).addClass('root').prepend('<span class="expand" />');
			}
        });

		//when expand is clicked
        $('span.expand').toggle(
			function(){
				// if clicked once, find all lists inside and expand
                $(this).toggleClass('contract').nextAll('ul').slideDown("fast");
            },
			
            function(){
				//if it's clicked again, find all inside lists and hide them
                $(this).toggleClass('contract').nextAll('ul').slideUp("fast");
            }
        );
    });
};