(function($) {
	$(document).ready(function() {

		function toSlug(value, separator)
		{
			var value_lowered = $.trim(value.toLowerCase());
			var value_with_crap_removed = value_lowered.replace(/[^a-z0-9\s]+/g, '');
			return value_with_crap_removed.replace(/\b[\s]+\b/g, separator);
		}

		var courselist = {
			css: {
				back: 'sys_course_browser_list_back'
			},
			hash: location.hash,
			open: false
		};

		var $backButton = $(document.createElement('a'))
			.attr({ 'href':'javascript:void(0)' })
			.text('Back')
			.addClass(courselist.css.back)
			.click(function() {
				var $this = $(this);
				$this.parent().siblings('li').show();
	        		$this.siblings('ul').hide();
				$this.hide();
        			courselist.open = false;
        			location.hash = 'closed';
				return false;
			});
		
		$('.sys_course_browser_text > div > ul > li > a').each(function() {
			var $this = $(this);
			var $href = '#' + toSlug($this.text(), '-');
			$this.attr('href', $href);
			$this.wrap('<h2/>');
		});
		
		$backButton.appendTo('.sys_course_browser_text ul li');
		$('.sys_course_browser_text ul li ul, .sys_course_browser_text ul li .' + courselist.css.back).hide();

		$('.sys_course_browser_text > div > ul > li > h2 > a').click(function() {
			var $this = $(this);
			if (courselist.open) {
				$this.parent().siblings('.' + courselist.css.back).click();
				return false;
			} else {
				$this.parent().parent().siblings('li').hide();
				$this.parent().siblings().show();
				courselist.open = true;
        		}
        		//return false;
		});
	
		if (courselist.hash.length > 1)
		{
			$('.sys_course_browser_text > div > ul > li > h2 > a[href="' + courselist.hash + '"]').click();
		}
	});
})(jQuery);