/**Tree**/
jQuery.fn.toggler = function(){	
	// SETTINGS
	var myid = new RegExp('controls_[a-zA-Z0-9_-]+').exec(this.attr("class"))[0].split("controls_")[1];
	var settings = {
		startclosed: this.is(".start_closed"),
		controlleeid: myid,
		controllee: "#" + myid,
		graphiccontrollerid: myid + "_graphic_controller",
		graphiccontroller: "#" + myid + "_graphic_controller"
	};
	console.log(settings.controllee);
	console.log(settings.startclosed);

	// VARIABLES

  // SETUP
  // add toggle expand/collapse links
  if (settings.startclosed) {	  
    $(settings.controllee).hide();
    $(this).before("<a href='#' id='"+settings.graphiccontrollerid+"' class='toggler_icon expand' title='Expand'><span>+</span></a>&nbsp;");
		} else {
		  $(this).before("<a href='#' id='"+settings.graphiccontrollerid+"' class='toggler_icon collapse' title='Collapse'><span>-</span></a>&nbsp;");
	  };

  
	// bind expand/contract events
	$(settings.graphiccontroller).click(function() { expandcollapse();return false; });
	$(this).click(function() { expandcollapse();return false; });
	
  // FUNCTIONS	
	var expandcollapse = function() {
    if ($(settings.graphiccontroller).is(".expand")) {
	    expand();
	  } else if ($(settings.graphiccontroller).is(".collapse")) {
	    collapse();
  	};
  };
  
	var expand = function() {
    $(settings.controllee).slideDown(250).end();
    $(settings.graphiccontroller).removeClass("expand").addClass("collapse");
    $(settings.graphiccontroller).find('span').empty().prepend("-");
  };
  
	var collapse = function() {
    $(settings.controllee).slideUp(250).end();
    $(settings.graphiccontroller).removeClass("collapse").addClass("expand");
    $(settings.graphiccontroller).find('span').empty().prepend("+");
  };
  

};

$(document).ready(function() {
  $('a.toggler').each(function(i){
   $(this).toggler();
  });
});
