

$(function() {
  $("#browser1").addClass("treeview");
  $("#browser1").empty();
  $("#browser2").addClass("treeview");
  $("#browser2").empty();
  $.each(coursePartnerTree, createNode, [$("#browser1")]);
  $.each(courseCategoryTree, createNode, [$("#browser2")]);

  var onToggle = function(treeData) {
    var $this = $(this);
    if (!$this.hasClass("hasChildren")) {
      var node = findInTree(treeData, this.id);
      if (node && node.hasChildren) {
        // if there is only one course group, do not display it - display the children
        if (node.typeName == "Partner" && node.children.length == 1) {
          node = node.children[0];
        }
        $this.addClass("hasChildren");
        var branch = $this.find("ul");
        $.each(node.children, function() {
          var added = createNode.call(this, branch);
        });
        $this.parents(".treeview").treeview({ add: branch });
      }
    }
  }

  $("#browser1").treeview({ collapsed: true, toggle: function() { onToggle.call(this, [coursePartnerTree]) } });
  $("#browser2").treeview({ collapsed: true, toggle: function() { onToggle.call(this, [courseCategoryTree]) } });

  $(".treeview span.course").live("click", function() {
    var url = $(this).parent().attr("href")
    window.location = encodeURI(url);
    return false;
  });
});

function buildCourseUrl(node) {
  var url = courseShowUrl;
  url = url.replace("9999999", node.pkid);
  url = url.replace("_data_", node.attributes["FriendlyUrl"]);
  return url;
}

function createNode(parent) {
  var current;
  if (this.typeName == "Course") {
    current = $("<li/>").attr("id", this.id || "").attr("href", buildCourseUrl(this)).html("<span>" + '【'  + this.attributes.CourseId + '】' + this.text + "</span>");
  }
  else {
    current = $("<li/>").attr("id", this.id || "").html("<span>" + this.text + "</span>");
  }
  current.appendTo(parent);
  current.children("span").addClass(this.typeName.toLowerCase());
  
  if (this.expanded) {
	  current.addClass("open");
  }
  
  if (this.hasChildren || this.children && this.children.length) {
	  var branch = $("<ul/>").appendTo(current);
	  if (this.hasChildren) {
	  }
  }
  return current;
}

function findInTree(node, id) {
  var found = null;
  if ($.isArray(node)) {
    var i;
    for (i=0; i < node.length; i++) {
      found = findInTree(node[i], id);
      if (found) break;
    }
  }
  else {
    if (node.id == id) {
      found = node;
    }
    else {
      if (node.hasChildren) {
        found = findInTree(node.children, id);
      }
    }
  }
  return found;
}	  

