$(document).ready(function(){
	$('#tableofcontents ul li.hideable').addClass('show'); // hide all
	var stateArray = [];
	$("#tableofcontents").children('ul').children('li:not(.leaf)').each(function(){
	    stateArray.push("open");
	});

	
	$('#tableofcontents li a').click(function(event){ // on li click
		event.stopPropagation();
		if ($(this).parent("li").hasClass("show")) //if this has a class of expanded i.e. already open
		{
			$(this).parent("li").removeClass('show').addClass('hide'); // remove class expanded add class hidden
			
		    if($(this).parent("li").parent('li').length == 0){ // if this is the first branch
		       if($(this).hasClass("actionBtn")){
		            $(this).html('Expand +');
			        var myPos = $(this).attr("rel");
		            stateArray[myPos] = "closed";
                   
		            if(countItems(stateArray,"open")==0){
			            $('#collapse_all').html('Expand all +');
			        }
			    }
		    }
		}
		else //else
		{
			$(this).parent("li").removeClass('hide').addClass('show'); // add class of expanded to this
			
			if($(this).parent("li").parent('li').length == 0){
			    if($(this).hasClass("actionBtn")){
			        $(this).html('Collapse -');
			        var myPos = $(this).attr("rel");
			        stateArray[myPos] = "open";
                    
		            if(countItems(stateArray,"open")==stateArray.length){
			            $('#collapse_all').html('Collapse all -');
			        }
			    }
			}
		}
	});
	//collapse all funciton
	$('#collapse_all').click(function(event){ //on collapse all button click
		if($(this).html() == 'Expand all +'){
		    $(this).html('Collapse all -');
		    $('#tableofcontents ul li.hideable').removeClass('hide').addClass('show'); //remove show class, add hide class
		    
		    $(this).siblings("ul").children("li:not(.leaf)").children("a").html("Collapse -");
		    stateArray = [];
	        $("#tableofcontents").children().each(function(){
	            stateArray.push("open");
	        });
	       
		}else{
		    $(this).html('Expand all +');
		    $('#tableofcontents ul li').removeClass('show').addClass('hide'); //remove show class, add hide class
		    $(this).siblings("ul").children("li:not(.leaf)").children("a").html("Expand +");
		    stateArray = [];
	        $("#tableofcontents").children().each(function(){
	            stateArray.push("closed");
	        });
	         
		}
	});

});

function countItems(arrayIn, stringToMatch){
    var count = 0;
    for(var i=0; i < arrayIn.length; i++){
        if(arrayIn[i] === stringToMatch){
            count++;
        }
    }
    return count;
}




