$(document).ready(function(){
	var o=$("#startExpand").val();
	//more advanced stuff for which categories to expand
	var path=window.location.href.split("#");
	if(path.length>1){
		o=path[1];
	}
	setCurrentExpand(o);
	setupPage(o);
	$("#expandAll").click(expandAll);
	$("#closeAll").click(closeAll);
});
function setCurrentExpand(ce){
	$("#currentExpand").val(ce);
	if(ce=="all"){
		$("#closeAll").show();
		$("#expandAll").hide();
	}
	else if(ce==""){
		$("#closeAll").hide();
		$("#expandAll").show();		
	}
	else{
		$("#closeAll").show();
		$("#expandAll").show();		
	}
	if(ce=="" || ce.charAt(0)!="#")ce="#"+ce;
	window.location.href=ce;
}

function setupPage(open){
	if(open=="all")return;
	var oarr=open.split(",");
	var clist=$("ul.catLinks");
	for(var i=0; i<clist.length; i++){
		var c=$(clist[i]); //the category's list of links
		var cid=c.attr("id").replace("categoryLinks","");
		if(jQuery.inArray(cid,oarr)<0)
			c.hide();

	}
}

function categoryClick(catid){
	if($("#categoryLinks"+catid+":visible").length>0){
		//it's already visible, hide it
		$("#categoryLinks"+catid).slideUp();
		//take the catid out of the currentExpand variable
		var ids=$("#currentExpand").val().split(",");
		var ce="";
		if(ids[0]=="all"){
			//set ce to all ids
			ids=[];
			$("ul.catLinks").each(function(i){
				if(ce!="")ce+=",";
				var l=$(this).attr("id").replace("categoryLinks","");
				if(l!=catid)
					ce+=l;
			});
		}
		for(var i=0; i<ids.length; i++){
			if(ids[i]==catid || ids[i]=="")continue;//take out this category id
			if(ce!="")ce+=",";
			ce+=ids[i];
		}
		setCurrentExpand(ce);
		return;
	}
	var ce=$("#currentExpand").val();
	if(parseInt(ce)<0)ce="";
	if(ce.lastIndexOf(",")!=ce.length-1)ce+=",";
	setCurrentExpand(ce+catid);
	$("#categoryLinks"+catid).slideDown('normal',consolidateIds);
}
function consolidateIds(){
	if($("ul.catLinks").length==$("ul.catLinks:visible").length)
		setCurrentExpand("all"); //if they're all open, remove the id list and set it to all instead
}
function expandAll(evt){
	evt.preventDefault();
	$("ul.catLinks:hidden").slideDown();
	setCurrentExpand("all");
	$("#expandAll").hide();
	$("#closeAll").show();
}

function closeAll(evt){
	evt.preventDefault();
	$("ul.catLinks:visible").slideUp();
	setCurrentExpand("");
	$("#expandAll").show();
	$("#closeAll").hide();
}
