/*
 * Copyright SYSteam DK Väst
 * Author: Magnus Johansson
 * Date:   2012-01-13
 *
 */

(function( $ ) {
  $.fn.treeView = function() {

		// hide all
		this.addClass("treeview");
		this.attr("state", "max");
		this.children("ul").attr("state", "max");
		var parent = this.parent();
		$("ul", this).hide();
		$("ul", this).attr("state", "min");

		$("li", this).each(function() {
			//if ($(this).children('ul').length > 0) {
				if ($.trim($(this).children('ul').text()) != "") {
					$(this).addClass("expandable");
				} else {
					$(this).addClass("not-expandable");
					$(this).children('ul').remove();
				}
			//}
			/*
			var ul = $(this).children('ul').html();
			if (ul != null) {			
				ul = ul.replace(/(\r\n|\n|\r|\s)/gm,"");
				if (ul == "") {
					$(this).children('ul').remove();
				}
			}
			
			var t = $(this).html();
			t = t.replace(/(\r\n|\n|\r|\s)/gm,"");
			if (t == "") {
				$(this).remove();
			}
			*/
		});
		
		$(".subcategory .subcategory", this).each(function() {
			if ($.trim($(this).children('.documents').text()) != "") {
				$(this).addClass("hasdoc");
				$(this).parents("li.expandable").addClass("hasdoc");
			}
		});

		$("li", this).click(function(event){
		
			parent.css('borderColor', 'white');
			parent.css('borderWidth', '0px');

			if ($(this).children('ul').length == 0) {
				event.stopPropagation();
				return true;
			}
			
			if ($(this).children('ul').attr("state") == "max") {
				$(this).children('ul').hide();
				$(this).children('ul').attr("state", "min");
				$(this).removeClass("minimizable");
				$(this).addClass("expandable");
				event.stopPropagation();
				return true;
			}
			
			if ($(this).children('ul').attr("state") == "min") {
				$(this).children('ul').show();
				$(this).children('ul').attr("state", "max");
				$(this).addClass("minimizable");
				$(this).removeClass("expandable");
				event.stopPropagation();
				return true;
			}
		});	

  };
})( jQuery );
